Skip to content

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

- more attributes for search progress bar - moved cache strategy to cora package

orbiter115abc891779
diff --git a/htroot/Bookmarks.java b/htroot/Bookmarks.java
index 473bf6438..e4e611c05 100644
--- a/htroot/Bookmarks.java
+++ b/htroot/Bookmarks.java
@@ -1,4 +1,4 @@
-// Bookmarks_p.java
+// Bookmarks_p.java
// -----------------------
// part of YACY
// (C) by Michael Peter Christen; [email protected]
@@ -35,19 +35,19 @@ import java.net.MalformedURLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.Map;
import java.util.Set;
import net.yacy.cora.date.ISO8601Formatter;
import net.yacy.cora.document.ASCII;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Document;
import net.yacy.document.Parser;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.logging.Log;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.data.BookmarkHelper;
import de.anomic.data.BookmarksDB;
import de.anomic.data.BookmarksDB.Bookmark;
@@ -59,7 +59,6 @@ import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyNewsPool;
-import java.util.Map;
public class Bookmarks {
@@ -67,14 +66,14 @@ public class Bookmarks {
private static final serverObjects prop = new serverObjects();
private static Switchboard sb = null;
private static UserDB.Entry user = null;
- private static boolean isAdmin = false;
+ private static boolean isAdmin = false;
final static int SORT_ALPHA = 1;
final static int SORT_SIZE = 2;
final static int SHOW_ALL = -1;
final static boolean TAGS = false;
final static boolean FOLDERS = true;
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
int max_count = 10;
@@ -82,12 +81,12 @@ public class Bookmarks {
int display = 0;
String tagName = "";
String username="";
-
+
prop.clear();
sb = (Switchboard) env;
- user = sb.userDB.getUser(header);
+ user = sb.userDB.getUser(header);
isAdmin = (sb.verifyAuthentication(header, true) || user!= null && user.hasRight(UserDB.AccessRight.BOOKMARK_RIGHT));
-
+
// set user name
if (user != null) {
username=user.getUserName();
@@ -95,16 +94,16 @@ public class Bookmarks {
username="admin";
}
prop.putHTML("user", username);
-
+
//redirect to userpage
/*
if(username!="" &&(post == null || !post.containsKey("user") && !post.containsKey("mode")))
prop.put("LOCATION", "/Bookmarks.html?user="+username);
*/
-
+
// set peer address
prop.put("address", sb.peers.mySeed().getPublicAddress());
-
+
//defaultvalues
if(isAdmin) {
prop.put("mode", "1");
@@ -123,7 +122,7 @@ public class Bookmarks {
prop.put("mode_path", "");
prop.put("mode_public", "1"); //1=is public
prop.put("mode_feed", "0"); //no newsfeed
-
+
if (post != null) {
if (!isAdmin) {
if(post.containsKey("login")){
@@ -173,7 +172,7 @@ public class Bookmarks {
} else {
bookmark.setFeed(false);
}
-
+
bookmark.setTags(tags, true);
sb.bookmarksDB.saveBookmark(bookmark);
}
@@ -199,7 +198,7 @@ public class Bookmarks {
final URIMetadataRow urlentry = sb.indexSegments.urlMetadata(Segments.Process.PUBLIC).load(ASCII.getBytes(urlHash));
if (urlentry != null) try {
final URIMetadataRow.Components metadata = urlentry.metadata();
- final Document document = Document.mergeDocuments(metadata.url(), null, sb.loader.loadDocuments(sb.loader.request(metadata.url(), true, false), CrawlProfile.CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE));
+ final Document document = Document.mergeDocuments(metadata.url(), null, sb.loader.loadDocuments(sb.loader.request(metadata.url(), true, false), CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE));
prop.put("mode_edit", "0"); // create mode
prop.put("mode_url", metadata.url().toNormalform(false, true));
prop.putHTML("mode_title", metadata.dc_title());
@@ -209,7 +208,7 @@ public class Bookmarks {
prop.putHTML("mode_path","");
prop.put("mode_public", "0");
prop.put("mode_feed", "0"); //TODO: check if it IS a feed
- } catch (IOException e) {Log.logException(e);} catch (Parser.Failure e) {Log.logException(e);}
+ } catch (final IOException e) {Log.logException(e);} catch (final Parser.Failure e) {Log.logException(e);}
} else {
// get from the bookmark database
prop.put("mode_edit", "1"); // edit mode
@@ -224,7 +223,7 @@ public class Bookmarks {
} else {
prop.put("mode_public", "0");
}
-
+
if (bookmark.getFeed()) {
prop.put("mode_feed", "1");
} else {
@@ -239,7 +238,7 @@ public class Bookmarks {
if("".equals(tags)){
tags="unsorted";
}
-
+
Log.logInfo("BOOKMARKS", "Trying to import bookmarks from HTML-file");
try {
@@ -273,23 +272,23 @@ public class Bookmarks {
max_count = post.getInt("num", 10);
}
} // END if(post != null)
-
+
if (display == 0) {
-
+
//-----------------------
// create tag list
//-----------------------
printTagList("taglist", tagName, SORT_SIZE, 25, false);
printTagList("optlist", tagName, SORT_ALPHA, SHOW_ALL, true);
-
+
//-----------------------
// create bookmark list
//-----------------------
int count = 0;
- Iterator<String> it = null;
+ Iterator<String> it = null;
prop.put("display_num-bookmarks", sb.bookmarksDB.bookmarksSize());
-
+
if(!"".equals(tagName)){
prop.put("display_selected", "");
it = sb.bookmarksDB.getBookmarksIterator(tagName, isAdmin);
@@ -297,18 +296,18 @@ public class Bookmarks {
prop.put("display_selected", " selected=\"selected\"");
it = sb.bookmarksDB.getBookmarksIterator(isAdmin);
}
-
+
//skip the first entries (display next page)
count = 0;
while(count < start && it.hasNext()){
it.next();
count++;
}
-
+
count = 0;
while(count < max_count && it.hasNext()) {
final Bookmark bookmark = sb.bookmarksDB.getBookmark(it.next());
-
+
if (bookmark != null){
if (bookmark.getFeed() && isAdmin) {
prop.put("display_bookmarks_"+count+"_link", "/FeedReader_p.html?url="+bookmark.getUrl());
@@ -320,7 +319,7 @@ public class Bookmarks {
prop.put("display_bookmarks_"+count+"_date", ISO8601Formatter.FORMATTER.format(new Date(bookmark.getTimeStamp())));
prop.put("display_bookmarks_"+count+"_rfc822date", HeaderFramework.formatRFC1123(new Date(bookmark.getTimeStamp())));
prop.put("display_bookmarks_"+count+"_public", (bookmark.getPublic() ? "1" : "0"));
-
+
//List Tags.
final Set<String> tags = bookmark.getTags();
int tagCount=0;
@@ -356,29 +355,29 @@ public class Bookmarks {
prop.put("display_prev-page_num", max_count);
}
prop.put("display_bookmarks", count);
-
-
+
+
//-----------------------
// create folder list
//-----------------------
-
+
count = 0;
count = recurseFolders(BookmarkHelper.getFolderList("/", sb.bookmarksDB.getTagIterator(isAdmin)), "/", 0, true, "");
prop.put("display_folderlist", count);
}
return prop; // return from serverObjects respond()
- }
-
- private static void printTagList(final String id, final String tagName, final int comp, final int max, final boolean opt){
-
+ }
+
+ private static void printTagList(final String id, final String tagName, final int comp, final int max, final boolean opt){
+
if (sb.bookmarksDB == null) {
- prop.put("display_"+id, 0);
+ prop.put("display_"+id, 0);
return;
}
-
+
int count=0;
final Iterator<BookmarksDB.Tag> it;
-
+
if ("".equals(tagName)) {
it = sb.bookmarksDB.getTagIterator(isAdmin, comp, max);
} else {
@@ -404,11 +403,11 @@ public class Bookmarks {
count++;
}
}
- prop.put("display_"+id, count);
+ prop.put("display_"+id, count);
}
-
+
private static int recurseFolders(final Iterator<String> it, String root, int count, final boolean next, final String prev) {
-
+
final String fn = (next) ? it.next() : prev;
if("\uffff".equals(fn)) {
@@ -420,14 +419,14 @@ public class Bookmarks {
}
return count;
}
-
+
if (fn.startsWith(("/".equals(root) ? root : root + "/"))) {
prop.put("display_folderlist_"+count+"_folder", "<li>"+fn.replaceFirst(root+"/*","")+"<ul class=\"folder\">");
count++;
final Iterator<String> bit = sb.bookmarksDB.getBookmarksIterator(fn, isAdmin);
while (bit.hasNext()) {
- Bookmark bookmark=sb.bookmarksDB.getBookmark(bit.next());
+ final Bookmark bookmark=sb.bookmarksDB.getBookmark(bit.next());
if(bookmark == null) {
break;
}
@@ -439,7 +438,7 @@ public class Bookmarks {
count = recurseFolders(it, fn, count, true, fn);
}
- } else {
+ } else {
prop.put("display_folderlist_"+count+"_folder", "</ul></li>");
count++;
root = root.replaceAll("(/.[^/]*$)", "");
@@ -447,7 +446,7 @@ public class Bookmarks {
root = "/";
}
count = recurseFolders(it, root, count, false, fn);
- }
+ }
return count;
}
diff --git a/htroot/Crawler_p.java b/htroot/Crawler_p.java
index d4f46a508..1253400da 100644
--- a/htroot/Crawler_p.java
+++ b/htroot/Crawler_p.java
@@ -10,7 +10,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -41,20 +41,20 @@ import java.util.regex.PatternSyntaxException;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.document.parser.html.TransformerWriter;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
-
import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.SitemapImporter;
import de.anomic.crawler.ZURL.FailCategory;
import de.anomic.crawler.retrieval.Request;
import de.anomic.data.BookmarkHelper;
-import de.anomic.data.WorkTables;
import de.anomic.data.BookmarksDB;
import de.anomic.data.ListManager;
+import de.anomic.data.WorkTables;
import de.anomic.search.Segment;
import de.anomic.search.Segments;
import de.anomic.search.Switchboard;
@@ -67,17 +67,17 @@ public class Crawler_p {
// this servlet does NOT create the Crawler servlet page content!
// this servlet starts a web crawl. The interface for entering the web crawl parameters is in IndexCreate_p.html
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
- // inital values for AJAX Elements (without JavaScript)
+ // inital values for AJAX Elements (without JavaScript)
final serverObjects prop = new serverObjects();
prop.put("rejected", 0);
prop.put("urlpublictextSize", 0);
prop.put("rwipublictextSize", 0);
prop.put("list", "0");
- prop.put("loaderSize", 0);
+ prop.put("loaderSize", 0);
prop.put("loaderMax", 0);
prop.put("list-loader", 0);
prop.put("localCrawlSize", sb.crawlQueues.coreCrawlJobSize());
@@ -88,11 +88,11 @@ public class Crawler_p {
prop.put("remoteCrawlState", "");
prop.put("list-remote", 0);
prop.put("forwardToCrawlStart", "0");
-
+
// get segment
Segment indexSegment = null;
if (post != null && post.containsKey("segment")) {
- String segmentName = post.get("segment");
+ final String segmentName = post.get("segment");
if (sb.indexSegments.segmentExist(segmentName)) {
indexSegment = sb.indexSegments.segment(segmentName);
}
@@ -100,9 +100,9 @@ public class Crawler_p {
// take default segment
indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
}
-
+
prop.put("info", "0");
-
+
if (post != null && post.containsKey("continue")) {
// continue queue
final String queue = post.get("continue", "");
@@ -122,7 +122,7 @@ public class Crawler_p {
sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
}
}
-
+
if (post != null && post.containsKey("crawlingstart")) {
// init crawl
if (sb.peers == null) {
@@ -142,19 +142,19 @@ public class Crawler_p {
if (crawlingFile != null && crawlingFile.exists()) {
post.remove("crawlingFile$file");
}
-
+
// normalize URL
DigestURI crawlingStartURL = null;
if (crawlingFile == null) try {crawlingStartURL = new DigestURI(crawlingStart);} catch (final MalformedURLException e1) {Log.logException(e1);}
crawlingStart = (crawlingStartURL == null) ? null : crawlingStartURL.toNormalform(true, true);
-
+
// set new properties
final boolean fullDomain = "domain".equals(post.get("range", "wide")); // special property in simple crawl start
final boolean subPath = "subpath".equals(post.get("range", "wide")); // special property in simple crawl start
-
+
// set the crawl filter
String newcrawlingMustMatch = post.get("mustmatch", CrawlProfile.MATCH_ALL);
- String newcrawlingMustNotMatch = post.get("mustnotmatch", CrawlProfile.MATCH_NEVER);
+ final String newcrawlingMustNotMatch = post.get("mustnotmatch", CrawlProfile.MATCH_NEVER);
if (newcrawlingMustMatch.length() < 2) newcrawlingMustMatch = CrawlProfile.MATCH_ALL; // avoid that all urls are filtered out if bad value was submitted
// special cases:
if (crawlingStartURL!= null && fullDomain) {
@@ -171,14 +171,14 @@ public class Crawler_p {
if (crawlingStart!= null && subPath && (pos = crawlingStart.lastIndexOf('/')) > 0) {
newcrawlingMustMatch = crawlingStart.substring(0, pos + 1) + ".*";
}
-
+
final boolean crawlOrder = post.get("crawlOrder", "off").equals("on");
env.setConfig("crawlOrder", crawlOrder);
-
+
int newcrawlingdepth = post.getInt("crawlingDepth", 8);
env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth));
if ((crawlOrder) && (newcrawlingdepth > 8)) newcrawlingdepth = 8;
-
+
// recrawl
final String recrawl = post.get("recrawl", "nodoubles"); // nodoubles, reload, scheduler
boolean crawlingIfOlderCheck = "on".equals(post.get("crawlingIfOlderCheck", "off"));
@@ -186,9 +186,9 @@ public class Crawler_p {
String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year"); // year, month, day, hour
int repeat_time = post.getInt("repeat_time", -1);
final String repeat_unit = post.get("repeat_unit", "seldays"); // selminutes, selhours, seldays
-
+
if ("scheduler".equals(recrawl) && repeat_time > 0) {
- // set crawlingIfOlder attributes that are appropriate for scheduled crawling
+ // set crawlingIfOlder attributes that are appropriate for scheduled crawling
crawlingIfOlderCheck = true;
crawlingIfOlderNumber = "selminutes".equals(repeat_unit) ? 1 : "selhours".equals(repeat_unit) ? repeat_time / 2 : repeat_time * 12;
crawlingIfOlderUnit = "hour";
@@ -199,7 +199,7 @@ public class Crawler_p {
repeat_time = -1;
crawlingIfOlderCheck = false;
}
- long crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit);
+ final long crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit);
env.setConfig("crawlingIfOlder", crawlingIfOlder);
// store this call as api call
@@ -209,37 +209,37 @@ public class Crawler_p {
} else {
// store just a protocol
sb.tables.recordAPICall(post, "Crawler_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "crawl start for " + ((crawlingStart == null) ? post.get("crawlingFile", "") : crawlingStart));
- }
-
+ }
+
final boolean crawlingDomMaxCheck = "on".equals(post.get("crawlingDomMaxCheck", "off"));
final int crawlingDomMaxPages = (crawlingDomMaxCheck) ? post.getInt("crawlingDomMaxPages", -1) : -1;
env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages));
-
+
final boolean crawlingQ = "on".equals(post.get("crawlingQ", "off"));
env.setConfig("crawlingQ", crawlingQ);
-
+
final boolean indexText = "on".equals(post.get("indexText", "on"));
env.setConfig("indexText", indexText);
-
+
final boolean indexMedia = "on".equals(post.get("indexMedia", "on"));
env.setConfig("indexMedia", indexMedia);
-
+
boolean storeHTCache = "on".equals(post.get("storeHTCache", "on"));
if (crawlingStartURL!= null &&(crawlingStartURL.isFile() || crawlingStartURL.isSMB())) storeHTCache = false;
env.setConfig("storeHTCache", storeHTCache);
-
- CrawlProfile.CacheStrategy cachePolicy = CrawlProfile.CacheStrategy.parse(post.get("cachePolicy", "iffresh"));
- if (cachePolicy == null) cachePolicy = CrawlProfile.CacheStrategy.IFFRESH;
-
+
+ CacheStrategy cachePolicy = CacheStrategy.parse(post.get("cachePolicy", "iffresh"));
+ if (cachePolicy == null) cachePolicy = CacheStrategy.IFFRESH;
+
final boolean xsstopw = "on".equals(post.get("xsstopw", "off"));
env.setConfig("xsstopw", xsstopw);
-
+
final boolean xdstopw = "on".equals(post.get("xdstopw", "off"));
env.setConfig("xdstopw", xdstopw);
-
+
final boolean xpstopw = "on".equals(post.get("xpstopw", "off"));
env.setConfig("xpstopw", xpstopw);
-
+
final String crawlingMode = post.get("crawlingMode","url");
if (crawlingStart != null && crawlingStart.startsWith("ftp")) {
try {
@@ -279,7 +279,7 @@ public class Crawler_p {
}
sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL);
} else if ("url".equals(crawlingMode)) {
-
+
// check if pattern matches
if ((crawlingStart == null || crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) {
// print error message
@@ -287,10 +287,10 @@ public class Crawler_p {
prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch);
prop.putHTML("info_crawlingStart", crawlingStart);
} else try {
-
+
// check if the crawl filter works correctly
Pattern.compile(newcrawlingMustMatch);
-
+
// stack request
// first delete old entry, if exists
final DigestURI url = new DigestURI(crawlingStart);
@@ -298,7 +298,7 @@ public class Crawler_p {
indexSegment.urlMetadata().remove(urlhash);
sb.crawlQueues.noticeURL.removeByURLHash(urlhash);
sb.crawlQueues.errorURL.remove(urlhash);
-
+
// stack url
sb.crawler.removePassive(crawlingStartURL.hash()); // if there is an old entry, delete it
final CrawlProfile pe = new CrawlProfile(
@@ -330,13 +330,13 @@ public class Crawler_p {
0,
0
));
-
+
if (reasonString == null) {
// create a bookmark from crawl start url
- Set<String> tags=ListManager.string2set(BookmarkHelper.cleanTagsString(post.get("bookmarkFolder","/crawlStart")));
+ final Set<String> tags=ListManager.string2set(BookmarkHelper.cleanTagsString(post.get("bookmarkFolder","/crawlStart")));
tags.add("crawlStart");
if ("on".equals(post.get("createBookmark","off"))) {
- BookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(crawlingStart, "admin");
+ final BookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(crawlingStart, "admin");
if (bookmark != null) {
bookmark.setProperty(BookmarksDB.Bookmark.BOOKMARK_TITLE, post.get("bookmarkTitle", crawlingStart));
bookmark.setOwner("admin");
@@ -348,7 +348,7 @@ public class Crawler_p {
// liftoff!
prop.put("info", "8");//start msg
prop.putHTML("info_crawlingURL", (post.get("crawlingURL")));
-
+
// generate a YaCyNews if the global flag was set
if (!sb.isRobinsonMode() && crawlOrder) {
final Map<String, String> m = new HashMap<String, String>(pe); // must be cloned
@@ -365,12 +365,12 @@ public class Crawler_p {
m.remove("specificFilter");
m.put("intention", post.get("intention", "").replace(',', '/'));
sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), yacyNewsPool.CATEGORY_CRAWL_START, m);
- }
+ }
} else {
prop.put("info", "5"); //Crawling failed
prop.putHTML("info_crawlingURL", (post.get("crawlingURL")));
prop.putHTML("info_reasonString", reasonString);
-
+
sb.crawlQueues.errorURL.push(
new Request(
sb.peers.mySeed().hash.getBytes(),
@@ -400,7 +400,7 @@ public class Crawler_p {
prop.putHTML("info_error", e.getMessage());
Log.logException(e);
}
-
+
} else if ("file".equals(crawlingMode)) {
if (post.containsKey("crawlingFile")) {
final String crawlingFileContent = post.get("crawlingFile$file", "");
@@ -415,11 +415,11 @@ public class Crawler_p {
FileUtils.copy(crawlingFileContent, writer);
}
writer.close();
-
+
// get links and generate filter
final Map<MultiProtocolURI, Properties> hyperlinks = scraper.getAnchors();
if (fullDomain && newcrawlingdepth > 0) newcrawlingMustMatch = siteFilter(hyperlinks.keySet());
-
+
final DigestURI crawlURL = new DigestURI("file://" + crawlingFile.toString());
final CrawlProfile profile = new CrawlProfile(
crawlingFileName,
@@ -455,7 +455,7 @@ public class Crawler_p {
sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL);
}
} else if ("sitemap".equals(crawlingMode)) {
- String sitemapURLStr = post.get("sitemapURL","");
+ final String sitemapURLStr = post.get("sitemapURL","");
try {
final DigestURI sitemapURL = new DigestURI(sitemapURLStr);
final CrawlProfile pe = new CrawlProfile(
@@ -490,10 +490,10 @@ public class Crawler_p {
final DigestURI sitelistURL = new DigestURI(crawlingStart);
// download document
ContentScraper scraper = null;
- scraper = sb.loader.parseResource(sitelistURL, CrawlProfile.CacheStrategy.IFFRESH);
+ scraper = sb.loader.parseResource(sitelistURL, CacheStrategy.IFFRESH);
// String title = scraper.getTitle();
// String description = scraper.getDescription();
-
+
// get links and generate filter
final Map<MultiProtocolURI, Properties> hyperlinks = scraper.getAnchors();
if (fullDomain && newcrawlingdepth > 0) newcrawlingMustMatch = siteFilter(hyperlinks.keySet());
@@ -530,10 +530,10 @@ public class Crawler_p {
sb.crawlQueues.noticeURL.removeByURLHash(urlhash);
sb.crawlQueues.errorURL.remove(urlhash);
sb.crawlStacker.enqueueEntry(new Request(
- sb.peers.mySeed().hash.getBytes(),
- nexturl,
- null,
- e.getValue().getProperty("name", ""),
+ sb.peers.mySeed().hash.getBytes(),
+ nexturl,
+ null,
+ e.getValue().getProperty("name", ""),
new Date(),
profile.handle(),
0,
@@ -552,11 +552,11 @@ public class Crawler_p {
}
}
}
-
+
if (post != null && post.containsKey("crawlingPerformance")) {
setPerformance(sb, post);
}
-
+
// performance settings
final long LCbusySleep = env.getConfigLong(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, 1000L);
final int LCppm = (int) (60000L / Math.max(1,LCbusySleep));
@@ -564,11 +564,11 @@ public class Crawler_p {
prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 30000)) ? "1" : "0");
prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? "1" : "0");
prop.put("customPPMdefault", Integer.toString(LCppm));
-
+
// return rewrite properties
return prop;
}
-
+
private static long recrawlIfOlderC(final boolean recrawlIfOlderCheck, final int recrawlIfOlderNumber, final String crawlingIfOlderUnit) {
if (!recrawlIfOlderCheck) return 0L;
if ("year".equals(crawlingIfOlderUnit)) return System.currentTimeMillis() - (long) recrawlIfOlderNumber * 1000L * 60L * 60L * 24L * 365L;
@@ -577,7 +577,7 @@ public class Crawler_p {
if ("hour".equals(crawlingIfOlderUnit)) return System.currentTimeMillis() - (long) recrawlIfOlderNumber * 1000L * 60L * 60L;
return System.currentTimeMillis() - (long) recrawlIfOlderNumber;
}
-
+
private static void setPerformance(final Switchboard sb, final serverObjects post) {
final String crawlingPerformance = post.get("crawlingPerformance", "custom");
final long LCbusySleep = sb.getConfigLong(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, 1000L);
@@ -589,8 +589,8 @@ public class Crawler_p {
if ("maximum".equals(crawlingPerformance.toLowerCase())) wantedPPM = 30000;
sb.setPerformance(wantedPPM);
}
-
- private static String siteFilter(Set<MultiProtocolURI> uris) {
+
+ private static String siteFilter(final Set<MultiProtocolURI> uris) {
final StringBuilder filter = new StringBuilder();
final Set<String> filterSet = new HashSet<String>();
for (final MultiProtocolURI uri: uris) {
diff --git a/htroot/DictionaryLoader_p.java b/htroot/DictionaryLoader_p.java
index 9928e5e18..b9f21da20 100644
--- a/htroot/DictionaryLoader_p.java
+++ b/htroot/DictionaryLoader_p.java
@@ -22,13 +22,13 @@ import java.io.IOException;
import java.net.MalformedURLException;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.LibraryProvider;
import net.yacy.document.geolocalization.GeonamesLocalization;
import net.yacy.document.geolocalization.OpenGeoDBLocalization;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
@@ -39,15 +39,15 @@ public class DictionaryLoader_p {
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects(); // return variable that accumulates replacements
-
+
/*
* distinguish the following cases:
* - dictionary file was not loaded -> actions: load the file
* - dictionary file is loaded and enabled -> actions: disable or remove the file
* - dictionary file is loaded but disabled -> actions: enable or remove the file
*/
-
- for (LibraryProvider.Dictionary dictionary: LibraryProvider.Dictionary.values()) {
+
+ for (final LibraryProvider.Dictionary dictionary: LibraryProvider.Dictionary.values()) {
prop.put(dictionary.nickname + "URL", dictionary.url);
prop.put(dictionary.nickname + "Storage", dictionary.file().toString());
prop.put(dictionary.nickname + "Status", dictionary.file().exists() ? 1 : dictionary.fileDisabled().exists() ? 2 : 0);
@@ -56,95 +56,95 @@ public class DictionaryLoader_p {
prop.put(dictionary.nickname + "ActionActivated", 0);
prop.put(dictionary.nickname + "ActionDeactivated", 0);
}
-
+
if (post == null) return prop;
-
+
// GEON0
if (post.containsKey("geon0Load")) {
// load from the net
try {
- Response response = sb.loader.load(sb.loader.request(new DigestURI(LibraryProvider.Dictionary.GEON0.url), false, true), CrawlProfile.CacheStrategy.NOCACHE, Long.MAX_VALUE, false);
- byte[] b = response.getContent();
+ final Response response = sb.loader.load(sb.loader.request(new DigestURI(LibraryProvider.Dictionary.GEON0.url), false, true), CacheStrategy.NOCACHE, Long.MAX_VALUE, false);
+ final byte[] b = response.getContent();
FileUtils.copy(b, LibraryProvider.Dictionary.GEON0.file());
LibraryProvider.geoLoc.addLocalization(LibraryProvider.Dictionary.GEON0.nickname, new GeonamesLocalization(LibraryProvider.Dictionary.GEON0.file()));
prop.put("geon0Status", LibraryProvider.Dictionary.GEON0.file().exists() ? 1 : 0);
prop.put("geon0ActionLoaded", 1);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logException(e);
prop.put("geon0ActionLoaded", 2);
prop.put("geon0ActionLoaded_error", e.getMessage());
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
prop.put("geon0ActionLoaded", 2);
prop.put("geon0ActionLoaded_error", e.getMessage());
}
}
-
+
if (post.containsKey("geon0Remove")) {
FileUtils.deletedelete(LibraryProvider.Dictionary.GEON0.file());
FileUtils.deletedelete(LibraryProvider.Dictionary.GEON0.fileDisabled());
LibraryProvider.geoLoc.removeLocalization(LibraryProvider.Dictionary.GEON0.nickname);
prop.put("geon0ActionRemoved", 1);
}
-
+
if (post.containsKey("geon0Deactivate")) {
LibraryProvider.Dictionary.GEON0.file().renameTo(LibraryProvider.Dictionary.GEON0.fileDisabled());
LibraryProvider.geoLoc.removeLocalization(LibraryProvider.Dictionary.GEON0.nickname);
prop.put("geon0ActionDeactivated", 1);
}
-
+
if (post.containsKey("geon0Activate")) {
LibraryProvider.Dictionary.GEON0.fileDisabled().renameTo(LibraryProvider.Dictionary.GEON0.file());
LibraryProvider.geoLoc.addLocalization(LibraryProvider.Dictionary.GEON0.nickname, new GeonamesLocalization(LibraryProvider.Dictionary.GEON0.file()));
prop.put("geon0ActionActivated", 1);
}
-
+
// GEO1
if (post.containsKey("geo1Load")) {
// load from the net
try {
- Response response = sb.loader.load(sb.loader.request(new DigestURI(LibraryProvider.Dictionary.GEODB1.url), false, true), CrawlProfile.CacheStrategy.NOCACHE, Long.MAX_VALUE, false);
- byte[] b = response.getContent();
+ final Response response = sb.loader.load(sb.loader.request(new DigestURI(LibraryProvider.Dictionary.GEODB1.url), false, true), CacheStrategy.NOCACHE, Long.MAX_VALUE, false);
+ final byte[] b = response.getContent();
FileUtils.copy(b, LibraryProvider.Dictionary.GEODB1.file());
LibraryProvider.geoLoc.removeLocalization(LibraryProvider.Dictionary.GEODB0.nickname);
LibraryProvider.geoLoc.addLocalization(LibraryProvider.Dictionary.GEODB1.nickname, new OpenGeoDBLocalization(LibraryProvider.Dictionary.GEODB1.file(), false));
prop.put("geo1Status", LibraryProvider.Dictionary.GEODB1.file().exists() ? 1 : 0);
prop.put("geo1ActionLoaded", 1);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logException(e);
prop.put("geo1ActionLoaded", 2);
prop.put("geo1ActionLoaded_error", e.getMessage());
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
prop.put("geo1ActionLoaded", 2);
prop.put("geo1ActionLoaded_error", e.getMessage());
}
}
-
+
if (post.containsKey("geo1Remove")) {
FileUtils.deletedelete(LibraryProvider.Dictionary.GEODB1.file());
FileUtils.deletedelete(LibraryProvider.Dictionary.GEODB1.fileDisabled());
LibraryProvider.geoLoc.removeLocalization(LibraryProvider.Dictionary.GEODB1.nickname);
prop.put("geo1ActionRemoved", 1);
}
-
+
if (post.containsKey("geo1Deactivate")) {
LibraryProvider.Dictionary.GEODB1.file().renameTo(LibraryProvider.Dictionary.GEODB1.fileDisabled());
LibraryProvider.geoLoc.removeLocalization(LibraryProvider.Dictionary.GEODB1.nickname);
prop.put("geo1ActionDeactivated", 1);
}
-
+
if (post.containsKey("geo1Activate")) {
LibraryProvider.Dictionary.GEODB1.fileDisabled().renameTo(LibraryProvider.Dictionary.GEODB1.file());
LibraryProvider.geoLoc.addLocalization(LibraryProvider.Dictionary.GEODB1.nickname, new OpenGeoDBLocalization(LibraryProvider.Dictionary.GEODB1.file(), false));
prop.put("geo1ActionActivated", 1);
}
-
+
// check status again
- for (LibraryProvider.Dictionary dictionary: LibraryProvider.Dictionary.values()) {
+ for (final LibraryProvider.Dictionary dictionary: LibraryProvider.Dictionary.values()) {
prop.put(dictionary.nickname + "Status", dictionary.file().exists() ? 1 : dictionary.fileDisabled().exists() ? 2 : 0);
}
-
+
return prop; // return rewrite values for templates
}
}
diff --git a/htroot/IndexControlRWIs_p.java b/htroot/IndexControlRWIs_p.java
index 05764736c..4d34a1430 100644
--- a/htroot/IndexControlRWIs_p.java
+++ b/htroot/IndexControlRWIs_p.java
@@ -10,7 +10,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -35,9 +35,10 @@ import java.util.List;
import java.util.TreeMap;
import net.yacy.cora.date.GenericFormatter;
+import net.yacy.cora.document.ASCII;
import net.yacy.cora.document.UTF8;
import net.yacy.cora.protocol.RequestHeader;
-import net.yacy.cora.document.ASCII;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
@@ -52,11 +53,9 @@ import net.yacy.kelondro.order.Bitfield;
import net.yacy.kelondro.rwi.Reference;
import net.yacy.kelondro.rwi.ReferenceContainer;
import net.yacy.kelondro.rwi.ReferenceContainerCache;
-import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.util.ByteBuffer;
+import net.yacy.kelondro.util.FileUtils;
import net.yacy.repository.Blacklist;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.ResultURLs;
import de.anomic.data.ListManager;
import de.anomic.data.WorkTables;
@@ -76,7 +75,7 @@ import de.anomic.yacy.yacySeed;
import de.anomic.yacy.dht.PeerSelection;
public class IndexControlRWIs_p {
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws IOException {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
@@ -88,46 +87,46 @@ public class IndexControlRWIs_p {
prop.put("result", "");
prop.put("cleanup", post == null ? 1 : 0);
prop.put("cleanup_solr", sb.solrConnector == null || !sb.getConfigBool("federated.service.solr.indexing.enabled", false) ? 0 : 1);
-
+
String segmentName = sb.getConfig(SwitchboardConstants.SEGMENT_PUBLIC, "default");
int i = 0;
- for (String s: sb.indexSegments.segmentNames()) {
+ for (final String s: sb.indexSegments.segmentNames()) {
prop.put("segments_" + i + "_name", s);
prop.put("segments_" + i + "_selected", (segmentName.equals(s)) ? 1 : 0);
i++;
}
Segment segment = sb.indexSegments.segment(segmentName);
prop.put("segments", i);
-
+
// switch off all optional forms/lists
prop.put("searchresult", 0);
prop.put("keyhashsimilar", 0);
prop.put("genUrlList", 0);
-
+
// clean up all search events
SearchEventCache.cleanupEvents(true);
-
+
if (post != null) {
// default values
segmentName = post.get("segment", segmentName).trim();
i= 0;
- for (String s: sb.indexSegments.segmentNames()) {
+ for (final String s: sb.indexSegments.segmentNames()) {
prop.put("segments_" + i + "_name", s);
prop.put("segments_" + i + "_selected", (segmentName.equals(s)) ? 1 : 0);
i++;
}
prop.put("segments", i);
segment = sb.indexSegments.segment(segmentName);
-
+
final String keystring = post.get("keystring", "").trim();
byte[] keyhash = post.get("keyhash", "").trim().getBytes();
prop.putHTML("keystring", keystring);
prop.putHTML("keyhash", ASCII.String(keyhash));
// read values from checkboxes
- String[] urls = post.getAll("urlhx.*");
+ final String[] urls = post.getAll("urlhx.*");
HandleSet urlb = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, urls.length);
- if (urls != null) for (String s: urls) try { urlb.put(s.getBytes()); } catch (RowSpaceExceededException e) { Log.logException(e); }
+ if (urls != null) for (final String s: urls) try { urlb.put(s.getBytes()); } catch (final RowSpaceExceededException e) { Log.logException(e); }
final boolean delurl = post.containsKey("delurl");
final boolean delurlref = post.containsKey("delurlref");
@@ -140,7 +139,7 @@ public class IndexControlRWIs_p {
prop.putHTML("searchresult_word", keystring);
}
}
-
+
if (post.containsKey("keyhashsearch")) {
if (keystring.length() == 0 || !ByteBuffer.equals(Word.word2hash(keystring), keyhash)) {
prop.put("keystring", "&lt;not possible to compute word from hash&gt;");
@@ -151,7 +150,7 @@ public class IndexControlRWIs_p {
prop.putHTML("searchresult_wordhash", ASCII.String(keyhash));
}
}
-
+
// delete everything
if (post.containsKey("deletecomplete")) {
if (post.get("deleteIndex", "").equals("on")) {
@@ -159,7 +158,7 @@ public class IndexControlRWIs_p {
}
if (post.get("deleteSolr", "").equals("on") && sb.getConfigBool("federated.service.solr.indexing.enabled", false)) try {
sb.solrConnector.clear();
- } catch (Exception e) {
+ } catch (final Exception e) {
Log.logException(e);
}
if (post.get("deleteCrawlQueues", "").equals("on")) {
@@ -178,7 +177,7 @@ public class IndexControlRWIs_p {
}
post.remove("deletecomplete");
}
-
+
// delete word
if (post.containsKey("keyhashdeleteall")) try {
if (delurl || delurlref) {
@@ -187,43 +186,43 @@ public class IndexControlRWIs_p {
index = segment.termIndex().get(keyhash, null);
final Iterator<WordReference> en = index.entries();
urlb = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, index.size());
- while (en.hasNext()) try { urlb.put(en.next().urlhash()); } catch (RowSpaceExceededException e) { Log.logException(e); }
+ while (en.hasNext()) try { urlb.put(en.next().urlhash()); } catch (final RowSpaceExceededException e) { Log.logException(e); }
index = null;
}
if (delurlref) {
- segment.removeAllUrlReferences(urlb, sb.loader, CrawlProfile.CacheStrategy.IFEXIST);
+ segment.removeAllUrlReferences(urlb, sb.loader, CacheStrategy.IFEXIST);
}
// delete the word first because that is much faster than the deletion of the urls from the url database
segment.termIndex().delete(keyhash);
// now delete all urls if demanded
if (delurl || delurlref) {
- for (byte[] b: urlb) sb.urlRemove(segment, b);
+ for (final byte[] b: urlb) sb.urlRemove(segment, b);
}
post.remove("keyhashdeleteall");
post.put("urllist", "generated");
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
-
+
// delete selected URLs
if (post.containsKey("keyhashdelete")) try {
if (delurlref) {
- segment.removeAllUrlReferences(urlb, sb.loader, CrawlProfile.CacheStrategy.IFEXIST);
+ segment.removeAllUrlReferences(urlb, sb.loader, CacheStrategy.IFEXIST);
}
if (delurl || delurlref) {
- for (byte[] b: urlb) sb.urlRemove(segment, b);
+ for (final byte[] b: urlb) sb.urlRemove(segment, b);
}
final HandleSet urlHashes = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 0);
- for (byte[] b: urlb) try { urlHashes.put(b); } catch (RowSpaceExceededException e) { Log.logException(e); }
+ for (final byte[] b: urlb) try { urlHashes.put(b); } catch (final RowSpaceExceededException e) { Log.logException(e); }
segment.termIndex().remove(keyhash, urlHashes);
// this shall lead to a presentation of the list; so handle that the remaining program
// thinks that it was called for a list presentation
post.remove("keyhashdelete");
post.put("urllist", "generated");
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
-
+
if (post.containsKey("urllist")) {
if (keystring.length() == 0 || !ByteBuffer.equals(Word.word2hash(keystring), keyhash)) {
prop.put("keystring", "&lt;not possible to compute word from hash&gt;");
@@ -239,7 +238,7 @@ public class IndexControlRWIs_p {
if (keystring.length() == 0 || !ByteBuffer.equals(Word.word2hash(keystring), keyhash)) {
prop.put("keystring", "&lt;not possible to compute word from hash&gt;");
}
-
+
// find host & peer
String host = post.get("host", ""); // get host from input field
yacySeed seed = null;
@@ -255,7 +254,7 @@ public class IndexControlRWIs_p {
host = post.get("hostHash", ""); // if input field is empty, get from select box
seed = sb.peers.getConnected(host);
}
-
+
// prepare index
ReferenceContainer<WordReference> index;
final long starttime = System.currentTimeMillis();
@@ -272,7 +271,7 @@ public class IndexControlRWIs_p {
if (lurl == null) {
try {
unknownURLEntries.put(iEntry.urlhash());
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
urlIter.remove();
@@ -280,15 +279,15 @@ public class IndexControlRWIs_p {
knownURLs.put(iEntry.urlhash(), lurl);
}
}
-
+
// make an indexContainerCache
- ReferenceContainerCache<WordReference> icc = new ReferenceContainerCache<WordReference>(Segment.wordReferenceFactory, Segment.wordOrder, Word.commonHashLength);
+ final ReferenceContainerCache<WordReference> icc = new ReferenceContainerCache<WordReference>(Segment.wordReferenceFactory, Segment.wordOrder, Word.commonHashLength);
try {
icc.add(index);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
-
+
// transport to other peer
final boolean gzipBody = sb.getConfigBool("indexControl.gzipBody", false);
final int timeout = (int) sb.getConfigLong("indexControl.timeout", 60000);
@@ -300,10 +299,10 @@ public class IndexControlRWIs_p {
timeout);
prop.put("result", (error == null) ? ("Successfully transferred " + knownURLs.size() + " words in " + ((System.currentTimeMillis() - starttime) / 1000) + " seconds, " + unknownURLEntries.size() + " URL not found") : "error: " + error);
index = null;
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
-
+
// generate list
if (post.containsKey("keyhashsimilar")) try {
final Iterator<ReferenceContainer<WordReference>> containerIt = segment.termIndex().references(keyhash, true, 256, false).iterator();
@@ -325,10 +324,10 @@ public class IndexControlRWIs_p {
prop.put("keyhashsimilar_rows_"+rows+"_cols", cols);
prop.put("keyhashsimilar_rows", rows + 1);
prop.put("result", "");
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
-
+
if (post.containsKey("blacklist")) {
final String blacklist = post.get("blacklist", "");
final HandleSet urlHashes = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, urlb.size());
@@ -338,10 +337,10 @@ public class IndexControlRWIs_p {
final String[] supportedBlacklistTypes = env.getConfig("BlackLists.types", "").split(",");
pw = new PrintWriter(new FileWriter(new File(ListManager.listsPath, blacklist), true));
DigestURI url;
- for (byte[] b: urlb) {
+ for (final byte[] b: urlb) {
try {
urlHashes.put(b);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
final URIMetadataRow e = segment.urlMetadata().load(b);
@@ -349,13 +348,13 @@ public class IndexControlRWIs_p {
if (e != null) {
url = e.metadata().url();
pw.println(url.getHost() + "/" + url.getFile());
- for (int blTypes=0; blTypes < supportedBlacklistTypes.length; blTypes++) {
- if (ListManager.listSetContains(supportedBlacklistTypes[blTypes] + ".BlackLists", blacklist)) {
+ for (final String supportedBlacklistType : supportedBlacklistTypes) {
+ if (ListManager.listSetContains(supportedBlacklistType + ".BlackLists", blacklist)) {
Switchboard.urlBlacklist.add(
- supportedBlacklistTypes[blTypes],
+ supportedBlacklistType,
url.getHost(),
url.getFile());
- }
+ }
}
SearchEventCache.cleanupEvents(true);
}
@@ -364,17 +363,17 @@ public class IndexControlRWIs_p {
} catch (final IOException e) {
}
}
-
+
if (post.containsKey("blacklistdomains")) {
PrintWriter pw;
try {
final String[] supportedBlacklistTypes = Blacklist.BLACKLIST_TYPES_STRING.split(",");
pw = new PrintWriter(new FileWriter(new File(ListManager.listsPath, blacklist), true));
DigestURI url;
- for (byte[] b: urlb) {
+ for (final byte[] b: urlb) {
try {
urlHashes.put(b);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
final URIMetadataRow e = segment.urlMetadata().load(b);
@@ -382,12 +381,12 @@ public class IndexControlRWIs_p {
if (e != null) {
url = e.metadata().url();
pw.println(url.getHost() + "/.*");
- for (int blTypes=0; blTypes < supportedBlacklistTypes.length; blTypes++) {
- if (ListManager.listSetContains(supportedBlacklistTypes[blTypes] + ".BlackLists", blacklist)) {
+ for (final String supportedBlacklistType : supportedBlacklistTypes) {
+ if (ListManager.listSetContains(supportedBlacklistType + ".BlackLists", blacklist)) {
Switchboard.urlBlacklist.add(
- supportedBlacklistTypes[blTypes],
+ supportedBlacklistType,
url.getHost(), ".*");
- }
+ }
}
}
}
@@ -397,26 +396,26 @@ public class IndexControlRWIs_p {
}
try {
segment.termIndex().remove(keyhash, urlHashes);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
-
+
if (prop.getInt("searchresult", 0) == 3) listHosts(prop, keyhash, sb);
}
-
+
// insert constants
prop.putNum("wcount", segment.termIndex().sizesMax());
// return rewrite properties
return prop;
}
-
+
public static void genURLList(final serverObjects prop, final byte[] keyhash, final String keystring, final RankingProcess ranked, final Bitfield flags, final int maxlines) {
// search for a word hash and generate a list of url links
- String keyhashs = ASCII.String(keyhash);
+ final String keyhashs = ASCII.String(keyhash);
prop.put("genUrlList_keyHash", keyhashs);
-
+
if (ranked.filteredCount() == 0) {
prop.put("genUrlList", 1);
prop.put("genUrlList_count", 0);
@@ -498,14 +497,14 @@ public class IndexControlRWIs_p {
putBlacklists(prop, FileUtils.getDirListing(ListManager.listsPath));
}
}
-
+
public static void putBlacklists(final serverObjects prop, final List<String> lists) {
prop.put("genUrlList_blacklists", lists.size());
int i = 0;
- for (String list : lists)
+ for (final String list : lists)
prop.put("genUrlList_blacklists_" + i++ + "_name", list);
}
-
+
public static Bitfield compileFlags(final serverObjects post) {
final Bitfield b = new Bitfield(4);
if (post.get("allurl", "").equals("on")) return null;
@@ -544,12 +543,12 @@ public class IndexControlRWIs_p {
prop.put("searchresult_hosts", hc);
}
- public static RankingProcess genSearchresult(final serverObjects prop, final Switchboard sb, Segment segment, final byte[] keyhash, final Bitfield filter) {
+ public static RankingProcess genSearchresult(final serverObjects prop, final Switchboard sb, final Segment segment, final byte[] keyhash, final Bitfield filter) {
final QueryParams query = new QueryParams(ASCII.String(keyhash), -1, filter, segment, sb.getRanking(), "IndexControlRWIs_p");
final ReferenceOrder order = new ReferenceOrder(query.ranking, UTF8.getBytes(query.targetlang));
final RankingProcess ranked = new RankingProcess(query, order, Integer.MAX_VALUE);
ranked.run();
-
+
if (ranked.filteredCount() == 0) {
prop.put("searchresult", 2);
prop.put("searchresult_wordhash", keyhash);
diff --git a/htroot/IndexControlURLs_p.java b/htroot/IndexControlURLs_p.java
index 36a3450a2..3ea3cb078 100644
--- a/htroot/IndexControlURLs_p.java
+++ b/htroot/IndexControlURLs_p.java
@@ -10,7 +10,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -33,13 +33,13 @@ import java.util.Iterator;
import net.yacy.cora.date.GenericFormatter;
import net.yacy.cora.document.ASCII;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.data.word.Word;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.order.RotateIterator;
-import de.anomic.crawler.CrawlProfile;
import de.anomic.search.MetadataRepository;
import de.anomic.search.Segment;
import de.anomic.search.Switchboard;
@@ -48,20 +48,20 @@ import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
public class IndexControlURLs_p {
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
-
+
final serverObjects prop = new serverObjects();
-
+
// set default values
prop.put("urlstring", "");
prop.put("urlhash", "");
prop.put("result", "");
String segmentName = sb.getConfig(SwitchboardConstants.SEGMENT_PUBLIC, "default");
int i = 0;
- for (String s: sb.indexSegments.segmentNames()) {
+ for (final String s: sb.indexSegments.segmentNames()) {
prop.put("segments_" + i + "_name", s);
prop.put("segments_" + i + "_selected", (segmentName.equals(s)) ? 1 : 0);
i++;
@@ -75,13 +75,13 @@ public class IndexControlURLs_p {
prop.put("statistics_lines", 100);
prop.put("statisticslines", 0);
prop.put("reload", 0);
-
+
// do segment selection
if (post != null && post.containsKey("segment")) {
// default values
segmentName = post.get("segment", segmentName).trim();
i= 0;
- for (String s: sb.indexSegments.segmentNames()) {
+ for (final String s: sb.indexSegments.segmentNames()) {
prop.put("segments_" + i + "_name", s);
prop.put("segments_" + i + "_selected", (segmentName.equals(s)) ? 1 : 0);
i++;
@@ -89,7 +89,7 @@ public class IndexControlURLs_p {
prop.put("segments", i);
segment = sb.indexSegments.segment(segmentName);
}
-
+
// show export messages
final MetadataRepository.Export export = segment.urlMetadata().export();
if ((export != null) && (export.isAlive())) {
@@ -121,15 +121,15 @@ public class IndexControlURLs_p {
}
}
}
-
+
if (post == null || env == null) {
return prop; // nothing to do
}
-
+
// post values that are set on numerous input fields with same name
String urlstring = post.get("urlstring", "").trim();
String urlhash = post.get("urlhash", "").trim();
-
+
if (!urlstring.startsWith("http://") &&
!urlstring.startsWith("https://") &&
!urlstring.startsWith("ftp://") &&
@@ -141,7 +141,7 @@ public class IndexControlURLs_p {
prop.put("result", " ");
if (post.containsKey("urlhashdeleteall")) {
- i = segment.removeAllUrlReferences(urlhash.getBytes(), sb.loader, CrawlProfile.CacheStrategy.IFEXIST);
+ i = segment.removeAllUrlReferences(urlhash.getBytes(), sb.loader, CacheStrategy.IFEXIST);
prop.put("result", "Deleted URL and " + i + " references from " + i + " word indexes.");
prop.put("lurlexport", 0);
prop.put("reload", 0);
@@ -215,7 +215,7 @@ public class IndexControlURLs_p {
// generate list
if (post.containsKey("urlhashsimilar")) {
try {
- final Iterator<URIMetadataRow> entryIt = new RotateIterator<URIMetadataRow>(segment.urlMetadata().entries(true, urlhash), ASCII.String(Base64Order.zero((urlhash == null ? 0 : urlhash.length()))), segment.termIndex().sizesMax());
+ final Iterator<URIMetadataRow> entryIt = new RotateIterator<URIMetadataRow>(segment.urlMetadata().entries(true, urlhash), ASCII.String(Base64Order.zero((urlhash == null ? 0 : urlhash.length()))), segment.termIndex().sizesMax());
final StringBuilder result = new StringBuilder("Sequential List of URL-Hashes:<br />");
URIMetadataRow entry;
i = 0;
@@ -242,7 +242,7 @@ public class IndexControlURLs_p {
prop.put("lurlexport", 0);
prop.put("reload", 0);
}
-
+
if (post.containsKey("lurlexport")) {
// parse format
int format = 0;
@@ -251,7 +251,7 @@ public class IndexControlURLs_p {
if (fname.endsWith("text")) format = 0;
if (fname.endsWith("html")) format = 1;
if (fname.endsWith("rss")) format = 2;
-
+
// extend export file name
String s = post.get("exportfile", "");
if (s.indexOf('.') < 0) {
@@ -267,16 +267,16 @@ public class IndexControlURLs_p {
prop.put("lurlexport_exportfile", s);
prop.put("lurlexport_urlcount", running.count());
if ((running != null) && (running.failed() == null)) {
- prop.put("lurlexport", 2);
+ prop.put("lurlexport", 2);
}
prop.put("reload", 1);
}
-
+
if (post.containsKey("deletedomain")) {
- String hp = post.get("hashpart");
+ final String hp = post.get("hashpart");
try {
segment.urlMetadata().deleteDomain(hp);
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
Log.logException(e);
}
@@ -284,14 +284,14 @@ public class IndexControlURLs_p {
post.put("statistics", "");
prop.put("reload", 0);
}
-
+
if (post.containsKey("statistics")) {
- int count = post.getInt("lines", 100);
+ final int count = post.getInt("lines", 100);
Iterator<MetadataRepository.HostStat> statsiter;
prop.put("statistics_lines", count);
int cnt = 0;
try {
- MetadataRepository metadata = segment.urlMetadata();
+ final MetadataRepository metadata = segment.urlMetadata();
statsiter = metadata.statistics(count, metadata.urlSampleScores(metadata.domainSampleCollector()));
boolean dark = true;
MetadataRepository.HostStat hs;
@@ -305,7 +305,7 @@ public class IndexControlURLs_p {
dark = !dark;
cnt++;
}
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
prop.put("statisticslines_domains", cnt);
@@ -313,13 +313,13 @@ public class IndexControlURLs_p {
prop.put("lurlexport", 0);
prop.put("reload", 0);
}
-
+
// insert constants
prop.putNum("ucount", segment.urlMetadata().size());
// return rewrite properties
return prop;
}
-
+
private static serverObjects genUrlProfile(final Segment segment, final URIMetadataRow entry, final String urlhash) {
final serverObjects prop = new serverObjects();
if (entry == null) {
diff --git a/htroot/Load_RSS_p.java b/htroot/Load_RSS_p.java
index aab39a1f0..935e43c7b 100644
--- a/htroot/Load_RSS_p.java
+++ b/htroot/Load_RSS_p.java
@@ -7,12 +7,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -33,14 +33,13 @@ import net.yacy.cora.document.RSSMessage;
import net.yacy.cora.document.RSSReader;
import net.yacy.cora.document.UTF8;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Parser.Failure;
import net.yacy.kelondro.blob.Tables;
import net.yacy.kelondro.blob.Tables.Row;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.index.RowSpaceExceededException;
import net.yacy.kelondro.logging.Log;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.RSSLoader;
import de.anomic.crawler.retrieval.Response;
import de.anomic.data.WorkTables;
@@ -63,104 +62,104 @@ public class Load_RSS_p {
prop.put("url", "");
if (post != null && post.containsKey("removeSelectedFeedsNewList")) {
- for (Map.Entry<String, String> entry: post.entrySet()) {
+ for (final Map.Entry<String, String> entry: post.entrySet()) {
if (entry.getValue().startsWith("mark_")) try {
sb.tables.delete("rss", entry.getValue().substring(5).getBytes());
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
}
-
+
if (post != null && post.containsKey("removeAllFeedsNewList")) try {
- Iterator<Row> plainIterator = sb.tables.iterator("rss");
+ final Iterator<Row> plainIterator = sb.tables.iterator("rss");
Row row;
String messageurl;
- List<byte[]> d = new ArrayList<byte[]>();
+ final List<byte[]> d = new ArrayList<byte[]>();
while (plainIterator.hasNext()) {
row = plainIterator.next();
if (row == null) continue;
messageurl = row.get("url", "");
if (messageurl.length() == 0) continue;
- byte[] api_pk = row.get("api_pk");
- Row r = api_pk == null ? null : sb.tables.select("api", api_pk);
+ final byte[] api_pk = row.get("api_pk");
+ final Row r = api_pk == null ? null : sb.tables.select("api", api_pk);
if (r == null || !r.get("comment", "").matches(".*\\Q" + messageurl + "\\E.*")) {
d.add(row.getPK());
}
}
- for (byte[] pk: d) {
+ for (final byte[] pk: d) {
sb.tables.delete("rss", pk);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
-
+
if (post != null && post.containsKey("removeSelectedFeedsScheduler")) {
- for (Map.Entry<String, String> entry: post.entrySet()) {
+ for (final Map.Entry<String, String> entry: post.entrySet()) {
if (entry.getValue().startsWith("mark_")) try {
- byte[] pk = entry.getValue().substring(5).getBytes();
- Row rssRow = sb.tables.select("rss", pk);
- byte[] schedulerPK = rssRow.get("api_pk", (byte[]) null);
+ final byte[] pk = entry.getValue().substring(5).getBytes();
+ final Row rssRow = sb.tables.select("rss", pk);
+ final byte[] schedulerPK = rssRow.get("api_pk", (byte[]) null);
if (schedulerPK != null) sb.tables.delete("api", schedulerPK);
rssRow.remove("api_pk");
sb.tables.insert("rss", pk, rssRow);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
}
}
-
+
if (post != null && post.containsKey("removeAllFeedsScheduler")) try {
- Iterator<Row> plainIterator = sb.tables.iterator("rss");
+ final Iterator<Row> plainIterator = sb.tables.iterator("rss");
Row row;
String messageurl;
- List<byte[]> d = new ArrayList<byte[]>();
+ final List<byte[]> d = new ArrayList<byte[]>();
while (plainIterator.hasNext()) {
row = plainIterator.next();
if (row == null) continue;
messageurl = row.get("url", "");
if (messageurl.length() == 0) continue;
- byte[] api_pk = row.get("api_pk");
- Row r = api_pk == null ? null : sb.tables.select("api", api_pk);
+ final byte[] api_pk = row.get("api_pk");
+ final Row r = api_pk == null ? null : sb.tables.select("api", api_pk);
if (r != null && r.get("comment", "").matches(".*\\Q" + messageurl + "\\E.*")) {
d.add(row.getPK());
}
}
- for (byte[] pk: d) {
- Row rssRow = sb.tables.select("rss", pk);
- byte[] schedulerPK = rssRow.get("api_pk", (byte[]) null);
+ for (final byte[] pk: d) {
+ final Row rssRow = sb.tables.select("rss", pk);
+ final byte[] schedulerPK = rssRow.get("api_pk", (byte[]) null);
if (schedulerPK != null) sb.tables.delete("api", schedulerPK);
rssRow.remove("api_pk");
sb.tables.insert("rss", pk, rssRow);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
-
+
if (post != null && post.containsKey("addSelectedFeedScheduler")) {
- for (Map.Entry<String, String> entry: post.entrySet()) {
+ for (final Map.Entry<String, String> entry: post.entrySet()) {
if (entry.getValue().startsWith("mark_")) {
Row row;
try {
- byte [] pk = entry.getValue().substring(5).getBytes();
+ final byte [] pk = entry.getValue().substring(5).getBytes();
row = sb.tables.select("rss", pk);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
continue;
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
continue;
}
DigestURI url = null;
try {
url = new DigestURI(row.get("url", ""));
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logWarning("Load_RSS", "malformed url '" + row.get("url", "") + "': " + e.getMessage());
continue;
}
@@ -169,7 +168,7 @@ public class Load_RSS_p {
}
}
}
-
+
if (post == null || (post != null && (
post.containsKey("addSelectedFeedScheduler") ||
post.containsKey("removeSelectedFeedsNewList") ||
@@ -181,23 +180,23 @@ public class Load_RSS_p {
// get list of primary keys from the api table with scheduled feed loading requests
Tables.Row row;
String messageurl;
-
+
// check feeds
int newc = 0, apic = 0;
- Iterator<Row> plainIterator = sb.tables.iterator("rss");
+ final Iterator<Row> plainIterator = sb.tables.iterator("rss");
while (plainIterator.hasNext()) {
row = plainIterator.next();
if (row == null) continue;
messageurl = row.get("url", "");
if (messageurl.length() == 0) continue;
// get referrer
- DigestURI referrer = sb.getURL(Segments.Process.LOCALCRAWLING, row.get("referrer", "").getBytes());
+ final DigestURI referrer = sb.getURL(Segments.Process.LOCALCRAWLING, row.get("referrer", "").getBytes());
// check if feed is registered in scheduler
- byte[] api_pk = row.get("api_pk");
- Row r = api_pk == null ? null : sb.tables.select("api", api_pk);
+ final byte[] api_pk = row.get("api_pk");
+ final Row r = api_pk == null ? null : sb.tables.select("api", api_pk);
if (r != null && r.get("comment", "").matches(".*\\Q" + messageurl + "\\E.*")) {
// this is a recorded entry
- Date date_next_exec = r.get(WorkTables.TABLE_API_COL_DATE_NEXT_EXEC, (Date) null);
+ final Date date_next_exec = r.get(WorkTables.TABLE_API_COL_DATE_NEXT_EXEC, (Date) null);
prop.put("showscheduledfeeds_list_" + apic + "_pk", UTF8.String(row.getPK()));
prop.put("showscheduledfeeds_list_" + apic + "_count", apic);
prop.putXML("showscheduledfeeds_list_" + apic + "_rss", messageurl);
@@ -228,44 +227,44 @@ public class Load_RSS_p {
prop.put("shownewfeeds_list" , newc);
prop.put("shownewfeeds_num", newc);
prop.put("shownewfeeds", newc > 0 ? 1 : 0);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
-
+
return prop;
}
prop.put("url", post.get("url", ""));
-
+
int repeat_time = post.getInt("repeat_time", -1);
final String repeat_unit = post.get("repeat_unit", "seldays"); // selminutes, selhours, seldays
if (!"on".equals(post.get("repeat", "off")) && repeat_time > 0) repeat_time = -1;
-
+
boolean record_api = false;
-
+
DigestURI url = null;
try {
url = post.containsKey("url") ? new DigestURI(post.get("url", "")) : null;
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logWarning("Load_RSS_p", "url not well-formed: '" + post.get("url", "") + "'");
}
-
+
// if we have an url then try to load the rss
RSSReader rss = null;
if (url != null) try {
prop.put("url", url.toNormalform(true, false));
- final Response response = sb.loader.load(sb.loader.request(url, true, false), CrawlProfile.CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
- byte[] resource = response == null ? null : response.getContent();
+ final Response response = sb.loader.load(sb.loader.request(url, true, false), CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
+ final byte[] resource = response == null ? null : response.getContent();
rss = resource == null ? null : RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, resource);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
// index all selected items: description only
if (rss != null && post.containsKey("indexSelectedItemContent")) {
- RSSFeed feed = rss.getFeed();
+ final RSSFeed feed = rss.getFeed();
loop: for (final Map.Entry<String, String> entry: post.entrySet()) {
if (entry.getValue().startsWith("mark_")) try {
final RSSMessage message = feed.getMessage(entry.getValue().substring(5));
@@ -274,25 +273,25 @@ public class Load_RSS_p {
if (sb.urlExists(Segments.Process.LOCALCRAWLING, messageurl.hash()) != null) continue loop;
sb.addToIndex(messageurl, null, null);
RSSLoader.indexTriggered.insertIfAbsent(messageurl.hash(), new Date());
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
- } catch (Failure e) {
+ } catch (final Failure e) {
Log.logException(e);
}
}
}
-
+
if (rss != null && post.containsKey("indexAllItemContent")) {
record_api = true;
final RSSFeed feed = rss.getFeed();
RSSLoader.indexAllRssFeed(sb, url, feed);
}
-
+
if (record_api && rss != null && rss.getFeed() != null && rss.getFeed().getChannel() != null) {
// record API action
RSSLoader.recordAPI(sb, post.get(WorkTables.TABLE_API_COL_APICALL_PK, null), url, rss.getFeed(), repeat_time, repeat_unit);
}
-
+
// show items from rss
if (rss != null) {
prop.put("showitems", 1);
@@ -308,7 +307,7 @@ public class Load_RSS_p {
prop.putHTML("showitems_date", (pubDate == null) ? "" : DateFormat.getDateTimeInstance().format(pubDate));
prop.putHTML("showitems_ttl", channel == null ? "" : channel.getTTL());
prop.putHTML("showitems_docs", channel == null ? "" : channel.getDocs());
-
+
int i = 0;
for (final Hit item: feed) {
try {
@@ -326,7 +325,7 @@ public class Load_RSS_p {
prop.putHTML("showitems_item_" + i + "_language", item.getLanguage());
prop.putHTML("showitems_item_" + i + "_date", (pubDate == null) ? "" : DateFormat.getDateTimeInstance().format(pubDate));
i++;
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logException(e);
continue;
}
@@ -339,8 +338,8 @@ public class Load_RSS_p {
prop.put("showload_rss", url.toNormalform(true, false));
}
}
-
+
return prop;
}
-
+
}
diff --git a/htroot/QuickCrawlLink_p.java b/htroot/QuickCrawlLink_p.java
index 500a6ecf0..6e65bd551 100644
--- a/htroot/QuickCrawlLink_p.java
+++ b/htroot/QuickCrawlLink_p.java
@@ -6,7 +6,7 @@
//Frankfurt, Germany, 2004
//
//This file was contributed by Martin Thelian
-//$LastChangedDate$
+//$LastChangedDate$
//$LastChangedBy$
//$LastChangedRevision$
//
@@ -36,9 +36,9 @@ import java.util.Date;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
-
import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Request;
import de.anomic.search.Segment;
@@ -48,7 +48,7 @@ import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
public class QuickCrawlLink_p {
-
+
/**
* Example Javascript to call this servlet:
* <code>javascript:w = window.open('http://user:pwd@localhost:8090/QuickCrawlLink_p.html?indexText=on&indexMedia=on&crawlingQ=on&xdstopw=on&title=' + escape(document.title) + '&url=' + location.href,'_blank','height=150,width=500,resizable=yes,scrollbar=no,directory=no,menubar=no,location=no'); w.focus();</code>
@@ -58,14 +58,14 @@ public class QuickCrawlLink_p {
* @return the rewrite-properties for the template
*/
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
-
+
final serverObjects prop = new serverObjects();
final Switchboard sb = (Switchboard) env;
-
+
// get segment
Segment indexSegment = null;
if (post != null && post.containsKey("segment")) {
- String segmentName = post.get("segment");
+ final String segmentName = post.get("segment");
if (sb.indexSegments.segmentExist(segmentName)) {
indexSegment = sb.indexSegments.segment(segmentName);
}
@@ -73,29 +73,29 @@ public class QuickCrawlLink_p {
// take default segment
indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
}
-
+
if (post == null) {
// send back usage example
prop.put("mode", "0");
-
+
// get the http host header
final String hostSocket = header.get(HeaderFramework.CONNECTION_PROP_HOST);
-
+
//String host = hostSocket;
int port = 80;
final int pos = hostSocket.indexOf(":");
if (pos != -1) {
port = Integer.parseInt(hostSocket.substring(pos + 1));
//host = hostSocket.substring(0, pos);
- }
-
+ }
+
prop.put("mode_host", "localhost");
prop.put("mode_port", port);
-
+
return prop;
}
prop.put("mode", "1");
-
+
// get the URL
String crawlingStart = post.get("url",null);
try {
@@ -103,10 +103,10 @@ public class QuickCrawlLink_p {
} catch (final UnsupportedEncodingException e) {
Log.logException(e);
}
-
+
// get the browser title
final String title = post.get("title",null);
-
+
// get other parameters if set
final String crawlingMustMatch = post.get("mustmatch", CrawlProfile.MATCH_ALL);
final String crawlingMustNotMatch = post.get("mustnotmatch", CrawlProfile.MATCH_NEVER);
@@ -122,11 +122,11 @@ public class QuickCrawlLink_p {
prop.put("mode_url", (crawlingStart == null) ? "unknown" : crawlingStart);
prop.putHTML("mode_title", (title == null) ? "unknown" : title);
-
+
if (crawlingStart != null) {
crawlingStart = crawlingStart.trim();
try {crawlingStart = new DigestURI(crawlingStart).toNormalform(true, true);} catch (final MalformedURLException e1) {}
-
+
// check if url is proper
DigestURI crawlingStartURL = null;
try {
@@ -136,17 +136,17 @@ public class QuickCrawlLink_p {
prop.put("mode_code", "1");
return prop;
}
-
+
final byte[] urlhash = crawlingStartURL.hash();
indexSegment.urlMetadata().remove(urlhash);
sb.crawlQueues.noticeURL.removeByURLHash(urlhash);
sb.crawlQueues.errorURL.remove(urlhash);
-
+
// create crawling profile
CrawlProfile pe = null;
try {
pe = new CrawlProfile(
- crawlingStartURL.getHost(),
+ crawlingStartURL.getHost(),
crawlingStartURL,
crawlingMustMatch,
crawlingMustNotMatch,
@@ -161,7 +161,7 @@ public class QuickCrawlLink_p {
xsstopw,
xdstopw,
xpstopw,
- CrawlProfile.CacheStrategy.IFFRESH);
+ CacheStrategy.IFFRESH);
sb.crawler.putActive(pe.handle().getBytes(), pe);
} catch (final Exception e) {
// mist
@@ -170,22 +170,22 @@ public class QuickCrawlLink_p {
prop.putHTML("mode_status_error", e.getMessage());
return prop;
}
-
+
// stack URL
String reasonString = null;
reasonString = sb.crawlStacker.stackCrawl(new Request(
- sb.peers.mySeed().hash.getBytes(),
+ sb.peers.mySeed().hash.getBytes(),
crawlingStartURL,
- null,
- (title==null)?"CRAWLING-ROOT":title,
+ null,
+ (title==null)?"CRAWLING-ROOT":title,
new Date(),
pe.handle(),
- 0,
+ 0,
0,
0,
0
));
-
+
// validate rejection reason
if (reasonString == null) {
prop.put("mode_status", "0");//start msg
@@ -196,7 +196,7 @@ public class QuickCrawlLink_p {
prop.putHTML("mode_status_error", reasonString);
}
}
-
+
return prop;
}
}
diff --git a/htroot/ViewFile.java b/htroot/ViewFile.java
index f28a80c38..af090dbeb 100644
--- a/htroot/ViewFile.java
+++ b/htroot/ViewFile.java
@@ -27,8 +27,8 @@
//javac -classpath .:../Classes Status.java
//if the shell's current path is HTROOT
-import java.io.IOException;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
@@ -41,6 +41,7 @@ import net.yacy.cora.document.ASCII;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.document.UTF8;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.LibraryProvider;
@@ -50,8 +51,6 @@ import net.yacy.document.parser.html.CharacterCoding;
import net.yacy.document.parser.html.ImageEntry;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
import de.anomic.http.client.Cache;
import de.anomic.search.Segment;
@@ -70,7 +69,7 @@ public class ViewFile {
public static final int VIEW_MODE_AS_IFRAME_FROM_CACHE = 5;
public static final int VIEW_MODE_AS_LINKLIST = 6;
public static final int VIEW_MODE_AS_PARSED_WORDS = 7;
-
+
private static final String HIGHLIGHT_CSS = "searchHighlight";
private static final int MAX_HIGHLIGHTS = 6;
@@ -78,7 +77,7 @@ public class ViewFile {
final serverObjects prop = new serverObjects();
final Switchboard sb = (Switchboard)env;
-
+
if (post == null) {
prop.put("display", 1);
prop.put("error_display", 0);
@@ -89,18 +88,18 @@ public class ViewFile {
prop.put("viewMode", VIEW_MODE_NO_TEXT);
return prop;
}
-
+
final int display = post.getInt("display", 1);
-
+
// get segment
Segment indexSegment = null;
- boolean authorized = sb.verifyAuthentication(header, false);
+ final boolean authorized = sb.verifyAuthentication(header, false);
if (post != null && post.containsKey("segment") && authorized) {
indexSegment = sb.indexSegments.segment(post.get("segment"));
} else {
indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
- }
-
+ }
+
prop.put("display", display);
prop.put("error_display", display);
@@ -112,13 +111,13 @@ public class ViewFile {
final String viewMode = post.get("viewMode","parsed");
prop.put("error_vMode-" + viewMode, "1");
-
+
DigestURI url = null;
String descr = "";
final int wordCount = 0;
int size = 0;
boolean pre = false;
-
+
// get the url hash from which the content should be loaded
String urlHash = post.get("urlHash", "");
URIMetadataRow urlEntry = null;
@@ -139,14 +138,14 @@ public class ViewFile {
}
prop.put("error_inurldb", urlEntry == null ? 0 : 1);
-
+
// alternatively, get the url simply from a url String
// this can be used as a simple tool to test the text parser
final String urlString = post.get("url", "");
if (urlString.length() > 0) try {
// this call forces the peer to download web pages
// it is therefore protected by the admin password
-
+
if (!sb.verifyAuthentication(header, false)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
@@ -157,8 +156,8 @@ public class ViewFile {
urlHash = ASCII.String(url.hash());
pre = post.getBoolean("pre", false);
} catch (final MalformedURLException e) {}
-
-
+
+
if (url == null) {
prop.put("error", "1");
prop.put("viewMode", VIEW_MODE_NO_TEXT);
@@ -170,24 +169,24 @@ public class ViewFile {
// loading the resource content as byte array
prop.put("error_incache", Cache.has(url) ? 1 : 0);
-
+
Response response = null;
try {
- response = sb.loader.load(sb.loader.request(url, true, false), authorized ? CrawlProfile.CacheStrategy.IFEXIST : CrawlProfile.CacheStrategy.CACHEONLY, Long.MAX_VALUE, true);
- } catch (IOException e) {
+ response = sb.loader.load(sb.loader.request(url, true, false), authorized ? CacheStrategy.IFEXIST : CacheStrategy.CACHEONLY, Long.MAX_VALUE, true);
+ } catch (final IOException e) {
prop.put("error", "4");
prop.put("error_errorText", "error loading resource: " + e.getMessage());
prop.put("viewMode", VIEW_MODE_NO_TEXT);
return prop;
}
-
+
if (response == null) {
prop.put("error", "4");
prop.put("error_errorText", "No resource available");
prop.put("viewMode", VIEW_MODE_NO_TEXT);
return prop;
}
-
+
final String[] wordArray = wordArray(post.get("words", null));
if (viewMode.equals("plain")) {
@@ -206,11 +205,11 @@ public class ViewFile {
prop.put("error", "0");
prop.put("viewMode", VIEW_MODE_AS_PLAIN_TEXT);
prop.put("viewMode_plainText", markup(wordArray, content).replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"));
-
+
} else if (viewMode.equals("iframeWeb")) {
prop.put("viewMode", VIEW_MODE_AS_IFRAME_FROM_WEB);
prop.put("viewMode_url", url.toNormalform(false, true));
-
+
} else if (viewMode.equals("iframeCache")) {
prop.put("viewMode", VIEW_MODE_AS_IFRAME_FROM_CACHE);
final String ext = url.getFileExtension();
@@ -238,7 +237,7 @@ public class ViewFile {
prop.put("viewMode", VIEW_MODE_NO_TEXT);
return prop;
}
-
+
if (viewMode.equals("parsed")) {
final String content = UTF8.String(document.getTextBytes());
// content = wikiCode.replaceHTML(content); // added by Marc Nause
@@ -254,7 +253,7 @@ public class ViewFile {
prop.put("viewMode_lat", document.lat());
prop.put("viewMode_lon", document.lon());
prop.put("viewMode_parsedText", markup(wordArray, content).replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"));
-
+
} else if (viewMode.equals("sentences")) {
prop.put("viewMode", VIEW_MODE_AS_PARSED_SENTENCES);
final Collection<StringBuilder> sentences = document.getSentences(pre);
@@ -263,7 +262,7 @@ public class ViewFile {
int i = 0;
String sentence;
if (sentences != null) {
-
+
// Search word highlighting
for (final StringBuilder s: sentences) {
sentence = s.toString();
@@ -286,7 +285,7 @@ public class ViewFile {
int i = 0;
String sentence, token;
if (sentences != null) {
-
+
// Search word highlighting
for (final StringBuilder s: sentences) {
sentence = s.toString();
@@ -313,7 +312,7 @@ public class ViewFile {
i += putMediaInfo(prop, wordArray, i, document.getVideolinks(), "video", (i % 2 == 0));
i += putMediaInfo(prop, wordArray, i, document.getAudiolinks(), "audio", (i % 2 == 0));
dark = (i % 2 == 0);
-
+
final Map<MultiProtocolURI, ImageEntry> ts = document.getImages();
final Iterator<ImageEntry> tsi = ts.values().iterator();
ImageEntry entry;
@@ -366,7 +365,7 @@ public class ViewFile {
} catch (final UnsupportedEncodingException e) {}
return w;
}
-
+
private static final String markup(final String[] wordArray, String message) {
message = CharacterCoding.unicode2html(message, true);
if (wordArray != null) {
@@ -376,16 +375,16 @@ public class ViewFile {
// TODO: replace upper-/lowercase words as well
message = message.replaceAll(currentWord,
"<span class=\"" + HIGHLIGHT_CSS + ((j++ % MAX_HIGHLIGHTS) + 1) + "\">" +
- currentWord +
+ currentWord +
"</span>");
}
}
return message;
}
-
+
private static int putMediaInfo(final serverObjects prop, final String[] wordArray, int c, final Map<MultiProtocolURI, String> media, final String name, boolean dark) {
int i = 0;
- for (Map.Entry<MultiProtocolURI, String> entry : media.entrySet()) {
+ for (final Map.Entry<MultiProtocolURI, String> entry : media.entrySet()) {
prop.put("viewMode_links_" + c + "_nr", c);
prop.put("viewMode_links_" + c + "_dark", ((dark) ? 1 : 0));
prop.putHTML("viewMode_links_" + c + "_type", name);
@@ -399,5 +398,5 @@ public class ViewFile {
}
return i;
}
-
+
}
diff --git a/htroot/ViewImage.java b/htroot/ViewImage.java
index a2c2046a1..d4251d55f 100644
--- a/htroot/ViewImage.java
+++ b/htroot/ViewImage.java
@@ -34,14 +34,13 @@ import java.util.Map;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.cora.storage.ConcurrentARC;
import net.yacy.document.ImageParser;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.util.MemoryControl;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
@@ -57,46 +56,46 @@ public class ViewImage {
} catch (final IOException e) {
}
}
-
+
public static Image respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
-
+
final Switchboard sb = (Switchboard)env;
-
+
// the url to the image can be either submitted with an url in clear text, or using a license key
// if the url is given as clear text, the user must be authorized as admin
// the license can be used also from non-authorized users
-
+
String urlString = post.get("url", "");
final String urlLicense = post.get("code", "");
final boolean auth = (header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true); // handle access rights
-
+
DigestURI url = null;
if ((urlString.length() > 0) && (auth)) try {
url = new DigestURI(urlString);
} catch (final MalformedURLException e1) {
url = null;
}
-
+
if ((url == null) && (urlLicense.length() > 0)) {
url = sb.licensedURLs.releaseLicense(urlLicense);
urlString = (url == null) ? null : url.toNormalform(true, true);
}
-
+
if (urlString == null) return null;
-
+
int width = post.getInt("width", 0);
int height = post.getInt("height", 0);
int maxwidth = post.getInt("maxwidth", 0);
int maxheight = post.getInt("maxheight", 0);
-
+
// get the image as stream
if (MemoryControl.shortStatus()) iconcache.clear();
Image image = iconcache.get(urlString);
if (image == null) {
byte[] resourceb = null;
if (url != null) try {
- resourceb = sb.loader.loadContent(sb.loader.request(url, false, true), CrawlProfile.CacheStrategy.IFEXIST);
- } catch (IOException e) {
+ resourceb = sb.loader.loadContent(sb.loader.request(url, false, true), CacheStrategy.IFEXIST);
+ } catch (final IOException e) {
Log.logFine("ViewImage", "cannot load: " + e.getMessage());
}
byte[] imgb = null;
@@ -136,7 +135,7 @@ public class ViewImage {
// find original size
final int h = image.getHeight(null);
final int w = image.getWidth(null);
-
+
// in case of not-authorized access shrink the image to prevent
// copyright problems, so that images are not larger than thumbnails
if (auth) {
@@ -155,7 +154,7 @@ public class ViewImage {
// scale image
final double hs = (w <= maxwidth) ? 1.0 : ((double) maxwidth) / ((double) w);
final double vs = (h <= maxheight) ? 1.0 : ((double) maxheight) / ((double) h);
- double scale = Math.min(hs, vs);
+ final double scale = Math.min(hs, vs);
//if (!auth) scale = Math.min(scale, 0.6); // this is for copyright purpose
if (scale < 1.0) {
width = Math.max(1, (int) (w * scale));
@@ -164,28 +163,28 @@ public class ViewImage {
width = Math.max(1, w);
height = Math.max(1, h);
}
-
+
if (w != width && h != height) {
// compute scaled image
- Image scaled = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
+ final Image scaled = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
final MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(scaled, 0);
try {mediaTracker.waitForID(0);} catch (final InterruptedException e) {}
-
+
// make a BufferedImage out of that
- BufferedImage i = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+ final BufferedImage i = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
try {
- i.createGraphics().drawImage(scaled, 0, 0, width, height, null);
+ i.createGraphics().drawImage(scaled, 0, 0, width, height, null);
image = i;
// check outcome
- Raster raster = i.getData();
+ final Raster raster = i.getData();
int[] pixel = new int[3];
pixel = raster.getPixel(0, 0, pixel);
if (pixel[0] != 0 || pixel[1] != 0 || pixel[2] != 0) image = i;
- } catch (Exception e) {
+ } catch (final Exception e) {
//java.lang.ClassCastException: [I cannot be cast to [B
}
-
+
}
} else {
// do not scale
@@ -198,8 +197,8 @@ public class ViewImage {
iconcache.put(urlString, image);
}
}
-
+
return image;
}
-
+
}
diff --git a/htroot/api/util/getpageinfo_p.java b/htroot/api/util/getpageinfo_p.java
index f4aadb818..53b4aa5c1 100755
--- a/htroot/api/util/getpageinfo_p.java
+++ b/htroot/api/util/getpageinfo_p.java
@@ -5,34 +5,33 @@ import java.util.Set;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.kelondro.data.meta.DigestURI;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.RobotsTxtEntry;
import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
public class getpageinfo_p {
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
-
- // avoid UNRESOLVED PATTERN
- prop.put("title", "");
+
+ // avoid UNRESOLVED PATTERN
+ prop.put("title", "");
prop.put("desc", "");
prop.put("lang", "");
prop.put("robots-allowed", "3"); //unknown
prop.put("sitemap", "");
- prop.put("favicon","");
+ prop.put("favicon","");
prop.put("sitelist", "");
prop.put("filter", ".*");
-
+
// default actions
String actions="title,robots";
-
+
if (post != null && post.containsKey("url")) {
if(post.containsKey("actions"))
actions=post.get("actions");
@@ -57,40 +56,40 @@ public class getpageinfo_p {
}
ContentScraper scraper = null;
if (u != null) try {
- scraper = sb.loader.parseResource(u, CrawlProfile.CacheStrategy.IFEXIST);
+ scraper = sb.loader.parseResource(u, CacheStrategy.IFEXIST);
} catch (final IOException e) {
- // now thats a fail, do nothing
- }
+ // now thats a fail, do nothing
+ }
if (scraper != null) {
- // put the document title
+ // put the document title
prop.putXML("title", scraper.getTitle());
-
+
// put the favicon that belongs to the document
prop.put("favicon", (scraper.getFavicon()==null) ? "" : scraper.getFavicon().toString());
-
+
// put keywords
final String list[]=scraper.getKeywords();
int count = 0;
- for(int i=0;i<list.length;i++){
- String tag = list[i];
- if (!tag.equals("")) {
+ for (final String element : list) {
+ final String tag = element;
+ if (!tag.equals("")) {
prop.putXML("tags_"+count+"_tag", tag);
count++;
}
}
prop.put("tags", count);
- // put description
+ // put description
prop.putXML("desc", scraper.getDescription());
// put language
- Set<String> languages = scraper.getContentLanguages();
+ final Set<String> languages = scraper.getContentLanguages();
prop.putXML("lang", (languages == null) ? "unknown" : languages.iterator().next());
-
+
// get links and put them into a semicolon-separated list
- Set<MultiProtocolURI> uris = scraper.getAnchors().keySet();
- StringBuilder links = new StringBuilder(uris.size() * 80);
- StringBuilder filter = new StringBuilder(uris.size() * 40);
+ final Set<MultiProtocolURI> uris = scraper.getAnchors().keySet();
+ final StringBuilder links = new StringBuilder(uris.size() * 80);
+ final StringBuilder filter = new StringBuilder(uris.size() * 40);
count = 0;
- for (MultiProtocolURI uri: uris) {
+ for (final MultiProtocolURI uri: uris) {
links.append(';').append(uri.toNormalform(true, false));
filter.append('|').append(uri.getProtocol()).append("://").append(uri.getHost()).append(".*");
prop.putXML("links_" + count + "_link", uri.toNormalform(true, false));
@@ -104,12 +103,12 @@ public class getpageinfo_p {
if (actions.indexOf("robots")>=0) {
try {
final DigestURI theURL = new DigestURI(url);
-
+
// determine if crawling of the current URL is allowed
RobotsTxtEntry robotsEntry;
try {
robotsEntry = sb.robots.getEntry(theURL, sb.peers.myBotIDs());
- } catch (IOException e) {
+ } catch (final IOException e) {
robotsEntry = null;
}
prop.put("robots-allowed", robotsEntry == null ? 1 : robotsEntry.isDisallowed(theURL) ? 0 : 1);
@@ -119,10 +118,10 @@ public class getpageinfo_p {
prop.putXML("sitemap", sitemapURL == null ? "" : sitemapURL.toString());
} catch (final MalformedURLException e) {}
}
-
+
}
// return rewrite properties
return prop;
}
-
+
}
diff --git a/htroot/js/yacysearch.js b/htroot/js/yacysearch.js
index c2097453e..91e9e607c 100644
--- a/htroot/js/yacysearch.js
+++ b/htroot/js/yacysearch.js
@@ -70,7 +70,7 @@ function addHover() {
}
}
-function statistics(offset, itemscount, totalcount, localResourceSize, remoteResourceSize, remoteIndexCount, remotePeerCount) {
+function statistics(offset, itemscount, itemsperpage, totalcount, localResourceSize, remoteResourceSize, remoteIndexCount, remotePeerCount, navurlbase) {
if (offset >= 0) document.getElementById("resultsOffset").firstChild.nodeValue = offset;
if (itemscount >= 0) document.getElementById("itemscount").firstChild.nodeValue = itemscount;
document.getElementById("totalcount").firstChild.nodeValue = totalcount;
@@ -79,4 +79,42 @@ function statistics(offset, itemscount, totalcount, localResourceSize, remoteRes
document.getElementById("remoteResourceSize").firstChild.nodeValue = remoteResourceSize;
document.getElementById("remoteIndexCount").firstChild.nodeValue = remoteIndexCount;
document.getElementById("remotePeerCount").firstChild.nodeValue = remotePeerCount;
+ // compose page navigation
+
+ resnav = "";
+ thispage = offset / itemsperpage;
+ if (thispage == 0) {
+ resnav += ("<img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" />&nbsp;");
+ } else {
+ resnav += ("<a id=\"prevpage\" href=\"");
+ resnav += (QueryParams.navurl("html", thispage - 1, theQuery, null, originalUrlMask, navigation));
+ resnav += ("\"><img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /></a>&nbsp;");
+ }
+ numberofpages = Math.min(10, 1 + ((indexcount - 1) / itemsperpage));
+
+ for (i = 0; i < numberofpages; i++) {
+ if (i == thispage) {
+ resnav += "<img src=\"env/grafics/navs";
+ resnav += (i + 1);
+ resnav += (".gif\" alt=\"page");
+ resnav += (i + 1);
+ resnav += ("\" width=\"16\" height=\"16\" />&nbsp;");
+ } else {
+ resnav += ("<a href=\"");
+ resnav += (QueryParams.navurl("html", i, theQuery, null, originalUrlMask, navigation));
+ resnav += ("\"><img src=\"env/grafics/navd");
+ resnav += (i + 1);
+ resnav += (".gif\" alt=\"page");
+ resnav += (i + 1);
+ resnav += ("\" width=\"16\" height=\"16\" /></a>&nbsp;");
+ }
+ }
+ if (thispage >= numberofpages) {
+ resnav += ("<img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" />");
+ } else {
+ resnav += ("<a id=\"nextpage\" href=\"");
+ resnav += (QueryParams.navurl("html", thispage + 1, theQuery, null, originalUrlMask, navigation));
+ resnav += ("\"><img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" /></a>");
+ }
+ document.getElementById("resNav").firstChild.nodeValue = resnav;
}
\ No newline at end of file
diff --git a/htroot/yacy/search.java b/htroot/yacy/search.java
index d73651960..c4ca01da8 100644
--- a/htroot/yacy/search.java
+++ b/htroot/yacy/search.java
@@ -9,7 +9,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -42,6 +42,7 @@ import net.yacy.cora.document.UTF8;
import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.cora.storage.ScoreMap;
import net.yacy.cora.storage.WeakPriorityBlockingQueue;
import net.yacy.kelondro.data.meta.DigestURI;
@@ -55,18 +56,16 @@ import net.yacy.kelondro.util.ByteBuffer;
import net.yacy.kelondro.util.EventTracker;
import net.yacy.kelondro.util.ISO639;
import net.yacy.kelondro.util.MemoryControl;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.search.AccessTracker;
import de.anomic.search.ContentDomain;
import de.anomic.search.QueryParams;
import de.anomic.search.RankingProfile;
+import de.anomic.search.ResultEntry;
import de.anomic.search.SearchEvent;
import de.anomic.search.SearchEventCache;
import de.anomic.search.Segment;
import de.anomic.search.Segments;
import de.anomic.search.Switchboard;
-import de.anomic.search.ResultEntry;
import de.anomic.search.SwitchboardConstants;
import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
@@ -84,7 +83,7 @@ public final class search {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
sb.remoteSearchLastAccess = System.currentTimeMillis();
-
+
final serverObjects prop = new serverObjects();
if ((post == null) || (env == null)) return prop;
if (!yacyNetwork.authentifyRequest(post, env)) return prop;
@@ -152,7 +151,7 @@ public final class search {
prop.put("references", "");
return prop;
}
-
+
// check the search tracker
TreeSet<Long> trackerHandles = sb.remoteSearchTracker.get(client);
if (trackerHandles == null) trackerHandles = new TreeSet<Long>();
@@ -176,18 +175,18 @@ public final class search {
prop.put("searchtime", "0");
return prop;
}
-
+
// tell all threads to do nothing for a specific time
sb.intermissionAllThreads(100);
EventTracker.delete(EventTracker.EClass.SEARCH);
final HandleSet abstractSet = (abstracts.length() == 0 || abstracts.equals("auto")) ? null : QueryParams.hashes2Set(abstracts);
-
+
// store accessing peer
yacySeed remoteSeed;
try {
remoteSeed = yacySeed.genRemoteSeed(oseed, key, false, client);
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logInfo("yacy.search: access with bad seed: " + e.getMessage());
remoteSeed = null;
}
@@ -201,10 +200,10 @@ public final class search {
final HandleSet queryhashes = QueryParams.hashes2Set(query);
final HandleSet excludehashes = (exclude.length() == 0) ? new HandleSet(WordReferenceRow.urlEntryRow.primaryKeyLength, WordReferenceRow.urlEntryRow.objectOrder, 0) : QueryParams.hashes2Set(exclude);
final long timestamp = System.currentTimeMillis();
-
+
// prepare a search profile
final RankingProfile rankingProfile = (profile.length() == 0) ? new RankingProfile(ContentDomain.contentdomParser(contentdom)) : new RankingProfile("", profile);
-
+
// prepare an abstract result
final StringBuilder indexabstract = new StringBuilder(6000);
int indexabstractContainercount = 0;
@@ -214,7 +213,7 @@ public final class search {
ArrayList<WeakPriorityBlockingQueue.Element<ResultEntry>> accu = null;
if (query.length() == 0 && abstractSet != null) {
// this is _not_ a normal search, only a request for index abstracts
- Segment indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
+ final Segment indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
theQuery = new QueryParams(
null,
abstractSet,
@@ -227,7 +226,7 @@ public final class search {
ContentDomain.contentdomParser(contentdom),
language,
"", // no navigation
- CrawlProfile.CacheStrategy.CACHEONLY,
+ CacheStrategy.CACHEONLY,
count,
0,
filter,
@@ -235,7 +234,7 @@ public final class search {
-1,
null,
false,
- sitehash,
+ sitehash,
authorhash,
DigestURI.TLD_any_zone_filter,
client,
@@ -250,7 +249,7 @@ public final class search {
final long timer = System.currentTimeMillis();
//final Map<byte[], ReferenceContainer<WordReference>>[] containers = sb.indexSegment.index().searchTerm(theQuery.queryHashes, theQuery.excludeHashes, plasmaSearchQuery.hashes2StringSet(urls));
final TreeMap<byte[], ReferenceContainer<WordReference>> incc = indexSegment.termIndex().searchConjunction(theQuery.queryHashes, QueryParams.hashes2Handles(urls));
-
+
EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.Type.COLLECTION, "", incc.size(), System.currentTimeMillis() - timer), false);
if (incc != null) {
final Iterator<Map.Entry<byte[], ReferenceContainer<WordReference>>> ci = incc.entrySet().iterator();
@@ -268,37 +267,37 @@ public final class search {
indexabstract.append(serverCore.CRLF_STRING);
}
}
-
+
prop.put("indexcount", "");
prop.put("joincount", "0");
prop.put("references", "");
-
+
} else {
// retrieve index containers from search request
theQuery = new QueryParams(
- null,
- queryhashes,
- excludehashes,
+ null,
+ queryhashes,
+ excludehashes,
null,
snippetPattern,
null,
- maxdist,
+ maxdist,
prefer,
ContentDomain.contentdomParser(contentdom),
language,
"", // no navigation
- CrawlProfile.CacheStrategy.CACHEONLY,
- count,
- 0,
- filter,
- QueryParams.SEARCHDOM_LOCAL,
- -1,
- constraint,
+ CacheStrategy.CACHEONLY,
+ count,
+ 0,
+ filter,
+ QueryParams.SEARCHDOM_LOCAL,
+ -1,
+ constraint,
false,
sitehash,
authorhash,
DigestURI.TLD_any_zone_filter,
- client,
+ client,
false,
sb.indexSegments.segment(Segments.Process.PUBLIC),
rankingProfile,
@@ -307,10 +306,10 @@ public final class search {
);
yacyCore.log.logInfo("INIT HASH SEARCH (query-" + abstracts + "): " + QueryParams.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links");
yacyChannel.channels(yacyChannel.REMOTESEARCH).addMessage(new RSSMessage("Remote Search Request from " + ((remoteSeed == null) ? "unknown" : remoteSeed.getName()), QueryParams.anonymizedQueryHashes(theQuery.queryHashes), ""));
-
+
// make event
theSearch = SearchEventCache.getEvent(theQuery, sb.peers, sb.tables, null, abstracts.length() > 0, sb.loader, count, maxtime, (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_ROBINSON, 0), (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_MULTIWORD, 0));
-
+
// set statistic details of search result and find best result index set
joincount = theSearch.getRankingResult().getLocalIndexCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount();
prop.put("joincount", Integer.toString(joincount));
@@ -339,7 +338,7 @@ public final class search {
}
}
prop.put("indexcount", indexcount.toString());
-
+
// generate compressed index for maxcounthash
// this is not needed if the search is restricted to specific
// urls, because it is a re-search
@@ -360,12 +359,12 @@ public final class search {
}
}
if (partitions > 0) sb.searchQueriesGlobal += 1d / partitions; // increase query counter
-
+
// prepare reference hints
final long timer = System.currentTimeMillis();
- ScoreMap<String> topicNavigator = theSearch.getTopicNavigator(5);
+ final ScoreMap<String> topicNavigator = theSearch.getTopicNavigator(5);
final StringBuilder refstr = new StringBuilder(6000);
- Iterator<String> navigatorIterator = topicNavigator.keys(false);
+ final Iterator<String> navigatorIterator = topicNavigator.keys(false);
int i = 0;
String name;
while (i < 5 && navigatorIterator.hasNext()) {
@@ -377,10 +376,10 @@ public final class search {
EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.Type.REFERENCECOLLECTION, "", i, System.currentTimeMillis() - timer), false);
}
prop.put("indexabstract", indexabstract.toString());
-
+
// prepare result
if (joincount == 0 || accu == null || accu.isEmpty()) {
-
+
// no results
prop.put("links", "");
prop.put("linkcount", "0");
@@ -404,7 +403,7 @@ public final class search {
prop.put("linkcount", accu.size());
EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.Type.RESULTLIST, "", accu.size(), System.currentTimeMillis() - timer), false);
}
-
+
// add information about forward peers
prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result
prop.put("fwsrc", ""); // peers that helped to construct this result
@@ -417,7 +416,7 @@ public final class search {
theQuery.urlretrievaltime = (theSearch == null) ? 0 : theSearch.result().getURLRetrievalTime();
theQuery.snippetcomputationtime = (theSearch == null) ? 0 : theSearch.result().getSnippetComputationTime();
AccessTracker.add(AccessTracker.Location.remote, theQuery);
-
+
// update the search tracker
synchronized (trackerHandles) {
trackerHandles.add(theQuery.time); // thats the time when the handle was created
@@ -426,14 +425,14 @@ public final class search {
}
sb.remoteSearchTracker.put(client, trackerHandles);
if (MemoryControl.shortStatus()) sb.remoteSearchTracker.clear();
-
+
// log
yacyCore.log.logInfo("EXIT HASH SEARCH: " +
QueryParams.anonymizedQueryHashes(theQuery.queryHashes) + " - " + joincount + " links found, " +
prop.get("linkcount", "?") + " links selected, " +
indexabstractContainercount + " index abstracts, " +
(System.currentTimeMillis() - timestamp) + " milliseconds");
-
+
prop.put("searchtime", System.currentTimeMillis() - timestamp);
final int links = prop.getInt("linkcount",0);
diff --git a/htroot/yacysearch.html b/htroot/yacysearch.html
index dd394f22b..4702f51a6 100644
--- a/htroot/yacysearch.html
+++ b/htroot/yacysearch.html
@@ -162,7 +162,7 @@ document.getElementById("Enter").value = "search again";
::
<p>No Results.</p>
::
- <p>No Results. (length of search words must be at least 3 characters)</p>
+ <p>No Results. (length of search words must be at least 2 characters)</p>
::
<div id="results"></div>
<span id="resCounter" style="display: inline;"><strong id="resultsOffset">#[offset]#</strong>-<strong id="itemscount">#[itemscount]#</strong> of <strong id="totalcount">#[totalcount]#</strong> #(globalresults)#::; (<strong id="localResourceSize">#[localResourceSize]#</strong> local, <strong id="remoteResourceSize">#[remoteResourceSize]#</strong> remote), <strong id="remoteIndexCount">#[remoteIndexCount]#</strong> from <strong id="remotePeerCount">#[remotePeerCount]#</strong> remote YaCy peers.#(/globalresults)#</span>
@@ -227,7 +227,7 @@ function latestinfo() {
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
var rsp = eval("(" + self.xmlHttpReq.responseText + ")");
- statistics(rsp.offset, rsp.itemscount, rsp.totalcount, rsp.localResourceSize, rsp.remoteResourceSize, rsp.remoteIndexCount, rsp.remotePeerCount);
+ statistics(rsp.offset, rsp.itemscount, rsp.itemsperpage, rsp.totalcount, rsp.localResourceSize, rsp.remoteResourceSize, rsp.remoteIndexCount, rsp.remotePeerCount);
}
}
self.xmlHttpReq.send(null);
diff --git a/htroot/yacysearch.java b/htroot/yacysearch.java
index 2f763d89c..531ecc707 100644
--- a/htroot/yacysearch.java
+++ b/htroot/yacysearch.java
@@ -43,6 +43,7 @@ import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.protocol.ResponseHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.LibraryProvider;
@@ -56,12 +57,9 @@ import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.Bitfield;
import net.yacy.kelondro.util.EventTracker;
import net.yacy.kelondro.util.Formatter;
+import net.yacy.kelondro.util.ISO639;
import net.yacy.kelondro.util.MemoryControl;
import net.yacy.kelondro.util.SetTools;
-import net.yacy.kelondro.util.ISO639;
-
-import de.anomic.crawler.CrawlProfile;
-import de.anomic.crawler.CrawlProfile.CacheStrategy;
import de.anomic.data.DidYouMean;
import de.anomic.data.UserDB;
import de.anomic.search.AccessTracker;
@@ -78,18 +76,18 @@ import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.server.servletProperties;
+import de.anomic.yacy.yacyChannel;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.graphics.ProfilingGraph;
-import de.anomic.yacy.yacyChannel;
public class yacysearch {
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
sb.localSearchLastAccess = System.currentTimeMillis();
-
+
final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
-
+
boolean authenticated = sb.adminAuthenticated(header) >= 2;
if (!authenticated) {
final UserDB.Entry user = sb.userDB.getUser(header);
@@ -101,14 +99,14 @@ public class yacysearch {
env.getConfig("network.unit.description", "") :
env.getConfig(SwitchboardConstants.GREETING, "");
final String client = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search
-
+
// get query
final String originalquerystring = (post == null) ? "" : post.get("query", post.get("search", "")).trim();
String querystring = originalquerystring.replace('+', ' ').replace('*', ' ').trim();
- CrawlProfile.CacheStrategy snippetFetchStrategy = (post == null) ? null : CrawlProfile.CacheStrategy.parse(post.get("verify", "cacheonly"));
+ CacheStrategy snippetFetchStrategy = (post == null) ? null : CacheStrategy.parse(post.get("verify", "cacheonly"));
final servletProperties prop = new servletProperties();
prop.put("topmenu", sb.getConfigBool("publicTopmenu", true) ? 1 : 0);
-
+
// get segment
Segment indexSegment = null;
if (post != null && post.containsKey("segment")) {
@@ -120,7 +118,7 @@ public class yacysearch {
// take default segment
indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
}
-
+
final String EXT = header.get("EXT", "");
final boolean rss = EXT.equals("rss");
final boolean json = EXT.equals("json");
@@ -161,7 +159,7 @@ public class yacysearch {
prop.put("meanCount", 5);
return prop;
}
-
+
// check for JSONP
if (post.containsKey("callback")) {
final String jsonp = post.get("callback")+ "([";
@@ -171,28 +169,28 @@ public class yacysearch {
prop.put("jsonp-start", "");
prop.put("jsonp-end", "");
}
-
+
// Adding CORS Access header for yacysearch.rss output
if (rss) {
final ResponseHeader outgoingHeader = new ResponseHeader();
outgoingHeader.put(HeaderFramework.CORS_ALLOW_ORIGIN, "*");
prop.setOutgoingHeader(outgoingHeader);
}
-
+
// collect search attributes
final boolean newsearch =post.hasValue("query") && post.hasValue("former") && !post.get("query","").equalsIgnoreCase(post.get("former","")); //new search term
-
+
int itemsPerPage = Math.min((authenticated) ? (snippetFetchStrategy != null && snippetFetchStrategy.isAllowedToFetchOnline() ? 100 : 1000) : (snippetFetchStrategy != null && snippetFetchStrategy.isAllowedToFetchOnline() ? 20 : 500), post.getInt("maximumRecords", post.getInt("count", 10))); // SRU syntax with old property as alternative
int offset = (newsearch) ? 0 : post.getInt("startRecord", post.getInt("offset", 0));
-
+
final int newcount;
if ( authenticated && (newcount = post.getInt("count", 0)) > 0 ) {
sb.setConfig(SwitchboardConstants.SEARCH_ITEMS, newcount);
} // set new default maximumRecords if search with "more options"
-
+
boolean global = post.get("resource", "local").equals("global") && sb.peers.sizeConnected() > 0;
- final boolean indexof = (post != null && post.get("indexof","").equals("on"));
-
+ final boolean indexof = (post != null && post.get("indexof","").equals("on"));
+
final String originalUrlMask;
if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) { // option search all
originalUrlMask = ".*";
@@ -212,19 +210,19 @@ public class yacysearch {
constraint = new Bitfield(4);
constraint.set(Condenser.flag_cat_indexof, true);
}
-
+
// SEARCH
final boolean indexReceiveGranted = sb.getConfigBool(SwitchboardConstants.INDEX_RECEIVE_ALLOW, true) ||
sb.getConfigBool(SwitchboardConstants.INDEX_RECEIVE_AUTODISABLED, true);
global = global && indexReceiveGranted; // if the user does not want indexes from remote peers, it cannot be a global search
-
+
final boolean clustersearch = sb.isRobinsonMode() &&
(sb.getConfig("cluster.mode", "").equals("privatecluster") ||
sb.getConfig("cluster.mode", "").equals("publiccluster"));
if (clustersearch) {
global = true;
} // switches search on, but search target is limited to cluster nodes
-
+
// increase search statistic counter
if (!global) {
// we count only searches on the local peer here, because global searches
@@ -239,15 +237,15 @@ public class yacysearch {
sb.searchQueriesRobinsonFromRemote++;
}
}
-
+
// find search domain
final ContentDomain contentdom = ContentDomain.contentdomParser(post == null ? "text" : post.get("contentdom", "text"));
-
+
// patch until better search profiles are available
if ((contentdom != ContentDomain.TEXT) && (itemsPerPage <= 32)) {
itemsPerPage = 64;
}
-
+
// check the search tracker
TreeSet<Long> trackerHandles = sb.localSearchTracker.get(client);
if (trackerHandles == null) {
@@ -266,9 +264,9 @@ public class yacysearch {
} else if (!authenticated && !localhostAccess) {
// in case that we do a global search or we want to fetch snippets, we check for DoS cases
synchronized (trackerHandles) {
- int accInThreeSeconds = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 3000)).size();
- int accInOneMinute = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 60000)).size();
- int accInTenMinutes = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 600000)).size();
+ final int accInThreeSeconds = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 3000)).size();
+ final int accInOneMinute = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 60000)).size();
+ final int accInTenMinutes = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 600000)).size();
// protections against too strong YaCy network load, reduces remote search
if (global) {
if (accInTenMinutes >= 60 || accInOneMinute >= 6 || accInThreeSeconds >= 1) {
@@ -290,16 +288,16 @@ public class yacysearch {
}
}
}
-
+
if ((!block) && (post == null || post.get("cat", "href").equals("href"))) {
String urlmask = null;
-
+
// check available memory and clean up if necessary
if (!MemoryControl.request(8000000L, false)) {
indexSegment.urlMetadata().clearCache();
SearchEventCache.cleanupEvents(true);
}
-
+
final RankingProfile ranking = sb.getRanking();
if (querystring.indexOf("/near") >= 0) {
@@ -317,7 +315,7 @@ public class yacysearch {
}
constraint.set(Condenser.flag_cat_haslocation, true);
}
- int lrp = querystring.indexOf("/language/");
+ final int lrp = querystring.indexOf("/language/");
String lr = "";
if (lrp >= 0) {
if (querystring.length() >= (lrp + 11)) {
@@ -333,7 +331,7 @@ public class yacysearch {
if (ftb == -1) {
ftb = querystring.length();
}
- String urlstr = querystring.substring(inurl + 6, ftb);
+ final String urlstr = querystring.substring(inurl + 6, ftb);
querystring = querystring.replace("inurl:" + urlstr, "");
if (!urlstr.isEmpty()) {
urlmask = ".*" + urlstr + ".*";
@@ -368,7 +366,7 @@ public class yacysearch {
} else urlmask = ".*" + tenant + urlmask;
}
}
- int site = querystring.indexOf("site:");
+ final int site = querystring.indexOf("site:");
String sitehash = null;
String sitehost = null;
if (site >= 0) {
@@ -386,17 +384,17 @@ public class yacysearch {
}
sitehash = DigestURI.hosthash(sitehost);
}
-
+
final int heuristicScroogle = querystring.indexOf("heuristic:scroogle");
if (heuristicScroogle >= 0) {
querystring = querystring.replace("heuristic:scroogle", "");
}
-
+
final int heuristicBlekko = querystring.indexOf("heuristic:blekko");
if (heuristicBlekko >= 0) {
querystring = querystring.replace("heuristic:blekko", "");
}
-
+
final int authori = querystring.indexOf("author:");
String authorhash = null;
if (authori >= 0) {
@@ -441,7 +439,7 @@ public class yacysearch {
if (urlmask == null || urlmask.isEmpty()) {
urlmask = originalUrlMask;
} //if no urlmask was given
-
+
// read the language from the language-restrict option 'lr'
// if no one is given, use the user agent or the system language as default
String language = (post == null) ? lr : post.get("lr", lr);
@@ -459,14 +457,14 @@ public class yacysearch {
language = "en";
}
}
-
+
// navigation
final String navigation = (post == null) ? sb.getConfig("search.navigation", "all") : post.get("nav", "");
-
+
// the query
final TreeSet<String>[] query = QueryParams.cleanQuery(querystring.trim()); // converts also umlaute
-
- int maxDistance = (querystring.indexOf('"') >= 0) ? query.length - 1 : Integer.MAX_VALUE;
+
+ final int maxDistance = (querystring.indexOf('"') >= 0) ? query.length - 1 : Integer.MAX_VALUE;
// filter out stopwords
final SortedSet<String> filtered = SetTools.joinConstructive(query[0], Switchboard.stopwords);
@@ -494,7 +492,7 @@ public class yacysearch {
map.put("refid", "");
sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map);
}
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
@@ -511,9 +509,9 @@ public class yacysearch {
final URIMetadataRow.Components metadata = urlentry.metadata();
Document[] documents = null;
try {
- documents = sb.loader.loadDocuments(sb.loader.request(metadata.url(), true, false), CrawlProfile.CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE);
- } catch (IOException e) {
- } catch (Parser.Failure e) {
+ documents = sb.loader.loadDocuments(sb.loader.request(metadata.url(), true, false), CacheStrategy.IFEXIST, 5000, Long.MAX_VALUE);
+ } catch (final IOException e) {
+ } catch (final Parser.Failure e) {
}
if (documents != null) {
// create a news message
@@ -531,11 +529,11 @@ public class yacysearch {
// prepare search properties
final boolean globalsearch = (global) && indexReceiveGranted;
-
+
// do the search
final HandleSet queryHashes = Word.words2hashesHandles(query[0]);
final Pattern snippetPattern = QueryParams.stringSearchPattern(originalquerystring);
-
+
// check filters
try {
Pattern.compile(urlmask);
@@ -587,13 +585,13 @@ public class yacysearch {
sb.getConfigBool(SwitchboardConstants.NETWORK_SEARCHVERIFY, false) && sb.peers.mySeed().getFlagAcceptRemoteIndex());
EventTracker.delete(EventTracker.EClass.SEARCH);
EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.Type.INITIALIZATION, "", 0, 0), false);
-
+
// tell all threads to do nothing for a specific time
sb.intermissionAllThreads(3000);
-
+
// filter out words that appear in bluelist
theQuery.filterOut(Switchboard.blueList);
-
+
// log
Log.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + QueryParams.hashSet2hashString(theQuery.queryHashes) + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed");
yacyChannel.channels(yacyChannel.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, ""));
@@ -601,7 +599,7 @@ public class yacysearch {
// create a new search event
if (SearchEventCache.getEvent(theQuery.id(false)) == null) {
- theQuery.setOffset(0); // in case that this is a new search, always start without a offset
+ theQuery.setOffset(0); // in case that this is a new search, always start without a offset
offset = 0;
}
final SearchEvent theSearch = SearchEventCache.getEvent(
@@ -612,8 +610,8 @@ public class yacysearch {
(int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_MULTIWORD, 0));
try {
Thread.sleep(global ? 100 : 10);
- } catch (InterruptedException e1) {} // wait a little time to get first results in the search
-
+ } catch (final InterruptedException e1) {} // wait a little time to get first results in the search
+
if (offset == 0) {
if (sitehost != null && sb.getConfigBool("heuristic.site", false) && authenticated) {
sb.heuristicSite(theSearch, sitehost);
@@ -640,7 +638,7 @@ public class yacysearch {
theQuery.urlretrievaltime = theSearch.result().getURLRetrievalTime();
theQuery.snippetcomputationtime = theSearch.result().getSnippetComputationTime();
AccessTracker.add(AccessTracker.Location.local, theQuery);
-
+
// check suggestions
final int meanMax = (post != null) ? post.getInt("meanCount", 0) : 0;
@@ -654,7 +652,7 @@ public class yacysearch {
suggestion = meanIt.next();
prop.put("didYouMean_suggestions_"+meanCount+"_word", suggestion);
prop.put("didYouMean_suggestions_"+meanCount+"_url",
- QueryParams.navurl("html", 0, theQuery, suggestion, originalUrlMask.toString(), theQuery.navigators)
+ QueryParams.navurl("html", 0, theQuery, suggestion, originalUrlMask.toString(), theQuery.navigators).toString()
);
prop.put("didYouMean_suggestions_"+meanCount+"_sep","|");
meanCount++;
@@ -665,7 +663,7 @@ public class yacysearch {
} else {
prop.put("didYouMean", 0);
}
-
+
// find geographic info
final SortedSet<Location> coordinates = LibraryProvider.geoLoc.find(originalquerystring, false);
if (coordinates == null || coordinates.isEmpty() || offset > 0) {
@@ -682,7 +680,7 @@ public class yacysearch {
prop.put("geoinfo_loc", i);
prop.put("geoinfo", "1");
}
-
+
// update the search tracker
try {
synchronized (trackerHandles) {
@@ -696,10 +694,10 @@ public class yacysearch {
sb.localSearchTracker.remove(sb.localSearchTracker.keys().nextElement());
}
if (MemoryControl.shortStatus()) sb.localSearchTracker.clear();
- } catch (Exception e) {
+ } catch (final Exception e) {
Log.logException(e);
}
-
+
final int indexcount = theSearch.getRankingResult().getLocalIndexCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount();
prop.put("num-results_offset", offset);
prop.put("num-results_itemscount", Formatter.number(0, true));
@@ -711,7 +709,7 @@ public class yacysearch {
prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
-
+
// compose page navigation
final StringBuilder resnav = new StringBuilder();
final int thispage = offset / theQuery.displayResults();
@@ -719,11 +717,11 @@ public class yacysearch {
resnav.append("<img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" />&nbsp;");
} else {
resnav.append("<a id=\"prevpage\" href=\"");
- resnav.append(QueryParams.navurl("html", thispage - 1, theQuery, null, originalUrlMask, navigation));
+ resnav.append(QueryParams.navurl("html", thispage - 1, theQuery, null, originalUrlMask, navigation).toString());
resnav.append("\"><img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /></a>&nbsp;");
}
final int numberofpages = Math.min(10, 1 + ((indexcount - 1) / theQuery.displayResults()));
-
+
for (int i = 0; i < numberofpages; i++) {
if (i == thispage) {
resnav.append("<img src=\"env/grafics/navs");
@@ -733,7 +731,7 @@ public class yacysearch {
resnav.append("\" width=\"16\" height=\"16\" />&nbsp;");
} else {
resnav.append("<a href=\"");
- resnav.append(QueryParams.navurl("html", i, theQuery, null, originalUrlMask, navigation));
+ resnav.append(QueryParams.navurl("html", i, theQuery, null, originalUrlMask, navigation).toString());
resnav.append("\"><img src=\"env/grafics/navd");
resnav.append(i + 1);
resnav.append(".gif\" alt=\"page");
@@ -745,14 +743,14 @@ public class yacysearch {
resnav.append("<img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" />");
} else {
resnav.append("<a id=\"nextpage\" href=\"");
- resnav.append(QueryParams.navurl("html", thispage + 1, theQuery, null, originalUrlMask, navigation));
+ resnav.append(QueryParams.navurl("html", thispage + 1, theQuery, null, originalUrlMask, navigation).toString());
resnav.append("\"><img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" /></a>");
}
final String resnavs = resnav.toString();
prop.put("num-results_resnav", resnavs);
prop.put("pageNavBottom", (indexcount - offset > 6) ? 1 : 0); // if there are more results than may fit on the page we add a navigation at the bottom
prop.put("pageNavBottom_resnav", resnavs);
-
+
// generate the search result lines; the content will be produced by another servlet
for (int i = 0; i < theQuery.displayResults(); i++) {
prop.put("results_" + i + "_item", offset + i);
@@ -761,7 +759,7 @@ public class yacysearch {
prop.put("results", theQuery.displayResults());
prop.put("resultTable", (contentdom == ContentDomain.APP || contentdom == ContentDomain.AUDIO || contentdom == ContentDomain.VIDEO) ? 1 : 0);
prop.put("eventID", theQuery.id(false)); // for bottomline
-
+
// process result of search
if (!filtered.isEmpty()) {
prop.put("excluded", "1");
@@ -771,8 +769,8 @@ public class yacysearch {
}
if (prop == null || prop.isEmpty()) {
- if (post.get("query", post.get("search", "")).length() < 3) {
- prop.put("num-results", "2"); // no results - at least 3 chars
+ if (post.get("query", post.get("search", "")).length() < 2) {
+ prop.put("num-results", "2"); // no results - at least 2 chars
} else {
prop.put("num-results", "1"); // no results
}
@@ -791,7 +789,7 @@ public class yacysearch {
prop.put("searchBaseURL", "http://" + hostName + "/yacysearch.html");
prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif");
}
-
+
prop.put("searchagain", global ? "1" : "0");
prop.putHTML("former", originalquerystring);
prop.put("count", itemsPerPage);
@@ -829,9 +827,9 @@ public class yacysearch {
// for RSS: don't HTML encode some elements
prop.putXML("rss_query", originalquerystring);
prop.putXML("rss_queryenc", originalquerystring.replace(' ', '+'));
-
+
sb.localSearchLastAccess = System.currentTimeMillis();
-
+
// return rewrite properties
return prop;
}
diff --git a/htroot/yacysearchitem.html b/htroot/yacysearchitem.html
index b1f88a6ed..61bdad4cb 100644
--- a/htroot/yacysearchitem.html
+++ b/htroot/yacysearchitem.html
@@ -53,7 +53,7 @@
#(/content)#
<script type="text/javascript">
-statistics("#[offset]#", "#[itemscount]#", "#[totalcount]#", "#[localResourceSize]#", "#[remoteResourceSize]#", "#[remoteIndexCount]#", "#[remotePeerCount]#");
+statistics("#[offset]#", "#[itemscount]#", "#[itemsperpage]#", "#[totalcount]#", "#[localResourceSize]#", "#[remoteResourceSize]#", "#[remoteIndexCount]#", "#[remotePeerCount]#");
progressbar.step(1);
</script>
diff --git a/htroot/yacysearchitem.java b/htroot/yacysearchitem.java
index 201577e31..d44f469cc 100644
--- a/htroot/yacysearchitem.java
+++ b/htroot/yacysearchitem.java
@@ -9,7 +9,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -36,12 +36,11 @@ import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.EventTracker;
import net.yacy.kelondro.util.Formatter;
-
import de.anomic.search.ContentDomain;
import de.anomic.search.MediaSnippet;
import de.anomic.search.QueryParams;
-import de.anomic.search.SearchEvent;
import de.anomic.search.ResultEntry;
+import de.anomic.search.SearchEvent;
import de.anomic.search.SearchEventCache;
import de.anomic.search.Switchboard;
import de.anomic.search.SwitchboardConstants;
@@ -56,18 +55,18 @@ import de.anomic.yacy.graphics.ProfilingGraph;
public class yacysearchitem {
-
+
private static final String SHORTEN_SUFFIX = "...";
private static final int SHORTEN_SUFFIX_LENGTH = SHORTEN_SUFFIX.length();
private static final int MAX_NAME_LENGTH = 60;
private static final int MAX_URL_LENGTH = 120;
private static boolean col = true;
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
-
+
final String eventID = post.get("eventID", "");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int item = post.getInt("item", -1);
@@ -82,7 +81,7 @@ public class yacysearchitem {
prop.put("references", "0");
prop.put("rssreferences", "0");
prop.put("dynamic", "0");
-
+
// find search event
final SearchEvent theSearch = SearchEventCache.getEvent(eventID);
if (theSearch == null) {
@@ -90,19 +89,20 @@ public class yacysearchitem {
return prop;
}
final QueryParams theQuery = theSearch.getQuery();
-
+
// dynamically update count values
final int totalcount = theSearch.getRankingResult().getLocalIndexCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount();
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", Formatter.number(Math.min((item < 0) ? theQuery.neededResults() : item + 1, totalcount)));
+ prop.put("itemsperpage", Formatter.number(theQuery.itemsPerPage));
prop.put("totalcount", Formatter.number(totalcount, true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalIndexCount(), true));
prop.put("localMissCount", Formatter.number(theSearch.getRankingResult().getMissCount(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
-
+
final String target = sb.getConfig(SwitchboardConstants.SEARCH_TARGET, "_self");
if (theQuery.contentdom == ContentDomain.TEXT) {
// text search
@@ -120,7 +120,7 @@ public class yacysearchitem {
Log.logException(e1);
faviconURL = null;
}
-
+
prop.put("content", 1); // switch on specific content
prop.put("content_showDate", sb.getConfigBool("search.result.show.date", true) ? 1 : 0);
prop.put("content_showSize", sb.getConfigBool("search.result.show.size", true) ? 1 : 0);
@@ -132,7 +132,7 @@ public class yacysearchitem {
prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?query=" + theQuery.queryString.replace(' ', '+') + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + ASCII.String(result.hash()) + "&urlmaskfilter=.*");
prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?query=" + theQuery.queryString.replace(' ', '+') + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + ASCII.String(result.hash()) + "&urlmaskfilter=.*");
prop.put("content_authorized_urlhash", ASCII.String(result.hash()));
- String resulthashString = ASCII.String(result.hash());
+ final String resulthashString = ASCII.String(result.hash());
prop.putHTML("content_title", result.title());
prop.putXML("content_title-xml", result.title());
prop.putJSON("content_title-json", result.title());
@@ -175,7 +175,7 @@ public class yacysearchitem {
prop.put("content_description", desc);
prop.putXML("content_description-xml", desc);
prop.putJSON("content_description-json", desc);
- SearchEvent.HeuristicResult heuristic = theSearch.getHeuristic(result.hash());
+ final SearchEvent.HeuristicResult heuristic = theSearch.getHeuristic(result.hash());
if (heuristic == null) {
prop.put("content_heuristic", 0);
} else {
@@ -189,7 +189,7 @@ public class yacysearchitem {
EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.Type.FINALIZATION, "" + item, 0, 0), false);
final String ext = resultURL.getFileExtension().toLowerCase();
if (ext.equals("png") || ext.equals("jpg") || ext.equals("gif")) {
- String license = sb.licensedURLs.aquireLicense(resultURL);
+ final String license = sb.licensedURLs.aquireLicense(resultURL);
prop.put("content_code", license);
} else {
prop.put("content_code", "");
@@ -234,7 +234,7 @@ public class yacysearchitem {
theQuery.transmitcount = item + 1;
return prop;
}
-
+
if ((theQuery.contentdom == ContentDomain.AUDIO) ||
(theQuery.contentdom == ContentDomain.VIDEO) ||
(theQuery.contentdom == ContentDomain.APP)) {
@@ -243,7 +243,7 @@ public class yacysearchitem {
// generate result object
final ResultEntry result = theSearch.oneResult(item, 500);
if (result == null) return prop; // no content
-
+
prop.put("content", theQuery.contentdom.getCode() + 1); // switch on specific content
final List<MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
@@ -265,10 +265,10 @@ public class yacysearchitem {
theQuery.transmitcount = item + 1;
return prop;
}
-
+
return prop;
}
-
+
private static String shorten(final String s, final int length) {
final String ret;
if (s.length() <= length) {
@@ -289,7 +289,7 @@ public class yacysearchitem {
}
return ret;
}
-
+
private static String sizename(int size) {
if (size < 1024) return size + " bytes";
size = size / 1024;
diff --git a/htroot/yacysearchlatestinfo.java b/htroot/yacysearchlatestinfo.java
index ca303b6cb..5ca112ac6 100644
--- a/htroot/yacysearchlatestinfo.java
+++ b/htroot/yacysearchlatestinfo.java
@@ -1,6 +1,5 @@
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.kelondro.util.Formatter;
-
import de.anomic.search.QueryParams;
import de.anomic.search.SearchEvent;
import de.anomic.search.SearchEventCache;
@@ -9,11 +8,11 @@ import de.anomic.server.serverSwitch;
public class yacysearchlatestinfo {
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final serverObjects prop = new serverObjects();
//Switchboard sb = (Switchboard) env;
-
+
// find search event
final String eventID = post.get("eventID", "");
final SearchEvent theSearch = SearchEventCache.getEvent(eventID);
@@ -23,20 +22,21 @@ public class yacysearchlatestinfo {
}
final QueryParams theQuery = theSearch.getQuery();
//if (sb.isGlobalMode() && !theQuery.isLocal()) try {Thread.sleep(1000);} catch (InterruptedException e) {}
-
+
// dynamically update count values
final int totalcount = theSearch.getRankingResult().getLocalIndexCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount();
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", -1);
+ prop.put("itemsperpage", theSearch.getQuery().itemsPerPage);
prop.put("totalcount", Formatter.number(totalcount, true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalIndexCount(), true));
prop.put("localMissCount", Formatter.number(theSearch.getRankingResult().getMissCount(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
-
+
return prop;
}
-
+
}
diff --git a/htroot/yacysearchlatestinfo.json b/htroot/yacysearchlatestinfo.json
index 50dc1460b..b58401deb 100644
--- a/htroot/yacysearchlatestinfo.json
+++ b/htroot/yacysearchlatestinfo.json
@@ -1,5 +1,6 @@
{
"itemscount": "#[itemscount]#",
+"itemsperpage": "#[itemsperpage]#",
"totalcount": "#[totalcount]#",
"localResourceSize": "#[localResourceSize]#",
"localMissCount": "#[localMissCount]#",
diff --git a/htroot/yacysearchtrailer.java b/htroot/yacysearchtrailer.java
index c1d75aa01..3bd83d56d 100644
--- a/htroot/yacysearchtrailer.java
+++ b/htroot/yacysearchtrailer.java
@@ -9,7 +9,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -30,7 +30,6 @@ import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.storage.ScoreMap;
import net.yacy.document.LibraryProvider;
import net.yacy.kelondro.util.EventTracker;
-
import de.anomic.search.QueryParams;
import de.anomic.search.SearchEvent;
import de.anomic.search.SearchEventCache;
@@ -42,12 +41,12 @@ import de.anomic.yacy.graphics.ProfilingGraph;
public class yacysearchtrailer {
private static final int MAX_TOPWORDS = 12;
-
+
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final serverObjects prop = new serverObjects();
-
+
final String eventID = post.get("eventID", "");
-
+
// find search event
final SearchEvent theSearch = SearchEventCache.getEvent(eventID);
if (theSearch == null) {
@@ -55,11 +54,11 @@ public class yacysearchtrailer {
return prop;
}
final QueryParams theQuery = theSearch.getQuery();
-
+
// compose search navigation
// namespace navigators
- ScoreMap<String> namespaceNavigator = theSearch.getNamespaceNavigator();
+ final ScoreMap<String> namespaceNavigator = theSearch.getNamespaceNavigator();
String name;
int count;
Iterator<String> navigatorIterator;
@@ -73,8 +72,8 @@ public class yacysearchtrailer {
name = navigatorIterator.next();
count = namespaceNavigator.get(name);
prop.putJSON("nav-namespace_element_" + i + "_name", name);
- prop.put("nav-namespace_element_" + i + "_url", "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + "inurl:" + name, theQuery.urlMask.toString(), theQuery.navigators) + "\">" + name + " (" + count + ")</a>");
- prop.putJSON("nav-namespace_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + "inurl:" + name, theQuery.urlMask.toString(), theQuery.navigators));
+ prop.put("nav-namespace_element_" + i + "_url", "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + "inurl:" + name, theQuery.urlMask.toString(), theQuery.navigators).toString() + "\">" + name + " (" + count + ")</a>");
+ prop.putJSON("nav-namespace_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + "inurl:" + name, theQuery.urlMask.toString(), theQuery.navigators).toString());
prop.put("nav-namespace_element_" + i + "_count", count);
prop.put("nav-namespace_element_" + i + "_modifier", "inurl:" + name);
prop.put("nav-namespace_element_" + i + "_nl", 1);
@@ -84,9 +83,9 @@ public class yacysearchtrailer {
i--;
prop.put("nav-namespace_element_" + i + "_nl", 0);
}
-
+
// host navigators
- ScoreMap<String> hostNavigator = theSearch.getHostNavigator();
+ final ScoreMap<String> hostNavigator = theSearch.getHostNavigator();
if (hostNavigator == null || hostNavigator.isEmpty()) {
prop.put("nav-domains", 0);
} else {
@@ -97,8 +96,8 @@ public class yacysearchtrailer {
name = navigatorIterator.next();
count = hostNavigator.get(name);
prop.putJSON("nav-domains_element_" + i + "_name", name);
- prop.put("nav-domains_element_" + i + "_url", "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + "site:" + name, theQuery.urlMask.toString(), theQuery.navigators) + "\">" + name + " (" + count + ")</a>");
- prop.putJSON("nav-domains_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + "site:" + name, theQuery.urlMask.toString(), theQuery.navigators));
+ prop.put("nav-domains_element_" + i + "_url", "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + "site:" + name, theQuery.urlMask.toString(), theQuery.navigators).toString() + "\">" + name + " (" + count + ")</a>");
+ prop.putJSON("nav-domains_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + "site:" + name, theQuery.urlMask.toString(), theQuery.navigators).toString());
prop.put("nav-domains_element_" + i + "_count", count);
prop.put("nav-domains_element_" + i + "_modifier", "site:" + name);
prop.put("nav-domains_element_" + i + "_nl", 1);
@@ -108,9 +107,9 @@ public class yacysearchtrailer {
i--;
prop.put("nav-domains_element_" + i + "_nl", 0);
}
-
+
// author navigators
- ScoreMap<String> authorNavigator = theSearch.getAuthorNavigator();
+ final ScoreMap<String> authorNavigator = theSearch.getAuthorNavigator();
if (authorNavigator == null || authorNavigator.isEmpty()) {
prop.put("nav-authors", 0);
} else {
@@ -123,8 +122,8 @@ public class yacysearchtrailer {
count = authorNavigator.get(name);
anav = (name.indexOf(' ') < 0) ? "author:" + name : "author:'" + name.replace(" ", "+") + "'";
prop.putJSON("nav-authors_element_" + i + "_name", name);
- prop.put("nav-authors_element_" + i + "_url", "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + anav, theQuery.urlMask.toString(), theQuery.navigators) + "\">" + name + " (" + count + ")</a>");
- prop.putJSON("nav-authors_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + anav, theQuery.urlMask.toString(), theQuery.navigators));
+ prop.put("nav-authors_element_" + i + "_url", "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + anav, theQuery.urlMask.toString(), theQuery.navigators).toString() + "\">" + name + " (" + count + ")</a>");
+ prop.putJSON("nav-authors_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + anav, theQuery.urlMask.toString(), theQuery.navigators).toString());
prop.put("nav-authors_element_" + i + "_count", count);
prop.put("nav-authors_element_" + i + "_modifier", "author:'" + name + "'");
prop.put("nav-authors_element_" + i + "_nl", 1);
@@ -136,7 +135,7 @@ public class yacysearchtrailer {
}
// topics navigator
- ScoreMap<String> topicNavigator = theSearch.getTopicNavigator(MAX_TOPWORDS);
+ final ScoreMap<String> topicNavigator = theSearch.getTopicNavigator(MAX_TOPWORDS);
if (topicNavigator == null || topicNavigator.isEmpty()) {
prop.put("nav-topics", "0");
} else {
@@ -150,9 +149,9 @@ public class yacysearchtrailer {
if (name != null) {
prop.putJSON("nav-topics_element_" + i + "_name", name);
prop.put("nav-topics_element_" + i + "_url",
- "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + name, theQuery.urlMask.toString(), theQuery.navigators) + "\">" + name + "</a>");
+ "<a href=\"" + QueryParams.navurl("html", 0, theQuery, theQuery.queryStringForUrl() + "+" + name, theQuery.urlMask.toString(), theQuery.navigators).toString() + "\">" + name + "</a>");
//+"<a href=\"" + QueryParams.navurl("html", 0, display, theQuery, theQuery.queryStringForUrl() + "+-" + name, theQuery.urlMask.toString(), theQuery.navigators) + "\">-</a>")*/;
- prop.putJSON("nav-topics_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + name, theQuery.urlMask.toString(), theQuery.navigators));
+ prop.putJSON("nav-topics_element_" + i + "_url-json", QueryParams.navurl("json", 0, theQuery, theQuery.queryStringForUrl() + "+" + name, theQuery.urlMask.toString(), theQuery.navigators).toString());
prop.put("nav-topics_element_" + i + "_count", count);
prop.put("nav-topics_element_" + i + "_modifier", name);
prop.put("nav-topics_element_" + i + "_nl", 1);
@@ -163,10 +162,10 @@ public class yacysearchtrailer {
i--;
prop.put("nav-topics_element_" + i + "_nl", 0);
}
-
+
// about box
- String aboutBody = env.getConfig("about.body", "");
- String aboutHeadline = env.getConfig("about.headline", "");
+ final String aboutBody = env.getConfig("about.body", "");
+ final String aboutHeadline = env.getConfig("about.headline", "");
if ((aboutBody.length() == 0 && aboutHeadline.length() == 0) ||
theSearch.getRankingResult().getLocalIndexCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount() == 0) {
prop.put("nav-about", 0);
@@ -175,7 +174,7 @@ public class yacysearchtrailer {
prop.put("nav-about_headline", aboutHeadline);
prop.put("nav-about_body", aboutBody);
}
-
+
// category: location search
// show only if there is a location database present and if there had been any search results
if (LibraryProvider.geoLoc.locations() == 0 ||
@@ -184,11 +183,11 @@ public class yacysearchtrailer {
} else {
prop.put("cat-location", 1);
prop.put("cat-location_query", theQuery.queryString(true));
- prop.put("cat-location_queryenc", theQuery.queryString(true).replace(' ', '+'));
+ prop.put("cat-location_queryenc", theQuery.queryString(true).replace(' ', '+'));
}
-
+
EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.Type.FINALIZATION, "bottomline", 0, 0), false);
-
+
return prop;
}
diff --git a/source/de/anomic/crawler/Balancer.java b/source/de/anomic/crawler/Balancer.java
index 28cebbdc5..f2c5ec0a6 100644
--- a/source/de/anomic/crawler/Balancer.java
+++ b/source/de/anomic/crawler/Balancer.java
@@ -1,4 +1,4 @@
-// Balancer.java
+// Balancer.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
@@ -37,9 +37,11 @@ import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentMap;
import net.yacy.cora.document.ASCII;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.index.BufferedObjectIndex;
import net.yacy.kelondro.index.HandleSet;
@@ -51,13 +53,11 @@ import net.yacy.kelondro.order.CloneableIterator;
import net.yacy.kelondro.table.Table;
import net.yacy.kelondro.util.ByteBuffer;
import net.yacy.kelondro.util.MemoryControl;
-
import de.anomic.crawler.retrieval.Request;
import de.anomic.http.client.Cache;
-import java.util.concurrent.ConcurrentMap;
public class Balancer {
-
+
private static final String indexSuffix = "9.db";
private static final int EcoFSBufferSize = 1000;
private static final int objectIndexBufferSize = 1000;
@@ -69,7 +69,7 @@ public class Balancer {
private long minimumGlobalDelta;
private final Set<String> myAgentIDs;
private BufferedObjectIndex urlFileIndex;
-
+
// class variables computed during operation
private final ConcurrentMap<String, HandleSet> domainStacks; // a map from host name to lists with url hashs
private final ConcurrentLinkedQueue<byte[]> top; // a list of url-hashes that shall be taken next
@@ -78,7 +78,7 @@ public class Balancer {
private final HandleSet double_push_check; // for debugging
private long lastDomainStackFill;
private int domStackInitSize;
-
+
public Balancer(
final File cachePath,
final String stackname,
@@ -97,76 +97,76 @@ public class Balancer {
this.domStackInitSize = Integer.MAX_VALUE;
this.ddc = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 0);
this.double_push_check = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 0);
-
+
// create a stack for newly entered entries
if (!(cachePath.exists())) cachePath.mkdir(); // make the path
- cacheStacksPath.mkdirs();
- final File f = new File(cacheStacksPath, stackname + indexSuffix);
+ this.cacheStacksPath.mkdirs();
+ final File f = new File(this.cacheStacksPath, stackname + indexSuffix);
try {
- urlFileIndex = new BufferedObjectIndex(new Table(f, Request.rowdef, EcoFSBufferSize, 0, useTailCache, exceed134217727), objectIndexBufferSize);
- } catch (RowSpaceExceededException e) {
+ this.urlFileIndex = new BufferedObjectIndex(new Table(f, Request.rowdef, EcoFSBufferSize, 0, useTailCache, exceed134217727), objectIndexBufferSize);
+ } catch (final RowSpaceExceededException e) {
try {
- urlFileIndex = new BufferedObjectIndex(new Table(f, Request.rowdef, 0, 0, false, exceed134217727), objectIndexBufferSize);
- } catch (RowSpaceExceededException e1) {
+ this.urlFileIndex = new BufferedObjectIndex(new Table(f, Request.rowdef, 0, 0, false, exceed134217727), objectIndexBufferSize);
+ } catch (final RowSpaceExceededException e1) {
Log.logException(e1);
}
}
- lastDomainStackFill = 0;
- Log.logInfo("Balancer", "opened balancer file with " + urlFileIndex.size() + " entries from " + f.toString());
+ this.lastDomainStackFill = 0;
+ Log.logInfo("Balancer", "opened balancer file with " + this.urlFileIndex.size() + " entries from " + f.toString());
}
public long getMinimumLocalDelta() {
return this.minimumLocalDelta;
}
-
+
public long getMinimumGlobalDelta() {
return this.minimumGlobalDelta;
}
-
+
public void setMinimumDelta(final long minimumLocalDelta, final long minimumGlobalDelta) {
this.minimumLocalDelta = minimumLocalDelta;
this.minimumGlobalDelta = minimumGlobalDelta;
}
-
+
public synchronized void close() {
- if (urlFileIndex != null) {
- urlFileIndex.close();
- urlFileIndex = null;
+ if (this.urlFileIndex != null) {
+ this.urlFileIndex.close();
+ this.urlFileIndex = null;
}
}
-
+
public void clear() {
- Log.logInfo("Balancer", "cleaning balancer with " + urlFileIndex.size() + " entries from " + urlFileIndex.filename());
+ Log.logInfo("Balancer", "cleaning balancer with " + this.urlFileIndex.size() + " entries from " + this.urlFileIndex.filename());
try {
- urlFileIndex.clear();
- } catch (IOException e) {
+ this.urlFileIndex.clear();
+ } catch (final IOException e) {
Log.logException(e);
}
- domainStacks.clear();
- top.clear();
+ this.domainStacks.clear();
+ this.top.clear();
synchronized (this.delayed) {
- delayed.clear();
+ this.delayed.clear();
}
}
-
+
public Request get(final byte[] urlhash) throws IOException {
assert urlhash != null;
- if (urlFileIndex == null) return null; // case occurs during shutdown
- final Row.Entry entry = urlFileIndex.get(urlhash);
+ if (this.urlFileIndex == null) return null; // case occurs during shutdown
+ final Row.Entry entry = this.urlFileIndex.get(urlhash);
if (entry == null) return null;
return new Request(entry);
}
-
+
public int removeAllByProfileHandle(final String profileHandle, final long timeout) throws IOException, RowSpaceExceededException {
// removes all entries with a specific profile hash.
// this may last some time
// returns number of deletions
-
+
// first find a list of url hashes that shall be deleted
final HandleSet urlHashes = Base64Order.enhancedCoder.getHandleSet(this.urlFileIndex.row().primaryKeyLength, 100);
final long terminate = (timeout > 0) ? System.currentTimeMillis() + timeout : Long.MAX_VALUE;
synchronized (this) {
- final Iterator<Row.Entry> i = urlFileIndex.rows();
+ final Iterator<Row.Entry> i = this.urlFileIndex.rows();
Row.Entry rowEntry;
Request crawlEntry;
while (i.hasNext() && (System.currentTimeMillis() < terminate)) {
@@ -177,11 +177,11 @@ public class Balancer {
}
}
}
-
+
// then delete all these urls from the queues and the file index
- return this.remove(urlHashes);
+ return remove(urlHashes);
}
-
+
/**
* this method is only here, because so many import/export methods need it
and it was implemented in the previous architecture
@@ -191,27 +191,27 @@ public class Balancer {
* @throws IOException
*/
public synchronized int remove(final HandleSet urlHashes) throws IOException {
- final int s = urlFileIndex.size();
+ final int s = this.urlFileIndex.size();
int removedCounter = 0;
for (final byte[] urlhash: urlHashes) {
- final Row.Entry entry = urlFileIndex.remove(urlhash);
+ final Row.Entry entry = this.urlFileIndex.remove(urlhash);
if (entry != null) removedCounter++;
-
+
// remove from double-check caches
- ddc.remove(urlhash);
- double_push_check.remove(urlhash);
+ this.ddc.remove(urlhash);
+ this.double_push_check.remove(urlhash);
}
if (removedCounter == 0) return 0;
- assert urlFileIndex.size() + removedCounter == s : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s;
+ assert this.urlFileIndex.size() + removedCounter == s : "urlFileIndex.size() = " + this.urlFileIndex.size() + ", s = " + s;
// iterate through the top list
- final Iterator<byte[]> j = top.iterator();
+ final Iterator<byte[]> j = this.top.iterator();
byte[] urlhash;
while (j.hasNext()) {
urlhash = j.next();
if (urlHashes.has(urlhash)) j.remove();
}
-
+
// remove from delayed
synchronized (this.delayed) {
final Iterator<Map.Entry<Long, byte[]>> k = this.delayed.entrySet().iterator();
@@ -219,9 +219,9 @@ public class Balancer {
if (urlHashes.has(k.next().getValue())) k.remove();
}
}
-
+
// iterate through the domain stacks
- final Iterator<Map.Entry<String, HandleSet>> q = domainStacks.entrySet().iterator();
+ final Iterator<Map.Entry<String, HandleSet>> q = this.domainStacks.entrySet().iterator();
HandleSet stack;
while (q.hasNext()) {
stack = q.next().getValue();
@@ -231,35 +231,35 @@ public class Balancer {
return removedCounter;
}
-
+
public boolean has(final byte[] urlhashb) {
return this.urlFileIndex.has(urlhashb) || this.ddc.has(urlhashb);
}
-
+
public boolean notEmpty() {
// alternative method to the property size() > 0
// this is better because it may avoid synchronized access to domain stack summarization
return domainStacksNotEmpty();
}
-
+
public int size() {
- return urlFileIndex.size();
+ return this.urlFileIndex.size();
}
-
+
public boolean isEmpty() {
- return urlFileIndex.isEmpty();
+ return this.urlFileIndex.isEmpty();
}
-
+
private boolean domainStacksNotEmpty() {
- if (domainStacks == null) return false;
- synchronized (domainStacks) {
- for (final HandleSet l: domainStacks.values()) {
+ if (this.domainStacks == null) return false;
+ synchronized (this.domainStacks) {
+ for (final HandleSet l: this.domainStacks.values()) {
if (!l.isEmpty()) return true;
}
}
return false;
}
-
+
/**
* push a crawl request on the balancer stack
* @param entry
@@ -275,10 +275,10 @@ public class Balancer {
if (this.double_push_check.has(hash)) return "double occurrence in double_push_check";
if (this.ddc.has(hash)) return "double occurrence in ddc";
if (this.urlFileIndex.has(hash)) return "double occurrence in urlFileIndex";
-
+
if (this.double_push_check.size() > 10000 || MemoryControl.shortStatus()) this.double_push_check.clear();
this.double_push_check.put(hash);
-
+
// add to index
final int s = this.urlFileIndex.size();
this.urlFileIndex.put(entry.toRow());
@@ -290,34 +290,34 @@ public class Balancer {
return null;
}
}
-
+
private void pushHashToDomainStacks(String host, final byte[] urlhash) throws RowSpaceExceededException {
// extend domain stack
if (host == null) host = localhost;
- HandleSet domainList = domainStacks.get(host);
+ HandleSet domainList = this.domainStacks.get(host);
if (domainList == null) {
// create new list
domainList = new HandleSet(12, Base64Order.enhancedCoder, 1);
domainList.put(urlhash);
- domainStacks.put(host, domainList);
+ this.domainStacks.put(host, domainList);
} else {
// extend existent domain list
domainList.put(urlhash);
}
}
-
+
private void removeHashFromDomainStacks(String host, final byte[] urlhash) {
// reduce domain stack
if (host == null) host = localhost;
- final HandleSet domainList = domainStacks.get(host);
+ final HandleSet domainList = this.domainStacks.get(host);
if (domainList == null) {
- domainStacks.remove(host);
+ this.domainStacks.remove(host);
return;
}
domainList.remove(urlhash);
- if (domainList.isEmpty()) domainStacks.remove(host);
+ if (domainList.isEmpty()) this.domainStacks.remove(host);
}
-
+
private byte[] nextFromDelayed() {
if (this.delayed.isEmpty()) return null;
final Long first = this.delayed.firstKey();
@@ -326,13 +326,13 @@ public class Balancer {
}
return null;
}
-
+
private byte[] anyFromDelayed() {
if (this.delayed.isEmpty()) return null;
final Long first = this.delayed.firstKey();
return this.delayed.remove(first);
}
-
+
/**
* get the next entry in this crawl queue in such a way that the domain access time delta is maximized
* and always above the given minimum delay time. An additional delay time is computed using the robots.txt
@@ -343,11 +343,11 @@ public class Balancer {
* @param profile
* @return a url in a CrawlEntry object
* @throws IOException
- * @throws RowSpaceExceededException
+ * @throws RowSpaceExceededException
*/
public Request pop(final boolean delay, final CrawlSwitchboard cs) throws IOException {
// returns a crawl entry from the stack and ensures minimum delta times
-
+
try {
filltop(delay, -600000, false);
filltop(delay, -60000, false);
@@ -366,8 +366,8 @@ public class Balancer {
filltop(delay, 4000, true);
filltop(delay, 6000, true);
filltop(delay, Long.MAX_VALUE, true);
- } catch (RowSpaceExceededException e) {}
-
+ } catch (final RowSpaceExceededException e) {}
+
long sleeptime = 0;
Request crawlEntry = null;
synchronized (this) {
@@ -377,36 +377,36 @@ public class Balancer {
byte[] nexthash = nextFromDelayed();
//System.out.println("*** nextFromDelayed=" + nexthash);
if (nexthash == null && !this.top.isEmpty()) {
- nexthash = top.remove();
+ nexthash = this.top.remove();
//System.out.println("*** top.remove()=" + nexthash);
}
if (nexthash == null) {
nexthash = anyFromDelayed();
}
-
+
// check minimumDelta and if necessary force a sleep
//final int s = urlFileIndex.size();
- Row.Entry rowEntry = (nexthash == null) ? null : urlFileIndex.remove(nexthash);
+ Row.Entry rowEntry = (nexthash == null) ? null : this.urlFileIndex.remove(nexthash);
if (rowEntry == null) {
//System.out.println("*** rowEntry=null, nexthash=" + UTF8.String(nexthash));
- rowEntry = urlFileIndex.removeOne();
+ rowEntry = this.urlFileIndex.removeOne();
if (rowEntry == null) {
nexthash = null;
} else {
nexthash = rowEntry.getPrimaryKeyBytes();
//System.out.println("*** rowEntry.getPrimaryKeyBytes()=" + UTF8.String(nexthash));
}
-
+
}
if (rowEntry == null) {
- Log.logWarning("Balancer", "removeOne() failed - size = " + this.size());
+ Log.logWarning("Balancer", "removeOne() failed - size = " + size());
return null;
}
//assert urlFileIndex.size() + 1 == s : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s + ", result = " + result;
-
+
crawlEntry = new Request(rowEntry);
//Log.logInfo("Balancer", "fetched next url: " + crawlEntry.url().toNormalform(true, false));
-
+
// at this point we must check if the crawlEntry has relevance because the crawl profile still exists
// if not: return null. A calling method must handle the null value and try again
final CrawlProfile profileEntry = cs.getActive(UTF8.getBytes(crawlEntry.profileHandle()));
@@ -416,19 +416,19 @@ public class Balancer {
}
// depending on the caching policy we need sleep time to avoid DoS-like situations
sleeptime = (
- profileEntry.cacheStrategy() == CrawlProfile.CacheStrategy.CACHEONLY ||
- (profileEntry.cacheStrategy() == CrawlProfile.CacheStrategy.IFEXIST && Cache.has(crawlEntry.url()))
- ) ? 0 : Latency.waitingRemaining(crawlEntry.url(), myAgentIDs, minimumLocalDelta, minimumGlobalDelta); // this uses the robots.txt database and may cause a loading of robots.txt from the server
-
+ profileEntry.cacheStrategy() == CacheStrategy.CACHEONLY ||
+ (profileEntry.cacheStrategy() == CacheStrategy.IFEXIST && Cache.has(crawlEntry.url()))
+ ) ? 0 : Latency.waitingRemaining(crawlEntry.url(), this.myAgentIDs, this.minimumLocalDelta, this.minimumGlobalDelta); // this uses the robots.txt database and may cause a loading of robots.txt from the server
+
assert Base64Order.enhancedCoder.equal(nexthash, rowEntry.getPrimaryKeyBytes()) : "result = " + ASCII.String(nexthash) + ", rowEntry.getPrimaryKeyBytes() = " + ASCII.String(rowEntry.getPrimaryKeyBytes());
assert Base64Order.enhancedCoder.equal(nexthash, crawlEntry.url().hash()) : "result = " + ASCII.String(nexthash) + ", crawlEntry.url().hash() = " + ASCII.String(crawlEntry.url().hash());
-
+
if (failhash != null && Base64Order.enhancedCoder.equal(failhash, nexthash)) break; // prevent endless loops
-
+
if (delay && sleeptime > 0 && this.domStackInitSize > 1) {
//System.out.println("*** putback: nexthash=" + nexthash + ", failhash="+failhash);
// put that thing back to omit a delay here
- if (!ByteBuffer.contains(delayed.values(), nexthash)) {
+ if (!ByteBuffer.contains(this.delayed.values(), nexthash)) {
//System.out.println("*** delayed +=" + nexthash);
this.delayed.put(Long.valueOf(System.currentTimeMillis() + sleeptime + 1), nexthash);
}
@@ -438,7 +438,7 @@ public class Balancer {
if (host == null) host = localhost;
this.domainStacks.remove(host);
failhash = nexthash;
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
continue;
@@ -447,17 +447,17 @@ public class Balancer {
}
if (crawlEntry != null) {
if (this.ddc.size() > 10000 || MemoryControl.shortStatus()) this.ddc.clear();
- try { this.ddc.put(crawlEntry.url().hash()); } catch (RowSpaceExceededException e) {}
+ try { this.ddc.put(crawlEntry.url().hash()); } catch (final RowSpaceExceededException e) {}
}
}
if (crawlEntry == null) return null;
-
+
if (delay && sleeptime > 0) {
// force a busy waiting here
// in best case, this should never happen if the balancer works propertly
// this is only to protection against the worst case, where the crawler could
// behave in a DoS-manner
- Log.logInfo("BALANCER", "forcing crawl-delay of " + sleeptime + " milliseconds for " + crawlEntry.url().getHost() + ": " + Latency.waitingRemainingExplain(crawlEntry.url(), myAgentIDs, minimumLocalDelta, minimumGlobalDelta) + ", top.size() = " + top.size() + ", delayed.size() = " + delayed.size() + ", domainStacks.size() = " + domainStacks.size() + ", domainStacksInitSize = " + this.domStackInitSize);
+ Log.logInfo("BALANCER", "forcing crawl-delay of " + sleeptime + " milliseconds for " + crawlEntry.url().getHost() + ": " + Latency.waitingRemainingExplain(crawlEntry.url(), this.myAgentIDs, this.minimumLocalDelta, this.minimumGlobalDelta) + ", top.size() = " + this.top.size() + ", delayed.size() = " + this.delayed.size() + ", domainStacks.size() = " + this.domainStacks.size() + ", domainStacksInitSize = " + this.domStackInitSize);
long loops = sleeptime / 1000;
long rest = sleeptime % 1000;
if (loops < 3) {
@@ -474,19 +474,19 @@ public class Balancer {
Latency.update(crawlEntry.url());
return crawlEntry;
}
-
+
private void filltop(final boolean delay, final long maximumwaiting, final boolean acceptonebest) throws RowSpaceExceededException {
if (!this.top.isEmpty()) return;
-
+
//System.out.println("*** DEBUG started filltop delay=" + ((delay) ? "true":"false") + ", maximumwaiting=" + maximumwaiting + ", acceptonebest=" + ((acceptonebest) ? "true":"false"));
-
+
// check if we need to get entries from the file index
try {
fillDomainStacks();
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
-
+
// iterate over the domain stacks
final Iterator<Map.Entry<String, HandleSet>> i = this.domainStacks.entrySet().iterator();
Map.Entry<String, HandleSet> entry;
@@ -502,10 +502,10 @@ public class Balancer {
continue;
}
- byte[] n = entry.getValue().removeOne();
+ final byte[] n = entry.getValue().removeOne();
if (n == null) continue;
if (delay) {
- final long w = Latency.waitingRemainingGuessed(entry.getKey(), minimumLocalDelta, minimumGlobalDelta);
+ final long w = Latency.waitingRemainingGuessed(entry.getKey(), this.minimumLocalDelta, this.minimumGlobalDelta);
if (w > maximumwaiting) {
if (w < smallestWaiting) {
smallestWaiting = w;
@@ -520,16 +520,16 @@ public class Balancer {
this.top.add(n);
if (entry.getValue().isEmpty()) i.remove();
}
-
+
// if we could not find any entry, then take the best we have seen so far
if (acceptonebest && !this.top.isEmpty() && besturlhash != null) {
removeHashFromDomainStacks(besthost, besturlhash);
this.top.add(besturlhash);
}
}
-
+
private void fillDomainStacks() throws IOException {
- if (!this.domainStacks.isEmpty() && System.currentTimeMillis() - lastDomainStackFill < 120000L) return;
+ if (!this.domainStacks.isEmpty() && System.currentTimeMillis() - this.lastDomainStackFill < 120000L) return;
this.domainStacks.clear();
this.top.clear();
this.lastDomainStackFill = System.currentTimeMillis();
@@ -540,96 +540,96 @@ public class Balancer {
Request request;
while (i.hasNext()) {
handle = i.next();
- Row.Entry entry = this.urlFileIndex.get(handle);
+ final Row.Entry entry = this.urlFileIndex.get(handle);
if (entry == null) continue;
request = new Request(entry);
host = request.url().getHost();
try {
pushHashToDomainStacks(host, handle);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
break;
}
}
- Log.logInfo("BALANCER", "re-fill of domain stacks; fileIndex.size() = " + this.urlFileIndex.size() + ", domainStacks.size = " + domainStacks.size() + ", collection time = " + (System.currentTimeMillis() - this.lastDomainStackFill) + " ms");
+ Log.logInfo("BALANCER", "re-fill of domain stacks; fileIndex.size() = " + this.urlFileIndex.size() + ", domainStacks.size = " + this.domainStacks.size() + ", collection time = " + (System.currentTimeMillis() - this.lastDomainStackFill) + " ms");
this.domStackInitSize = this.domainStacks.size();
}
public List<Request> top(int count) {
final List<Request> cel = new ArrayList<Request>();
if (count == 0) return cel;
- byte[][] ta = new byte[Math.min(count, top.size())][];
- ta = top.toArray(ta);
+ byte[][] ta = new byte[Math.min(count, this.top.size())][];
+ ta = this.top.toArray(ta);
for (final byte[] n: ta) {
if (n == null) break;
try {
- final Row.Entry rowEntry = urlFileIndex.get(n);
+ final Row.Entry rowEntry = this.urlFileIndex.get(n);
if (rowEntry == null) continue;
final Request crawlEntry = new Request(rowEntry);
cel.add(crawlEntry);
count--;
if (count <= 0) break;
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
-
+
int depth = 0;
loop: while (count > 0) {
// iterate over the domain stacks
- int celsize = cel.size();
- ll: for (HandleSet list: this.domainStacks.values()) {
+ final int celsize = cel.size();
+ ll: for (final HandleSet list: this.domainStacks.values()) {
if (list.size() <= depth) continue ll;
- byte[] n = list.getOne(depth);
+ final byte[] n = list.getOne(depth);
if (n == null) continue ll;
try {
- Row.Entry rowEntry = urlFileIndex.get(n);
+ final Row.Entry rowEntry = this.urlFileIndex.get(n);
if (rowEntry == null) continue;
final Request crawlEntry = new Request(rowEntry);
cel.add(crawlEntry);
count--;
if (count <= 0) break loop;
- } catch (IOException e) {}
+ } catch (final IOException e) {}
}
if (cel.size() == celsize) break loop;
depth++;
}
-
+
if (cel.size() < count) try {
- List<Row.Entry> list = urlFileIndex.top(count - cel.size());
+ final List<Row.Entry> list = this.urlFileIndex.top(count - cel.size());
for (final Row.Entry entry: list) cel.add(new Request(entry));
- } catch (IOException e) { }
+ } catch (final IOException e) { }
return cel;
}
-
+
public Iterator<Request> iterator() throws IOException {
return new EntryIterator();
}
-
+
private class EntryIterator implements Iterator<Request> {
private Iterator<Row.Entry> rowIterator;
-
+
public EntryIterator() throws IOException {
- rowIterator = urlFileIndex.rows();
+ this.rowIterator = Balancer.this.urlFileIndex.rows();
}
-
+
public boolean hasNext() {
- return (rowIterator == null) ? false : rowIterator.hasNext();
+ return (this.rowIterator == null) ? false : this.rowIterator.hasNext();
}
public Request next() {
- final Row.Entry entry = rowIterator.next();
+ final Row.Entry entry = this.rowIterator.next();
try {
return (entry == null) ? null : new Request(entry);
} catch (final IOException e) {
Log.logException(e);
- rowIterator = null;
+ this.rowIterator = null;
return null;
}
}
public void remove() {
- if (rowIterator != null) rowIterator.remove();
+ if (this.rowIterator != null) this.rowIterator.remove();
}
-
+
}
-
+
}
diff --git a/source/de/anomic/crawler/CrawlProfile.java b/source/de/anomic/crawler/CrawlProfile.java
index 35a93dc3f..ea1bc6fb0 100644
--- a/source/de/anomic/crawler/CrawlProfile.java
+++ b/source/de/anomic/crawler/CrawlProfile.java
@@ -1,4 +1,4 @@
-// CrawlProfile.java
+// CrawlProfile.java
// ------------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
@@ -27,6 +27,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import net.yacy.cora.document.ASCII;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.word.Word;
import net.yacy.kelondro.logging.Log;
@@ -36,11 +37,11 @@ import net.yacy.kelondro.order.Digest;
public class CrawlProfile extends ConcurrentHashMap<String, String> implements Map<String, String> {
private static final long serialVersionUID = 5527325718810703504L;
-
+
public static final String MATCH_ALL = ".*";
public static final String MATCH_NEVER = "";
-
- // this is a simple record structure that hold all properties of a single crawl start
+
+ // this is a simple record structure that hold all properties of a single crawl start
public static final String HANDLE = "handle";
public static final String NAME = "name";
public static final String START_URL = "startURL";
@@ -59,9 +60,9 @@ public class CrawlProfile extends ConcurrentHashMap<String, String> implements M
public static final String XDSTOPW = "xdstopw";
public static final String XPSTOPW = "xpstopw";
public static final String CACHE_STRAGEGY = "cacheStrategy";
-
+
private Pattern mustmatch = null, mustnotmatch = null;
-
+
public CrawlProfile(
final String name,
final DigestURI startURL,
@@ -100,24 +101,24 @@ public class CrawlProfile extends ConcurrentHashMap<String, String> implements M
put(XPSTOPW, xpstopw); // exclude parent stop-words
put(CACHE_STRAGEGY, cacheStrategy.toString());
}
-
- public CrawlProfile(Map<String, String> ext) {
+
+ public CrawlProfile(final Map<String, String> ext) {
super(ext == null ? 1 : ext.size());
- if (ext != null) this.putAll(ext);
+ if (ext != null) putAll(ext);
}
-
- public void put(String key, boolean value) {
+
+ public void put(final String key, final boolean value) {
super.put(key, Boolean.toString(value));
}
-
- public void put(String key, int value) {
+
+ public void put(final String key, final int value) {
super.put(key, Integer.toString(value));
}
-
- public void put(String key, long value) {
+
+ public void put(final String key, final long value) {
super.put(key, Long.toString(value));
}
-
+
public String handle() {
final String r = get(HANDLE);
//if (r == null) return null;
@@ -168,7 +169,7 @@ public class CrawlProfile extends ConcurrentHashMap<String, String> implements M
return CacheStrategy.IFEXIST;
}
}
- public void setCacheStrategy(CacheStrategy newStrategy) {
+ public void setCacheStrategy(final CacheStrategy newStrategy) {
put(CACHE_STRAGEGY, newStrategy.toString());
}
public long recrawlIfOlder() {
@@ -243,44 +244,6 @@ public class CrawlProfile extends ConcurrentHashMap<String, String> implements M
if (r == null) return false;
return (r.equals(Boolean.TRUE.toString()));
}
-
- public static enum CacheStrategy {
- NOCACHE(0), // never use the cache, all content from fresh internet source
- IFFRESH(1), // use the cache if the cache exists and is fresh using the proxy-fresh rules
- IFEXIST(2), // use the cache if the cache exist. Do no check freshness. Otherwise use online source.
- CACHEONLY(3); // never go online, use all content from cache. If no cache entry exist, consider content nevertheless as available
- // the fifth case may be that the CacheStrategy object is assigned NULL. That means that no snippet creation is wanted.
- public int code;
- private CacheStrategy(int code) {
- this.code = code;
- }
- public String toString() {
- return Integer.toString(this.code);
- }
- public static CacheStrategy decode(int code) {
- for (CacheStrategy strategy: CacheStrategy.values()) if (strategy.code == code) return strategy;
- return NOCACHE;
- }
- public static CacheStrategy parse(String name) {
- if (name == null) return null;
- if (name.equals("nocache")) return NOCACHE;
- if (name.equals("iffresh")) return IFFRESH;
- if (name.equals("ifexist")) return IFEXIST;
- if (name.equals("cacheonly")) return CACHEONLY;
- if (name.equals("true")) return IFEXIST;
- if (name.equals("false")) return null; // if this cache strategy is assigned as query attribute, null means "do not create a snippet"
- return null;
- }
- public String toName() {
- return this.name().toLowerCase();
- }
- public boolean isAllowedToFetchOnline() {
- return this.code < 3;
- }
- public boolean mustBeOffline() {
- return this.code == 3;
- }
- }
public static long getRecrawlDate(final long oldTimeMinutes) {
return System.currentTimeMillis() - (60000L * oldTimeMinutes);
diff --git a/source/de/anomic/crawler/CrawlQueues.java b/source/de/anomic/crawler/CrawlQueues.java
index 49beff401..ddfa2b494 100644
--- a/source/de/anomic/crawler/CrawlQueues.java
+++ b/source/de/anomic/crawler/CrawlQueues.java
@@ -9,7 +9,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -40,12 +40,12 @@ import net.yacy.cora.document.Hit;
import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.UTF8;
import net.yacy.cora.protocol.ConnectionInfo;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.workflow.WorkflowJob;
-
import de.anomic.crawler.NoticedURL.StackType;
import de.anomic.crawler.ZURL.FailCategory;
import de.anomic.crawler.retrieval.HTTPLoader;
@@ -53,8 +53,8 @@ import de.anomic.crawler.retrieval.Request;
import de.anomic.crawler.retrieval.Response;
import de.anomic.search.Segments;
import de.anomic.search.Switchboard;
-import de.anomic.search.SwitchboardConstants;
import de.anomic.search.Switchboard.indexingQueueEntry;
+import de.anomic.search.SwitchboardConstants;
import de.anomic.yacy.yacyClient;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.dht.PeerSelection;
@@ -71,207 +71,207 @@ public class CrawlQueues {
public NoticedURL noticeURL;
public ZURL errorURL, delegatedURL;
-
+
public CrawlQueues(final Switchboard sb, final File queuePath) {
this.sb = sb;
this.log = new Log("CRAWLER");
this.workers = new ConcurrentHashMap<Integer, Loader>();
this.remoteCrawlProviderHashes = new ArrayList<String>();
-
+
// start crawling management
- log.logConfig("Starting Crawling Management");
- noticeURL = new NoticedURL(queuePath, sb.peers.myBotIDs(), sb.useTailCache, sb.exceed134217727);
+ this.log.logConfig("Starting Crawling Management");
+ this.noticeURL = new NoticedURL(queuePath, sb.peers.myBotIDs(), sb.useTailCache, sb.exceed134217727);
FileUtils.deletedelete(new File(queuePath, ERROR_DB_FILENAME));
- errorURL = new ZURL(sb.solrConnector, queuePath, ERROR_DB_FILENAME, false, sb.useTailCache, sb.exceed134217727);
- delegatedURL = new ZURL(sb.solrConnector, queuePath, DELEGATED_DB_FILENAME, true, sb.useTailCache, sb.exceed134217727);
+ this.errorURL = new ZURL(sb.solrConnector, queuePath, ERROR_DB_FILENAME, false, sb.useTailCache, sb.exceed134217727);
+ this.delegatedURL = new ZURL(sb.solrConnector, queuePath, DELEGATED_DB_FILENAME, true, sb.useTailCache, sb.exceed134217727);
}
-
+
public void relocate(final File newQueuePath) {
- this.close();
-
+ close();
+
this.workers = new ConcurrentHashMap<Integer, Loader>();
this.remoteCrawlProviderHashes.clear();
-
- noticeURL = new NoticedURL(newQueuePath, sb.peers.myBotIDs(), sb.useTailCache, sb.exceed134217727);
+
+ this.noticeURL = new NoticedURL(newQueuePath, this.sb.peers.myBotIDs(), this.sb.useTailCache, this.sb.exceed134217727);
FileUtils.deletedelete(new File(newQueuePath, ERROR_DB_FILENAME));
- errorURL = new ZURL(sb.solrConnector, newQueuePath, ERROR_DB_FILENAME, false, sb.useTailCache, sb.exceed134217727);
- delegatedURL = new ZURL(sb.solrConnector, newQueuePath, DELEGATED_DB_FILENAME, true, sb.useTailCache, sb.exceed134217727);
+ this.errorURL = new ZURL(this.sb.solrConnector, newQueuePath, ERROR_DB_FILENAME, false, this.sb.useTailCache, this.sb.exceed134217727);
+ this.delegatedURL = new ZURL(this.sb.solrConnector, newQueuePath, DELEGATED_DB_FILENAME, true, this.sb.useTailCache, this.sb.exceed134217727);
}
-
+
public void close() {
// wait for all workers to finish
- for (final Loader w: workers.values()) {
+ for (final Loader w: this.workers.values()) {
w.interrupt();
}
- for (final Loader w: workers.values()) {
+ for (final Loader w: this.workers.values()) {
try {
w.join();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
Log.logException(e);
}
}
- noticeURL.close();
- errorURL.close();
- delegatedURL.close();
+ this.noticeURL.close();
+ this.errorURL.close();
+ this.delegatedURL.close();
}
-
+
public void clear() {
// wait for all workers to finish
- for (final Loader w: workers.values()) {
+ for (final Loader w: this.workers.values()) {
w.interrupt();
}
// TODO: wait some more time until all threads are finished
- workers.clear();
- remoteCrawlProviderHashes.clear();
- noticeURL.clear();
+ this.workers.clear();
+ this.remoteCrawlProviderHashes.clear();
+ this.noticeURL.clear();
try {
- errorURL.clear();
+ this.errorURL.clear();
} catch (final IOException e) {
Log.logException(e);
}
try {
- delegatedURL.clear();
+ this.delegatedURL.clear();
} catch (final IOException e) {
Log.logException(e);
}
}
-
+
/**
* tests if hash occurs in any database
* @param hash
* @return if the hash exists, the name of the database is returned, otherwise null is returned
*/
public String urlExists(final byte[] hash) {
- if (delegatedURL.exists(hash)) return "delegated";
- if (errorURL.exists(hash)) return "errors";
- if (noticeURL.existsInStack(hash)) return "crawler";
- for (final Loader worker: workers.values()) {
+ if (this.delegatedURL.exists(hash)) return "delegated";
+ if (this.errorURL.exists(hash)) return "errors";
+ if (this.noticeURL.existsInStack(hash)) return "crawler";
+ for (final Loader worker: this.workers.values()) {
if (Base64Order.enhancedCoder.equal(worker.request.url().hash(), hash)) return "worker";
}
return null;
}
-
+
public void urlRemove(final byte[] hash) {
- noticeURL.removeByURLHash(hash);
- delegatedURL.remove(hash);
- errorURL.remove(hash);
+ this.noticeURL.removeByURLHash(hash);
+ this.delegatedURL.remove(hash);
+ this.errorURL.remove(hash);
}
-
+
public DigestURI getURL(final byte[] urlhash) {
assert urlhash != null;
if (urlhash == null || urlhash.length == 0) return null;
- ZURL.Entry ee = delegatedURL.get(urlhash);
+ ZURL.Entry ee = this.delegatedURL.get(urlhash);
if (ee != null) return ee.url();
- ee = errorURL.get(urlhash);
+ ee = this.errorURL.get(urlhash);
if (ee != null) return ee.url();
- for (final Loader w: workers.values()) {
+ for (final Loader w: this.workers.values()) {
if (Base64Order.enhancedCoder.equal(w.request.url().hash(), urlhash)) return w.request.url();
}
- final Request ne = noticeURL.get(urlhash);
+ final Request ne = this.noticeURL.get(urlhash);
if (ne != null) return ne.url();
return null;
}
-
+
public void cleanup() {
// wait for all workers to finish
- int timeout = (int) sb.getConfigLong("crawler.clientTimeout", 10000);
- for (final Loader w: workers.values()) {
+ final int timeout = (int) this.sb.getConfigLong("crawler.clientTimeout", 10000);
+ for (final Loader w: this.workers.values()) {
if (w.age() > timeout) w.interrupt();
}
}
-
+
public Request[] activeWorkerEntries() {
- synchronized (workers) {
- final Request[] e = new Request[workers.size()];
+ synchronized (this.workers) {
+ final Request[] e = new Request[this.workers.size()];
int i = 0;
- for (final Loader w: workers.values()) {
+ for (final Loader w: this.workers.values()) {
if (i >= e.length) break;
e[i++] = w.request;
}
return e;
}
}
-
+
public int coreCrawlJobSize() {
- return noticeURL.stackSize(NoticedURL.StackType.CORE) + noticeURL.stackSize(NoticedURL.StackType.NOLOAD);
+ return this.noticeURL.stackSize(NoticedURL.StackType.CORE) + this.noticeURL.stackSize(NoticedURL.StackType.NOLOAD);
}
-
+
public boolean coreCrawlJob() {
-
- final boolean robinsonPrivateCase = (sb.isRobinsonMode() &&
- !sb.getConfig(SwitchboardConstants.CLUSTER_MODE, "").equals(SwitchboardConstants.CLUSTER_MODE_PUBLIC_CLUSTER) &&
- !sb.getConfig(SwitchboardConstants.CLUSTER_MODE, "").equals(SwitchboardConstants.CLUSTER_MODE_PRIVATE_CLUSTER));
-
+
+ final boolean robinsonPrivateCase = (this.sb.isRobinsonMode() &&
+ !this.sb.getConfig(SwitchboardConstants.CLUSTER_MODE, "").equals(SwitchboardConstants.CLUSTER_MODE_PUBLIC_CLUSTER) &&
+ !this.sb.getConfig(SwitchboardConstants.CLUSTER_MODE, "").equals(SwitchboardConstants.CLUSTER_MODE_PRIVATE_CLUSTER));
+
if ((robinsonPrivateCase || coreCrawlJobSize() <= 20) && limitCrawlJobSize() > 0) {
// move some tasks to the core crawl job so we have something to do
final int toshift = Math.min(10, limitCrawlJobSize()); // this cannot be a big number because the balancer makes a forced waiting if it cannot balance
for (int i = 0; i < toshift; i++) {
- noticeURL.shift(NoticedURL.StackType.LIMIT, NoticedURL.StackType.CORE, sb.crawler);
+ this.noticeURL.shift(NoticedURL.StackType.LIMIT, NoticedURL.StackType.CORE, this.sb.crawler);
}
- log.logInfo("shifted " + toshift + " jobs from global crawl to local crawl (coreCrawlJobSize()=" + coreCrawlJobSize() +
- ", limitCrawlJobSize()=" + limitCrawlJobSize() + ", cluster.mode=" + sb.getConfig(SwitchboardConstants.CLUSTER_MODE, "") +
- ", robinsonMode=" + ((sb.isRobinsonMode()) ? "on" : "off"));
+ this.log.logInfo("shifted " + toshift + " jobs from global crawl to local crawl (coreCrawlJobSize()=" + coreCrawlJobSize() +
+ ", limitCrawlJobSize()=" + limitCrawlJobSize() + ", cluster.mode=" + this.sb.getConfig(SwitchboardConstants.CLUSTER_MODE, "") +
+ ", robinsonMode=" + ((this.sb.isRobinsonMode()) ? "on" : "off"));
}
- String queueCheckCore = loadIsPossible(NoticedURL.StackType.CORE);
- String queueCheckNoload = loadIsPossible(NoticedURL.StackType.NOLOAD);
+ final String queueCheckCore = loadIsPossible(NoticedURL.StackType.CORE);
+ final String queueCheckNoload = loadIsPossible(NoticedURL.StackType.NOLOAD);
if (queueCheckCore != null && queueCheckNoload != null) {
- if (log.isFine()) log.logFine("omitting de-queue/local: " + queueCheckCore + ":" + queueCheckNoload);
+ if (this.log.isFine()) this.log.logFine("omitting de-queue/local: " + queueCheckCore + ":" + queueCheckNoload);
return false;
}
-
+
if (isPaused(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL)) {
- if (log.isFine()) log.logFine("omitting de-queue/local: paused");
+ if (this.log.isFine()) this.log.logFine("omitting de-queue/local: paused");
return false;
}
-
- // do a local crawl
+
+ // do a local crawl
Request urlEntry;
- while (noticeURL.stackSize(NoticedURL.StackType.CORE) > 0 || noticeURL.stackSize(NoticedURL.StackType.NOLOAD) > 0) {
+ while (this.noticeURL.stackSize(NoticedURL.StackType.CORE) > 0 || this.noticeURL.stackSize(NoticedURL.StackType.NOLOAD) > 0) {
final String stats = "LOCALCRAWL[" +
- noticeURL.stackSize(NoticedURL.StackType.NOLOAD) + ", " +
- noticeURL.stackSize(NoticedURL.StackType.CORE) + ", " +
- noticeURL.stackSize(NoticedURL.StackType.LIMIT) + ", " +
- noticeURL.stackSize(NoticedURL.StackType.OVERHANG) +
- ", " + noticeURL.stackSize(NoticedURL.StackType.REMOTE) + "]";
+ this.noticeURL.stackSize(NoticedURL.StackType.NOLOAD) + ", " +
+ this.noticeURL.stackSize(NoticedURL.StackType.CORE) + ", " +
+ this.noticeURL.stackSize(NoticedURL.StackType.LIMIT) + ", " +
+ this.noticeURL.stackSize(NoticedURL.StackType.OVERHANG) +
+ ", " + this.noticeURL.stackSize(NoticedURL.StackType.REMOTE) + "]";
try {
- if (noticeURL.stackSize(NoticedURL.StackType.NOLOAD) > 0) {
+ if (this.noticeURL.stackSize(NoticedURL.StackType.NOLOAD) > 0) {
// get one entry that will not be loaded, just indexed
- urlEntry = noticeURL.pop(NoticedURL.StackType.NOLOAD, true, sb.crawler);
+ urlEntry = this.noticeURL.pop(NoticedURL.StackType.NOLOAD, true, this.sb.crawler);
if (urlEntry == null) continue;
final String profileHandle = urlEntry.profileHandle();
if (profileHandle == null) {
- log.logSevere(stats + ": NULL PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
+ this.log.logSevere(stats + ": NULL PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
return true;
}
- CrawlProfile profile = sb.crawler.getActive(ASCII.getBytes(profileHandle));
+ final CrawlProfile profile = this.sb.crawler.getActive(ASCII.getBytes(profileHandle));
if (profile == null) {
- log.logSevere(stats + ": NULL PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
+ this.log.logSevere(stats + ": NULL PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
return true;
}
try {
- sb.indexingDocumentProcessor.enQueue(new indexingQueueEntry(Segments.Process.LOCALCRAWLING, new Response(urlEntry, profile), null, null));
+ this.sb.indexingDocumentProcessor.enQueue(new indexingQueueEntry(Segments.Process.LOCALCRAWLING, new Response(urlEntry, profile), null, null));
Log.logInfo("CrawlQueues", "placed NOLOAD URL on indexing queue: " + urlEntry.url().toNormalform(true, false));
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
Log.logException(e);
}
return true;
}
-
- urlEntry = noticeURL.pop(NoticedURL.StackType.CORE, true, sb.crawler);
+
+ urlEntry = this.noticeURL.pop(NoticedURL.StackType.CORE, true, this.sb.crawler);
if (urlEntry == null) continue;
final String profileHandle = urlEntry.profileHandle();
// System.out.println("DEBUG plasmaSwitchboard.processCrawling:
// profileHandle = " + profileHandle + ", urlEntry.url = " + urlEntry.url());
if (profileHandle == null) {
- log.logSevere(stats + ": NULL PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
+ this.log.logSevere(stats + ": NULL PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
return true;
}
load(urlEntry, stats, profileHandle);
return true;
} catch (final IOException e) {
- log.logSevere(stats + ": CANNOT FETCH ENTRY: " + e.getMessage(), e);
- if (e.getMessage().indexOf("hash is null") > 0) noticeURL.clear(NoticedURL.StackType.CORE);
+ this.log.logSevere(stats + ": CANNOT FETCH ENTRY: " + e.getMessage(), e);
+ if (e.getMessage().indexOf("hash is null") > 0) this.noticeURL.clear(NoticedURL.StackType.CORE);
}
}
return true;
@@ -279,42 +279,42 @@ public class CrawlQueues {
/**
* Make some checks if crawl is valid and start it
- *
+ *
* @param urlEntry
* @param profileHandle
* @param stats String for log prefixing
* @return
*/
- private void load(Request urlEntry, final String stats, final String profileHandle) {
- final CrawlProfile profile = sb.crawler.getActive(UTF8.getBytes(profileHandle));
+ private void load(final Request urlEntry, final String stats, final String profileHandle) {
+ final CrawlProfile profile = this.sb.crawler.getActive(UTF8.getBytes(profileHandle));
if (profile != null) {
// check if the protocol is supported
final DigestURI url = urlEntry.url();
final String urlProtocol = url.getProtocol();
- if (sb.loader.isSupportedProtocol(urlProtocol)) {
+ if (this.sb.loader.isSupportedProtocol(urlProtocol)) {
if (this.log.isFine())
- log.logFine(stats + ": URL=" + urlEntry.url()
+ this.log.logFine(stats + ": URL=" + urlEntry.url()
+ ", initiator=" + ((urlEntry.initiator() == null) ? "" : ASCII.String(urlEntry.initiator()))
+ ", crawlOrder=" + ((profile.remoteIndexing()) ? "true" : "false")
+ ", depth=" + urlEntry.depth()
+ ", crawlDepth=" + profile.depth()
+ ", must-match=" + profile.mustMatchPattern().toString()
+ ", must-not-match=" + profile.mustNotMatchPattern().toString()
- + ", permission=" + ((sb.peers == null) ? "undefined" : (((sb.peers.mySeed().isSenior()) || (sb.peers.mySeed().isPrincipal())) ? "true" : "false")));
+ + ", permission=" + ((this.sb.peers == null) ? "undefined" : (((this.sb.peers.mySeed().isSenior()) || (this.sb.peers.mySeed().isPrincipal())) ? "true" : "false")));
// work off one Crawl stack entry
if (urlEntry == null || urlEntry.url() == null) {
- log.logInfo(stats + ": urlEntry = null");
+ this.log.logInfo(stats + ": urlEntry = null");
} else {
new Loader(urlEntry);
}
-
+
} else {
this.log.logSevere("Unsupported protocol in URL '" + url.toString());
}
} else {
- log.logWarning(stats + ": LOST PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
+ this.log.logWarning(stats + ": LOST PROFILE HANDLE '" + urlEntry.profileHandle() + "' for URL " + urlEntry.url());
}
}
@@ -324,8 +324,8 @@ public class CrawlQueues {
* @param crawljob
* @return
*/
- private boolean isPaused(String crawljob) {
- final Object[] status = sb.crawlJobsStatus.get(crawljob);
+ private boolean isPaused(final String crawljob) {
+ final Object[] status = this.sb.crawlJobsStatus.get(crawljob);
boolean pauseEnded = false;
synchronized(status[SwitchboardConstants.CRAWLJOB_SYNC]) {
if (((Boolean)status[SwitchboardConstants.CRAWLJOB_STATUS]).booleanValue()) {
@@ -343,25 +343,25 @@ public class CrawlQueues {
* @param stackType
* @return
*/
- private String loadIsPossible(StackType stackType) {
+ private String loadIsPossible(final StackType stackType) {
//System.out.println("stacksize = " + noticeURL.stackSize(stackType));
- if (noticeURL.stackSize(stackType) == 0) {
+ if (this.noticeURL.stackSize(stackType) == 0) {
//log.logDebug("GlobalCrawl: queue is empty");
return "stack is empty";
}
-
+
// check the worker threads
- int maxWorkers = (int) sb.getConfigLong(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, 10);
+ final int maxWorkers = (int) this.sb.getConfigLong(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, 10);
if (this.workers.size() >= maxWorkers) {
// too many worker threads, try a cleanup
- this.cleanup();
+ cleanup();
}
// check again
if (this.workers.size() >= maxWorkers) {
return "too many workers active: " + this.workers.size();
}
- String cautionCause = sb.onlineCaution();
+ final String cautionCause = this.sb.onlineCaution();
if (cautionCause != null) {
return "online caution: " + cautionCause;
}
@@ -370,88 +370,88 @@ public class CrawlQueues {
public boolean remoteCrawlLoaderJob() {
// check if we are allowed to crawl urls provided by other peers
- if (!sb.peers.mySeed().getFlagAcceptRemoteCrawl()) {
+ if (!this.sb.peers.mySeed().getFlagAcceptRemoteCrawl()) {
//this.log.logInfo("remoteCrawlLoaderJob: not done, we are not allowed to do that");
return false;
}
-
+
// check if we are a senior peer
- if (!sb.peers.mySeed().isActive()) {
+ if (!this.sb.peers.mySeed().isActive()) {
//this.log.logInfo("remoteCrawlLoaderJob: not done, this should be a senior or principal peer");
return false;
}
-
- if (this.workers.size() >= sb.getConfigLong(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, 20)) {
+
+ if (this.workers.size() >= this.sb.getConfigLong(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, 20)) {
// try a cleanup
cleanup();
}
// check again
- if (this.workers.size() >= sb.getConfigLong(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, 20)) {
- if (this.log.isFine()) log.logFine("remoteCrawlLoaderJob: too many processes in loader queue, dismissed (" + "cacheLoader=" + this.workers.size() + "), httpClients = " + ConnectionInfo.getCount());
+ if (this.workers.size() >= this.sb.getConfigLong(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, 20)) {
+ if (this.log.isFine()) this.log.logFine("remoteCrawlLoaderJob: too many processes in loader queue, dismissed (" + "cacheLoader=" + this.workers.size() + "), httpClients = " + ConnectionInfo.getCount());
return false;
}
-
- String cautionCause = sb.onlineCaution();
+
+ final String cautionCause = this.sb.onlineCaution();
if (cautionCause != null) {
- if (this.log.isFine()) log.logFine("remoteCrawlLoaderJob: online caution for " + cautionCause + ", omitting processing");
+ if (this.log.isFine()) this.log.logFine("remoteCrawlLoaderJob: online caution for " + cautionCause + ", omitting processing");
return false;
}
-
+
if (remoteTriggeredCrawlJobSize() > 200) {
- if (this.log.isFine()) log.logFine("remoteCrawlLoaderJob: the remote-triggered crawl job queue is filled, omitting processing");
+ if (this.log.isFine()) this.log.logFine("remoteCrawlLoaderJob: the remote-triggered crawl job queue is filled, omitting processing");
return false;
}
-
+
if (coreCrawlJobSize() > 0 /*&& sb.indexingStorageProcessor.queueSize() > 0*/) {
- if (this.log.isFine()) log.logFine("remoteCrawlLoaderJob: a local crawl is running, omitting processing");
+ if (this.log.isFine()) this.log.logFine("remoteCrawlLoaderJob: a local crawl is running, omitting processing");
return false;
}
-
+
// check if we have an entry in the provider list, otherwise fill the list
yacySeed seed;
- if (remoteCrawlProviderHashes.isEmpty()) {
- if (sb.peers != null && sb.peers.sizeConnected() > 0) {
- final Iterator<yacySeed> e = PeerSelection.getProvidesRemoteCrawlURLs(sb.peers);
+ if (this.remoteCrawlProviderHashes.isEmpty()) {
+ if (this.sb.peers != null && this.sb.peers.sizeConnected() > 0) {
+ final Iterator<yacySeed> e = PeerSelection.getProvidesRemoteCrawlURLs(this.sb.peers);
while (e.hasNext()) {
seed = e.next();
- if (seed != null) remoteCrawlProviderHashes.add(seed.hash);
+ if (seed != null) this.remoteCrawlProviderHashes.add(seed.hash);
}
}
}
- if (remoteCrawlProviderHashes.isEmpty()) return false;
-
+ if (this.remoteCrawlProviderHashes.isEmpty()) return false;
+
// take one entry from the provider list and load the entries from the remote peer
seed = null;
String hash = null;
- while (seed == null && !remoteCrawlProviderHashes.isEmpty()) {
- hash = remoteCrawlProviderHashes.remove(remoteCrawlProviderHashes.size() - 1);
+ while (seed == null && !this.remoteCrawlProviderHashes.isEmpty()) {
+ hash = this.remoteCrawlProviderHashes.remove(this.remoteCrawlProviderHashes.size() - 1);
if (hash == null) continue;
- seed = sb.peers.get(hash);
+ seed = this.sb.peers.get(hash);
if (seed == null) continue;
// check if the peer is inside our cluster
- if ((sb.isRobinsonMode()) && (!sb.isInMyCluster(seed))) {
+ if ((this.sb.isRobinsonMode()) && (!this.sb.isInMyCluster(seed))) {
seed = null;
continue;
}
}
if (seed == null) return false;
-
+
// we know a peer which should provide remote crawl entries. load them now.
- final RSSFeed feed = yacyClient.queryRemoteCrawlURLs(sb.peers, seed, 60, 8000);
+ final RSSFeed feed = yacyClient.queryRemoteCrawlURLs(this.sb.peers, seed, 60, 8000);
if (feed == null || feed.isEmpty()) {
// something is wrong with this provider. To prevent that we get not stuck with this peer
// we remove it from the peer list
- sb.peers.peerActions.peerDeparture(seed, "no results from provided remote crawls");
+ this.sb.peers.peerActions.peerDeparture(seed, "no results from provided remote crawls");
// try again and ask another peer
return remoteCrawlLoaderJob();
}
-
+
// parse the rss
DigestURI url, referrer;
Date loaddate;
for (final Hit item: feed) {
//System.out.println("URL=" + item.getLink() + ", desc=" + item.getDescription() + ", pubDate=" + item.getPubDate());
-
+
// put url on remote crawl stack
try {
url = new DigestURI(item.getLink());
@@ -464,24 +464,24 @@ public class CrawlQueues {
referrer = null;
}
loaddate = item.getPubDate();
- final String urlRejectReason = sb.crawlStacker.urlInAcceptedDomain(url);
+ final String urlRejectReason = this.sb.crawlStacker.urlInAcceptedDomain(url);
if (urlRejectReason == null) {
// stack url
- if (sb.getLog().isFinest()) sb.getLog().logFinest("crawlOrder: stack: url='" + url + "'");
- sb.crawlStacker.enqueueEntry(new Request(
+ if (this.sb.getLog().isFinest()) this.sb.getLog().logFinest("crawlOrder: stack: url='" + url + "'");
+ this.sb.crawlStacker.enqueueEntry(new Request(
ASCII.getBytes(hash),
url,
(referrer == null) ? null : referrer.hash(),
item.getDescription(),
loaddate,
- sb.crawler.defaultRemoteProfile.handle(),
+ this.sb.crawler.defaultRemoteProfile.handle(),
0,
0,
0,
item.getSize()
));
} else {
- log.logWarning("crawlOrder: Rejected URL '" + urlToString(url) + "': " + urlRejectReason);
+ this.log.logWarning("crawlOrder: Rejected URL '" + urlToString(url) + "': " + urlRejectReason);
}
}
return true;
@@ -494,36 +494,36 @@ public class CrawlQueues {
private String urlToString(final DigestURI url) {
return (url == null ? "null" : url.toNormalform(true, false));
}
-
+
public int limitCrawlJobSize() {
- return noticeURL.stackSize(NoticedURL.StackType.LIMIT);
+ return this.noticeURL.stackSize(NoticedURL.StackType.LIMIT);
}
-
+
public int remoteTriggeredCrawlJobSize() {
- return noticeURL.stackSize(NoticedURL.StackType.REMOTE);
+ return this.noticeURL.stackSize(NoticedURL.StackType.REMOTE);
}
-
+
public boolean remoteTriggeredCrawlJob() {
// work off crawl requests that had been placed by other peers to our crawl stack
-
+
// do nothing if either there are private processes to be done
// or there is no global crawl on the stack
- String queueCheck = loadIsPossible(NoticedURL.StackType.REMOTE);
+ final String queueCheck = loadIsPossible(NoticedURL.StackType.REMOTE);
if (queueCheck != null) {
- if (log.isFinest()) log.logFinest("omitting de-queue/remote: " + queueCheck);
+ if (this.log.isFinest()) this.log.logFinest("omitting de-queue/remote: " + queueCheck);
return false;
}
if (isPaused(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL)) {
- if (log.isFinest()) log.logFinest("omitting de-queue/remote: paused");
+ if (this.log.isFinest()) this.log.logFinest("omitting de-queue/remote: paused");
return false;
}
-
+
// we don't want to crawl a global URL globally, since WE are the global part. (from this point of view)
- final String stats = "REMOTETRIGGEREDCRAWL[" + noticeURL.stackSize(NoticedURL.StackType.CORE) + ", " + noticeURL.stackSize(NoticedURL.StackType.LIMIT) + ", " + noticeURL.stackSize(NoticedURL.StackType.OVERHANG) + ", "
- + noticeURL.stackSize(NoticedURL.StackType.REMOTE) + "]";
+ final String stats = "REMOTETRIGGEREDCRAWL[" + this.noticeURL.stackSize(NoticedURL.StackType.CORE) + ", " + this.noticeURL.stackSize(NoticedURL.StackType.LIMIT) + ", " + this.noticeURL.stackSize(NoticedURL.StackType.OVERHANG) + ", "
+ + this.noticeURL.stackSize(NoticedURL.StackType.REMOTE) + "]";
try {
- final Request urlEntry = noticeURL.pop(NoticedURL.StackType.REMOTE, true, sb.crawler);
+ final Request urlEntry = this.noticeURL.pop(NoticedURL.StackType.REMOTE, true, this.sb.crawler);
final String profileHandle = urlEntry.profileHandle();
// System.out.println("DEBUG plasmaSwitchboard.processCrawling:
// profileHandle = " + profileHandle + ", urlEntry.url = " +
@@ -531,56 +531,56 @@ public class CrawlQueues {
load(urlEntry, stats, profileHandle);
return true;
} catch (final IOException e) {
- log.logSevere(stats + ": CANNOT FETCH ENTRY: " + e.getMessage(), e);
- if (e.getMessage().indexOf("hash is null") > 0) noticeURL.clear(NoticedURL.StackType.REMOTE);
+ this.log.logSevere(stats + ": CANNOT FETCH ENTRY: " + e.getMessage(), e);
+ if (e.getMessage().indexOf("hash is null") > 0) this.noticeURL.clear(NoticedURL.StackType.REMOTE);
return true;
}
}
-
+
public int workerSize() {
- return workers.size();
+ return this.workers.size();
}
-
+
protected final class Loader extends Thread {
-
+
protected Request request;
private final Integer code;
private final long start;
-
+
public Loader(final Request entry) {
this.start = System.currentTimeMillis();
this.request = entry;
this.request.setStatus("worker-initialized", WorkflowJob.STATUS_INITIATED);
this.code = Integer.valueOf(entry.hashCode());
- if (!workers.containsKey(code)) {
- workers.put(code, this);
+ if (!CrawlQueues.this.workers.containsKey(this.code)) {
+ CrawlQueues.this.workers.put(this.code, this);
try {
- this.start();
- } catch (OutOfMemoryError e) {
+ start();
+ } catch (final OutOfMemoryError e) {
Log.logWarning("CrawlQueues", "crawlWorker sequential fail-over: " + e.getMessage());
- this.run();
+ run();
}
}
- this.setPriority(Thread.MIN_PRIORITY); // http requests from the crawler should not cause that other functions work worse
+ setPriority(Thread.MIN_PRIORITY); // http requests from the crawler should not cause that other functions work worse
}
-
+
public long age() {
- return System.currentTimeMillis() - start;
+ return System.currentTimeMillis() - this.start;
}
-
+
@Override
public void run() {
try {
// checking robots.txt for http(s) resources
this.request.setStatus("worker-checkingrobots", WorkflowJob.STATUS_STARTED);
RobotsTxtEntry robotsEntry;
- if ((request.url().getProtocol().equals("http") || request.url().getProtocol().equals("https")) &&
- (robotsEntry = sb.robots.getEntry(request.url(), sb.peers.myBotIDs())) != null &&
- robotsEntry.isDisallowed(request.url())) {
+ if ((this.request.url().getProtocol().equals("http") || this.request.url().getProtocol().equals("https")) &&
+ (robotsEntry = CrawlQueues.this.sb.robots.getEntry(this.request.url(), CrawlQueues.this.sb.peers.myBotIDs())) != null &&
+ robotsEntry.isDisallowed(this.request.url())) {
//if (log.isFine()) log.logFine("Crawling of URL '" + request.url().toString() + "' disallowed by robots.txt.");
- errorURL.push(
+ CrawlQueues.this.errorURL.push(
this.request,
- ASCII.getBytes(sb.peers.mySeed().hash),
+ ASCII.getBytes(CrawlQueues.this.sb.peers.mySeed().hash),
new Date(),
1,
FailCategory.FINAL_ROBOTS_RULE,
@@ -590,34 +590,34 @@ public class CrawlQueues {
// starting a load from the internet
this.request.setStatus("worker-loading", WorkflowJob.STATUS_RUNNING);
String result = null;
-
+
// load a resource and push queue entry to switchboard queue
// returns null if everything went fine, a fail reason string if a problem occurred
try {
- request.setStatus("loading", WorkflowJob.STATUS_RUNNING);
- final long maxFileSize = sb.getConfigLong("crawler.http.maxFileSize", HTTPLoader.DEFAULT_MAXFILESIZE);
- final CrawlProfile e = sb.crawler.getActive(UTF8.getBytes(request.profileHandle()));
- Response response = sb.loader.load(request, e == null ? CrawlProfile.CacheStrategy.IFEXIST : e.cacheStrategy(), maxFileSize, true);
+ this.request.setStatus("loading", WorkflowJob.STATUS_RUNNING);
+ final long maxFileSize = CrawlQueues.this.sb.getConfigLong("crawler.http.maxFileSize", HTTPLoader.DEFAULT_MAXFILESIZE);
+ final CrawlProfile e = CrawlQueues.this.sb.crawler.getActive(UTF8.getBytes(this.request.profileHandle()));
+ final Response response = CrawlQueues.this.sb.loader.load(this.request, e == null ? CacheStrategy.IFEXIST : e.cacheStrategy(), maxFileSize, true);
if (response == null) {
- request.setStatus("error", WorkflowJob.STATUS_FINISHED);
- if (log.isFine()) log.logFine("problem loading " + request.url().toString() + ": no content (possibly caused by cache policy)");
+ this.request.setStatus("error", WorkflowJob.STATUS_FINISHED);
+ if (CrawlQueues.this.log.isFine()) CrawlQueues.this.log.logFine("problem loading " + this.request.url().toString() + ": no content (possibly caused by cache policy)");
result = "no content (possibly caused by cache policy)";
} else {
- request.setStatus("loaded", WorkflowJob.STATUS_RUNNING);
- final String storedFailMessage = sb.toIndexer(response);
- request.setStatus("enqueued-" + ((storedFailMessage == null) ? "ok" : "fail"), WorkflowJob.STATUS_FINISHED);
+ this.request.setStatus("loaded", WorkflowJob.STATUS_RUNNING);
+ final String storedFailMessage = CrawlQueues.this.sb.toIndexer(response);
+ this.request.setStatus("enqueued-" + ((storedFailMessage == null) ? "ok" : "fail"), WorkflowJob.STATUS_FINISHED);
result = (storedFailMessage == null) ? null : "not enqueued to indexer: " + storedFailMessage;
}
- } catch (IOException e) {
- request.setStatus("error", WorkflowJob.STATUS_FINISHED);
- if (log.isFine()) log.logFine("problem loading " + request.url().toString() + ": " + e.getMessage());
+ } catch (final IOException e) {
+ this.request.setStatus("error", WorkflowJob.STATUS_FINISHED);
+ if (CrawlQueues.this.log.isFine()) CrawlQueues.this.log.logFine("problem loading " + this.request.url().toString() + ": " + e.getMessage());
result = "load error - " + e.getMessage();
}
-
+
if (result != null) {
- errorURL.push(
+ CrawlQueues.this.errorURL.push(
this.request,
- ASCII.getBytes(sb.peers.mySeed().hash),
+ ASCII.getBytes(CrawlQueues.this.sb.peers.mySeed().hash),
new Date(),
1,
FailCategory.TEMPORARY_NETWORK_FAILURE,
@@ -628,9 +628,9 @@ public class CrawlQueues {
}
}
} catch (final Exception e) {
- errorURL.push(
+ CrawlQueues.this.errorURL.push(
this.request,
- ASCII.getBytes(sb.peers.mySeed().hash),
+ ASCII.getBytes(CrawlQueues.this.sb.peers.mySeed().hash),
new Date(),
1,
FailCategory.TEMPORARY_NETWORK_FAILURE,
@@ -639,11 +639,11 @@ public class CrawlQueues {
// Client.initConnectionManager();
this.request.setStatus("worker-exception", WorkflowJob.STATUS_FINISHED);
} finally {
- Loader w = workers.remove(code);
+ final Loader w = CrawlQueues.this.workers.remove(this.code);
assert w != null;
}
}
-
+
}
-
+
}
diff --git a/source/de/anomic/crawler/CrawlSwitchboard.java b/source/de/anomic/crawler/CrawlSwitchboard.java
index 1238f2ba7..11be8b7c4 100644
--- a/source/de/anomic/crawler/CrawlSwitchboard.java
+++ b/source/de/anomic/crawler/CrawlSwitchboard.java
@@ -32,6 +32,7 @@ import java.util.Map;
import java.util.Set;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.blob.MapHeap;
import net.yacy.kelondro.data.word.Word;
import net.yacy.kelondro.logging.Log;
@@ -48,17 +49,17 @@ public final class CrawlSwitchboard {
public static final String CRAWL_PROFILE_SNIPPET_LOCAL_MEDIA = "snippetLocalMedia";
public static final String CRAWL_PROFILE_SNIPPET_GLOBAL_MEDIA = "snippetGlobalMedia";
public static final String CRAWL_PROFILE_SURROGATE = "surrogates";
-
+
public static final String DBFILE_ACTIVE_CRAWL_PROFILES = "crawlProfilesActive.heap";
public static final String DBFILE_PASSIVE_CRAWL_PROFILES = "crawlProfilesPassive.heap";
-
+
public static final long CRAWL_PROFILE_PROXY_RECRAWL_CYCLE = 60L * 24L;
public static final long CRAWL_PROFILE_SNIPPET_LOCAL_TEXT_RECRAWL_CYCLE = 60L * 24L * 30L;
public static final long CRAWL_PROFILE_SNIPPET_GLOBAL_TEXT_RECRAWL_CYCLE = 60L * 24L * 30L;
public static final long CRAWL_PROFILE_SNIPPET_LOCAL_MEDIA_RECRAWL_CYCLE = 60L * 24L * 30L;
public static final long CRAWL_PROFILE_SNIPPET_GLOBAL_MEDIA_RECRAWL_CYCLE = 60L * 24L * 30L;
public static final long CRAWL_PROFILE_SURROGATE_RECRAWL_CYCLE = 60L * 24L * 30L;
-
+
private final Log log;
private Map<byte[], Map<String, String>> profilesActiveCrawls, profilesPassiveCrawls;
public CrawlProfile defaultProxyProfile;
@@ -67,60 +68,60 @@ public final class CrawlSwitchboard {
public CrawlProfile defaultMediaSnippetLocalProfile, defaultMediaSnippetGlobalProfile;
public CrawlProfile defaultSurrogateProfile;
private final File queuesRoot;
-
+
public CrawlSwitchboard(
final String networkName,
final Log log,
final File queuesRoot) {
-
+
log.logInfo("Initializing Word Index for the network '" + networkName + "'.");
-
+
if (networkName == null || networkName.length() == 0) {
log.logSevere("no network name given - shutting down");
System.exit(0);
}
this.log = log;
-
+
// make crawl profiles database and default profiles
this.queuesRoot = queuesRoot;
this.queuesRoot.mkdirs();
this.log.logConfig("Initializing Crawl Profiles");
-
+
final File profilesActiveFile = new File(queuesRoot, DBFILE_ACTIVE_CRAWL_PROFILES);
try {
this.profilesActiveCrawls = new MapHeap(profilesActiveFile, Word.commonHashLength, NaturalOrder.naturalOrder, 1024 * 64, 500, ' ');
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);Log.logException(e);
FileUtils.deletedelete(profilesActiveFile);
try {
this.profilesActiveCrawls = new MapHeap(profilesActiveFile, Word.commonHashLength, NaturalOrder.naturalOrder, 1024 * 64, 500, ' ');
- } catch (IOException e1) {
+ } catch (final IOException e1) {
Log.logException(e1);
this.profilesActiveCrawls = null;
}
}
- for (byte[] handle: this.profilesActiveCrawls.keySet()) {
- CrawlProfile p = new CrawlProfile(this.profilesActiveCrawls.get(handle));
+ for (final byte[] handle: this.profilesActiveCrawls.keySet()) {
+ final CrawlProfile p = new CrawlProfile(this.profilesActiveCrawls.get(handle));
Log.logInfo("CrawlProfiles", "loaded Profile " + p.handle() + ": " + p.name());
}
initActiveCrawlProfiles();
log.logInfo("Loaded active crawl profiles from file " + profilesActiveFile.getName() + ", " + this.profilesActiveCrawls.size() + " entries");
-
+
final File profilesPassiveFile = new File(queuesRoot, DBFILE_PASSIVE_CRAWL_PROFILES);
try {
this.profilesPassiveCrawls = new MapHeap(profilesPassiveFile, Word.commonHashLength, NaturalOrder.naturalOrder, 1024 * 64, 500, ' ');
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);Log.logException(e);
FileUtils.deletedelete(profilesActiveFile);
try {
this.profilesPassiveCrawls = new MapHeap(profilesPassiveFile, Word.commonHashLength, NaturalOrder.naturalOrder, 1024 * 64, 500, ' ');
- } catch (IOException e1) {
+ } catch (final IOException e1) {
Log.logException(e1);
this.profilesPassiveCrawls = null;
}
}
- for (byte[] handle: this.profilesPassiveCrawls.keySet()) {
- CrawlProfile p = new CrawlProfile(this.profilesPassiveCrawls.get(handle));
+ for (final byte[] handle: this.profilesPassiveCrawls.keySet()) {
+ final CrawlProfile p = new CrawlProfile(this.profilesPassiveCrawls.get(handle));
Log.logInfo("CrawlProfiles", "loaded Profile " + p.handle() + ": " + p.name());
}
log.logInfo("Loaded passive crawl profiles from file " + profilesPassiveFile.getName() +
@@ -128,20 +129,20 @@ public final class CrawlSwitchboard {
", " + profilesPassiveFile.length()/1024);
}
- public CrawlProfile getActive(byte[] profileKey) {
+ public CrawlProfile getActive(final byte[] profileKey) {
if (profileKey == null) return null;
- Map<String, String> m = this.profilesActiveCrawls.get(profileKey);
+ final Map<String, String> m = this.profilesActiveCrawls.get(profileKey);
if (m == null) return null;
return new CrawlProfile(m);
}
- public CrawlProfile getPassive(byte[] profileKey) {
+ public CrawlProfile getPassive(final byte[] profileKey) {
if (profileKey == null) return null;
- Map<String, String> m = this.profilesPassiveCrawls.get(profileKey);
+ final Map<String, String> m = this.profilesPassiveCrawls.get(profileKey);
if (m == null) return null;
return new CrawlProfile(m);
}
-
+
public Set<byte[]> getActive() {
return this.profilesActiveCrawls.keySet();
}
@@ -149,28 +150,28 @@ public final class CrawlSwitchboard {
public Set<byte[]> getPassive() {
return this.profilesPassiveCrawls.keySet();
}
-
- public void removeActive(byte[] profileKey) {
+
+ public void removeActive(final byte[] profileKey) {
if (profileKey == null) return;
this.profilesActiveCrawls.remove(profileKey);
}
- public void removePassive(byte[] profileKey) {
+ public void removePassive(final byte[] profileKey) {
if (profileKey == null) return;
this.profilesPassiveCrawls.remove(profileKey);
}
-
- public void putActive(byte[] profileKey, CrawlProfile profile) {
+
+ public void putActive(final byte[] profileKey, final CrawlProfile profile) {
this.profilesActiveCrawls.put(profileKey, profile);
}
-
- public void putPassive(byte[] profileKey, CrawlProfile profile) {
+
+ public void putPassive(final byte[] profileKey, final CrawlProfile profile) {
this.profilesPassiveCrawls.put(profileKey, profile);
}
-
+
public void clear() {
}
-
+
private void initActiveCrawlProfiles() {
this.defaultProxyProfile = null;
this.defaultRemoteProfile = null;
@@ -182,7 +183,7 @@ public final class CrawlSwitchboard {
CrawlProfile profile;
String name;
try {
- for (byte[] handle: this.profilesActiveCrawls.keySet()) {
+ for (final byte[] handle: this.profilesActiveCrawls.keySet()) {
profile = new CrawlProfile(this.profilesActiveCrawls.get(handle));
name = profile.name();
if (name.equals(CRAWL_PROFILE_PROXY)) this.defaultProxyProfile = profile;
@@ -203,7 +204,7 @@ public final class CrawlSwitchboard {
this.defaultMediaSnippetGlobalProfile = null;
this.defaultSurrogateProfile = null;
}
-
+
if (this.defaultProxyProfile == null) {
// generate new default entry for proxy crawling
this.defaultProxyProfile = new CrawlProfile(
@@ -214,70 +215,70 @@ public final class CrawlSwitchboard {
true /*getConfigBool(PROXY_INDEXING_LOCAL_MEDIA, true)*/,
true,
false /*getConfigBool(PROXY_INDEXING_REMOTE, false)*/, true, true, true,
- CrawlProfile.CacheStrategy.IFFRESH);
+ CacheStrategy.IFFRESH);
this.profilesActiveCrawls.put(UTF8.getBytes(this.defaultProxyProfile.handle()), this.defaultProxyProfile);
}
if (this.defaultRemoteProfile == null) {
// generate new default entry for remote crawling
this.defaultRemoteProfile = new CrawlProfile(CRAWL_PROFILE_REMOTE, null, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0,
- -1, -1, true, true, true, false, false, true, true, false, CrawlProfile.CacheStrategy.IFFRESH);
+ -1, -1, true, true, true, false, false, true, true, false, CacheStrategy.IFFRESH);
this.profilesActiveCrawls.put(UTF8.getBytes(this.defaultRemoteProfile.handle()), this.defaultRemoteProfile);
}
if (this.defaultTextSnippetLocalProfile == null) {
// generate new default entry for snippet fetch and optional crawling
this.defaultTextSnippetLocalProfile = new CrawlProfile(CRAWL_PROFILE_SNIPPET_LOCAL_TEXT, null, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0,
- CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_LOCAL_TEXT_RECRAWL_CYCLE), -1, true, false, false, true, false, true, true, false, CrawlProfile.CacheStrategy.IFEXIST);
+ CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_LOCAL_TEXT_RECRAWL_CYCLE), -1, true, false, false, true, false, true, true, false, CacheStrategy.IFEXIST);
this.profilesActiveCrawls.put(UTF8.getBytes(this.defaultTextSnippetLocalProfile.handle()), this.defaultTextSnippetLocalProfile);
}
if (this.defaultTextSnippetGlobalProfile == null) {
// generate new default entry for snippet fetch and optional crawling
this.defaultTextSnippetGlobalProfile = new CrawlProfile(CRAWL_PROFILE_SNIPPET_GLOBAL_TEXT, null, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0,
- CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_GLOBAL_TEXT_RECRAWL_CYCLE), -1, true, true, true, true, false, true, true, false, CrawlProfile.CacheStrategy.IFEXIST);
+ CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_GLOBAL_TEXT_RECRAWL_CYCLE), -1, true, true, true, true, false, true, true, false, CacheStrategy.IFEXIST);
this.profilesActiveCrawls.put(UTF8.getBytes(this.defaultTextSnippetGlobalProfile.handle()), this.defaultTextSnippetGlobalProfile);
}
- this.defaultTextSnippetGlobalProfile.setCacheStrategy(CrawlProfile.CacheStrategy.IFEXIST);
+ this.defaultTextSnippetGlobalProfile.setCacheStrategy(CacheStrategy.IFEXIST);
if (this.defaultMediaSnippetLocalProfile == null) {
// generate new default entry for snippet fetch and optional crawling
this.defaultMediaSnippetLocalProfile = new CrawlProfile(CRAWL_PROFILE_SNIPPET_LOCAL_MEDIA, null, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0,
- CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_LOCAL_MEDIA_RECRAWL_CYCLE), -1, true, false, false, true, false, true, true, false, CrawlProfile.CacheStrategy.IFEXIST);
+ CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_LOCAL_MEDIA_RECRAWL_CYCLE), -1, true, false, false, true, false, true, true, false, CacheStrategy.IFEXIST);
this.profilesActiveCrawls.put(UTF8.getBytes(this.defaultMediaSnippetLocalProfile.handle()), this.defaultMediaSnippetLocalProfile);
}
if (this.defaultMediaSnippetGlobalProfile == null) {
// generate new default entry for snippet fetch and optional crawling
this.defaultMediaSnippetGlobalProfile = new CrawlProfile(CRAWL_PROFILE_SNIPPET_GLOBAL_MEDIA, null, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0,
- CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_GLOBAL_MEDIA_RECRAWL_CYCLE), -1, true, false, true, true, false, true, true, false, CrawlProfile.CacheStrategy.IFEXIST);
+ CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SNIPPET_GLOBAL_MEDIA_RECRAWL_CYCLE), -1, true, false, true, true, false, true, true, false, CacheStrategy.IFEXIST);
this.profilesActiveCrawls.put(UTF8.getBytes(this.defaultMediaSnippetGlobalProfile.handle()), this.defaultMediaSnippetGlobalProfile);
}
if (this.defaultSurrogateProfile == null) {
// generate new default entry for surrogate parsing
this.defaultSurrogateProfile = new CrawlProfile(CRAWL_PROFILE_SURROGATE, null, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0,
- CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SURROGATE_RECRAWL_CYCLE), -1, true, true, false, false, false, true, true, false, CrawlProfile.CacheStrategy.NOCACHE);
+ CrawlProfile.getRecrawlDate(CRAWL_PROFILE_SURROGATE_RECRAWL_CYCLE), -1, true, true, false, false, false, true, true, false, CacheStrategy.NOCACHE);
this.profilesActiveCrawls.put(UTF8.getBytes(this.defaultSurrogateProfile.handle()), this.defaultSurrogateProfile);
}
}
-
+
private void resetProfiles() {
final File pdb = new File(this.queuesRoot, DBFILE_ACTIVE_CRAWL_PROFILES);
if (pdb.exists()) FileUtils.deletedelete(pdb);
try {
this.profilesActiveCrawls = new MapHeap(pdb, Word.commonHashLength, NaturalOrder.naturalOrder, 1024 * 64, 500, ' ');
- } catch (IOException e1) {
+ } catch (final IOException e1) {
Log.logException(e1);
this.profilesActiveCrawls = null;
}
initActiveCrawlProfiles();
}
-
+
public boolean cleanProfiles() throws InterruptedException {
CrawlProfile entry;
boolean hasDoneSomething = false;
try {
- for (byte[] handle: profilesActiveCrawls.keySet()) {
+ for (final byte[] handle: this.profilesActiveCrawls.keySet()) {
// check for interruption
if (Thread.currentThread().isInterrupted()) throw new InterruptedException("Shutdown in progress");
-
+
// getting next profile
- entry = new CrawlProfile(profilesActiveCrawls.get(handle));
+ entry = new CrawlProfile(this.profilesActiveCrawls.get(handle));
if (!((entry.name().equals(CRAWL_PROFILE_PROXY)) ||
(entry.name().equals(CRAWL_PROFILE_REMOTE)) ||
(entry.name().equals(CRAWL_PROFILE_SNIPPET_LOCAL_TEXT)) ||
@@ -285,9 +286,9 @@ public final class CrawlSwitchboard {
(entry.name().equals(CRAWL_PROFILE_SNIPPET_LOCAL_MEDIA)) ||
(entry.name().equals(CRAWL_PROFILE_SNIPPET_GLOBAL_MEDIA)) ||
(entry.name().equals(CRAWL_PROFILE_SURROGATE)))) {
- CrawlProfile p = new CrawlProfile(entry);
- profilesPassiveCrawls.put(UTF8.getBytes(p.handle()), p);
- profilesActiveCrawls.remove(handle);
+ final CrawlProfile p = new CrawlProfile(entry);
+ this.profilesPassiveCrawls.put(UTF8.getBytes(p.handle()), p);
+ this.profilesActiveCrawls.remove(handle);
hasDoneSomething = true;
}
}
@@ -298,7 +299,7 @@ public final class CrawlSwitchboard {
return hasDoneSomething;
}
-
+
public void close() {
((MapHeap) this.profilesActiveCrawls).close();
((MapHeap) this.profilesPassiveCrawls).close();
diff --git a/source/de/anomic/crawler/RSSLoader.java b/source/de/anomic/crawler/RSSLoader.java
index 50d8663ac..8a6b22d4a 100644
--- a/source/de/anomic/crawler/RSSLoader.java
+++ b/source/de/anomic/crawler/RSSLoader.java
@@ -11,12 +11,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -32,6 +32,7 @@ import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.cora.document.RSSReader;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.cora.storage.ARC;
import net.yacy.cora.storage.ComparableARC;
import net.yacy.document.Parser.Failure;
@@ -47,54 +48,54 @@ import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
public class RSSLoader extends Thread {
-
+
public static final ARC<byte[], Date> indexTriggered = new ComparableARC<byte[], Date>(1000, Base64Order.enhancedCoder);
-
+
DigestURI urlf;
Switchboard sb;
-
- public RSSLoader(Switchboard sb, DigestURI urlf) {
+
+ public RSSLoader(final Switchboard sb, final DigestURI urlf) {
this.sb = sb;
this.urlf = urlf;
}
-
+
public void run() {
RSSReader rss = null;
try {
- Response response = sb.loader.load(sb.loader.request(urlf, true, false), CrawlProfile.CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
- byte[] resource = response == null ? null : response.getContent();
+ final Response response = this.sb.loader.load(this.sb.loader.request(this.urlf, true, false), CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
+ final byte[] resource = response == null ? null : response.getContent();
rss = resource == null ? null : RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, resource);
- } catch (MalformedURLException e) {
- Log.logWarning("Load_RSS", "rss loading for url '" + this.getName().substring(9) + "' failed: " + e.getMessage());
+ } catch (final MalformedURLException e) {
+ Log.logWarning("Load_RSS", "rss loading for url '" + getName().substring(9) + "' failed: " + e.getMessage());
return;
- } catch (IOException e) {
- Log.logWarning("Load_RSS", "rss loading for url '" + urlf.toNormalform(true, false) + "' failed: " + e.getMessage());
+ } catch (final IOException e) {
+ Log.logWarning("Load_RSS", "rss loading for url '" + this.urlf.toNormalform(true, false) + "' failed: " + e.getMessage());
return;
}
if (rss == null) {
- Log.logWarning("Load_RSS", "no rss for url " + urlf.toNormalform(true, false));
+ Log.logWarning("Load_RSS", "no rss for url " + this.urlf.toNormalform(true, false));
return;
}
- RSSFeed feed = rss.getFeed();
- indexAllRssFeed(sb, urlf, feed);
-
+ final RSSFeed feed = rss.getFeed();
+ indexAllRssFeed(this.sb, this.urlf, feed);
+
// add the feed also to the scheduler
- recordAPI(sb, null, urlf, feed, 7, "seldays");
+ recordAPI(this.sb, null, this.urlf, feed, 7, "seldays");
}
-
- public static void indexAllRssFeed(Switchboard sb, DigestURI url, RSSFeed feed) {
+
+ public static void indexAllRssFeed(final Switchboard sb, final DigestURI url, final RSSFeed feed) {
int loadCount = 0;
- loop: for (RSSMessage message: feed) {
+ loop: for (final RSSMessage message: feed) {
try {
- DigestURI messageurl = new DigestURI(message.getLink());
+ final DigestURI messageurl = new DigestURI(message.getLink());
if (indexTriggered.containsKey(messageurl.hash())) continue loop;
if (sb.urlExists(Segments.Process.LOCALCRAWLING, messageurl.hash()) != null) continue loop;
sb.addToIndex(messageurl, null, null);
indexTriggered.insertIfAbsent(messageurl.hash(), new Date());
loadCount++;
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
- } catch (Failure e) {
+ } catch (final Failure e) {
Log.logException(e);
}
}
@@ -103,12 +104,12 @@ public class RSSLoader extends Thread {
try {
Tables.Data rssRow = sb.tables.select("rss", url.hash());
if (rssRow == null) rssRow = new Tables.Data();
- Date lastLoadDate = rssRow.get("last_load_date", new Date(0));
- long deltaTime = Math.min(System.currentTimeMillis() - lastLoadDate.getTime(), 1000 * 60 * 60 * 24);
- int allLoadCount = rssRow.get("all_load_count", 0);
- int lastAvg = rssRow.get("avg_upd_per_day", 0);
- long thisAvg = 1000 * 60 * 60 * 24 / deltaTime * loadCount;
- long nextAvg = lastAvg == 0 ? thisAvg : (thisAvg + lastAvg * 2) / 3;
+ final Date lastLoadDate = rssRow.get("last_load_date", new Date(0));
+ final long deltaTime = Math.min(System.currentTimeMillis() - lastLoadDate.getTime(), 1000 * 60 * 60 * 24);
+ final int allLoadCount = rssRow.get("all_load_count", 0);
+ final int lastAvg = rssRow.get("avg_upd_per_day", 0);
+ final long thisAvg = 1000 * 60 * 60 * 24 / deltaTime * loadCount;
+ final long nextAvg = lastAvg == 0 ? thisAvg : (thisAvg + lastAvg * 2) / 3;
rssRow.put("url", UTF8.getBytes(url.toNormalform(true, false)));
rssRow.put("title", feed.getChannel().getTitle());
rssRow.put("last_load_date", new Date());
@@ -116,18 +117,18 @@ public class RSSLoader extends Thread {
rssRow.put("all_load_count", allLoadCount + loadCount);
rssRow.put("avg_upd_per_day", nextAvg);
sb.tables.update("rss", url.hash(), rssRow);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
}
-
-
- public static void recordAPI(Switchboard sb, String apicall_pk, DigestURI url, RSSFeed feed, int repeat_time, String repeat_unit) {
+
+
+ public static void recordAPI(final Switchboard sb, final String apicall_pk, final DigestURI url, final RSSFeed feed, final int repeat_time, final String repeat_unit) {
// record API action
byte[] pk = null;
- serverObjects post = new serverObjects();
+ final serverObjects post = new serverObjects();
post.put("url", url.toNormalform(true, false));
post.put("indexAllItemContent", "");
if (apicall_pk != null) post.put(WorkTables.TABLE_API_COL_APICALL_PK, apicall_pk);
@@ -139,14 +140,14 @@ public class RSSLoader extends Thread {
pk = sb.tables.recordAPICall(post, "Load_RSS_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "import feed " + url.toNormalform(true, false));
}
// store pk of api table into rss table to show that the entry has been recorded
- assert pk != null;
- Tables.Data rssRow = new Tables.Data();
+ assert pk != null;
+ final Tables.Data rssRow = new Tables.Data();
rssRow.put("url", UTF8.getBytes(url.toNormalform(true, false)));
rssRow.put("title", feed.getChannel().getTitle());
rssRow.put("api_pk", pk);
try {
sb.tables.update("rss", url.hash(), rssRow);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
diff --git a/source/de/anomic/data/ymark/YMarkAutoTagger.java b/source/de/anomic/data/ymark/YMarkAutoTagger.java
index 986655899..90cbf4fcf 100644
--- a/source/de/anomic/data/ymark/YMarkAutoTagger.java
+++ b/source/de/anomic/data/ymark/YMarkAutoTagger.java
@@ -11,31 +11,31 @@ import java.util.TreeSet;
import java.util.concurrent.ArrayBlockingQueue;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.LibraryProvider;
-import net.yacy.document.WordTokenizer;
import net.yacy.document.Parser.Failure;
+import net.yacy.document.WordTokenizer;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.word.Word;
import net.yacy.kelondro.index.RowSpaceExceededException;
import net.yacy.kelondro.logging.Log;
import net.yacy.repository.LoaderDispatcher;
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
public class YMarkAutoTagger implements Runnable, Thread.UncaughtExceptionHandler {
public final static String SPACE = " ";
public final static String POISON = "";
-
+
private final ArrayBlockingQueue<String> bmkQueue;
private final YMarkTables ymarks;
private final String bmk_user;
private final LoaderDispatcher loader;
-
- private boolean merge;
-
+
+ private final boolean merge;
+
public YMarkAutoTagger(final ArrayBlockingQueue<String> bmkQueue, final LoaderDispatcher loader, final YMarkTables ymarks, final String bmk_user, final boolean merge) {
this.bmkQueue = bmkQueue;
this.ymarks = ymarks;
@@ -43,7 +43,7 @@ public class YMarkAutoTagger implements Runnable, Thread.UncaughtExceptionHandle
this.loader = loader;
this.merge = merge;
}
-
+
public YMarkAutoTagger(final LoaderDispatcher loader, final YMarkTables ymarks, final String bmk_user) {
this.bmkQueue = new ArrayBlockingQueue<String>(1);
this.ymarks = ymarks;
@@ -51,49 +51,49 @@ public class YMarkAutoTagger implements Runnable, Thread.UncaughtExceptionHandle
this.loader = loader;
this.merge = true;
}
-
+
private Document loadDocument(final String url) {
DigestURI uri;
Response response;
try {
uri = new DigestURI(url);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logWarning(YMarkTables.BOOKMARKS_LOG, "loadDocument failed due to malformed url: "+url);
return null;
}
try {
- response = loader.load(loader.request(uri, true, false), CrawlProfile.CacheStrategy.IFEXIST, Long.MAX_VALUE, true);
- } catch (IOException e) {
+ response = this.loader.load(this.loader.request(uri, true, false), CacheStrategy.IFEXIST, Long.MAX_VALUE, true);
+ } catch (final IOException e) {
Log.logWarning(YMarkTables.BOOKMARKS_LOG, "loadDocument failed due to IOException for url: "+url);
try {
this.ymarks.addFolder(this.bmk_user, url, "/IOExceptions");
- } catch (IOException e1) {
+ } catch (final IOException e1) {
Log.logException(e1);
- } catch (RowSpaceExceededException e1) {
+ } catch (final RowSpaceExceededException e1) {
Log.logException(e1);
}
return null;
- }
+ }
try {
return Document.mergeDocuments(response.url(), response.getMimeType(), response.parse());
- } catch (Failure e) {
+ } catch (final Failure e) {
Log.logWarning(YMarkTables.BOOKMARKS_LOG, "loadDocument failed due to a parser failure for url: "+url);
return null;
}
}
-
+
public String autoTag(final String url, final int max, final TreeMap<String, YMarkTag> tags) {
- final Document document = loadDocument(url);
+ final Document document = loadDocument(url);
final TreeSet<YMarkTag> topwords = new TreeSet<YMarkTag>();
// final TreeMap<String, YMarkTag> pairs = new TreeMap<String, YMarkTag>();
-
+
String token;
// StringBuilder pair = new StringBuilder(64);
-
+
if(document != null) {
//get words from document
final Map<String, Word> words = new Condenser(document, true, true, LibraryProvider.dymLib).words();
-
+
// generate potential tags from document title, description and subject
final int bufferSize = document.dc_title().length() + document.dc_description().length() + document.dc_subject(' ').length() + 32;
final StringBuilder buffer = new StringBuilder(bufferSize);
@@ -101,18 +101,18 @@ public class YMarkAutoTagger implements Runnable, Thread.UncaughtExceptionHandle
buffer.append(document.dc_description());
buffer.append(document.dc_subject(' '));
final Enumeration<String> tokens = new WordTokenizer(new ByteArrayInputStream(UTF8.getBytes(buffer.toString())), LibraryProvider.dymLib);
-
+
int count = 0;
-
+
// loop through potential tag and rank them
while(tokens.hasMoreElements()) {
count = 0;
token = tokens.nextElement();
-
+
/*
pair.delete(0, pair.indexOf(SPACE)+1);
if(pair.length() > 1)
- pair.append(SPACE);
+ pair.append(SPACE);
pair.append(token);
if(pair.indexOf(SPACE) > 1 && pairs.containsKey(pair.toString())) {
@@ -121,24 +121,24 @@ public class YMarkAutoTagger implements Runnable, Thread.UncaughtExceptionHandle
pairs.put(pair.toString(), new YMarkTag(pair.toString()));
}
*/
-
+
// check if the token appears in the text
if (words.containsKey(token)) {
- Word word = words.get(token);
+ final Word word = words.get(token);
// token appears in text and matches an existing bookmark tag
if (tags.containsKey(token)) {
count = word.occurrences() * tags.get(token).size() * 100;
- }
+ }
// token appears in text and has more than 3 characters
if (token.length()>3) {
count = word.occurrences() * 100;
}
topwords.add(new YMarkTag(token, count));
}
- }
+ }
count = 0;
- buffer.setLength(0);
- for(YMarkTag tag : topwords) {
+ buffer.setLength(0);
+ for(final YMarkTag tag : topwords) {
if(count < max) {
if(tag.size() > 100) {
buffer.append(tag.name());
@@ -149,27 +149,27 @@ public class YMarkAutoTagger implements Runnable, Thread.UncaughtExceptionHandle
break;
}
}
- String clean = YMarkUtil.cleanTagsString(buffer.toString());
+ final String clean = YMarkUtil.cleanTagsString(buffer.toString());
return clean;
}
return new String();
}
-
+
public void run() {
- Log.logInfo(YMarkTables.BOOKMARKS_LOG, "autoTagger run()");
+ Log.logInfo(YMarkTables.BOOKMARKS_LOG, "autoTagger run()");
Thread.currentThread().setUncaughtExceptionHandler(this);
String url = null;
String tagString;
Iterator<String> tit;
try {
- final TreeMap<String, YMarkTag> tags = this.ymarks.getTags(bmk_user);
- Log.logInfo(YMarkTables.BOOKMARKS_LOG, "autoTagger queue size: "+bmkQueue.size());
- while((url = bmkQueue.take()) != POISON) {
- tagString = this.autoTag(url, 5, tags);
-
+ final TreeMap<String, YMarkTag> tags = this.ymarks.getTags(this.bmk_user);
+ Log.logInfo(YMarkTables.BOOKMARKS_LOG, "autoTagger queue size: "+this.bmkQueue.size());
+ while((url = this.bmkQueue.take()) != POISON) {
+ tagString = autoTag(url, 5, tags);
+
// update tags
this.ymarks.addTags(this.bmk_user, url, tagString, this.merge);
-
+
// update tags
tit = YMarkUtil.keysStringToSet(tagString).iterator();
while(tit.hasNext()) {
@@ -179,20 +179,20 @@ public class YMarkAutoTagger implements Runnable, Thread.UncaughtExceptionHandle
} else {
tags.put(tag, new YMarkTag(tag));
}
- }
- }
+ }
+ }
Log.logInfo(YMarkTables.BOOKMARKS_LOG, "autoTagger has been poisoned");
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
Log.logException(e);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logWarning(YMarkTables.BOOKMARKS_LOG.toString(), "autoTagger - IOException for URL: "+url);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
} finally {
}
}
- public void uncaughtException(Thread t, Throwable e) {
+ public void uncaughtException(final Thread t, final Throwable e) {
Log.logWarning(YMarkTables.BOOKMARKS_LOG, "I caught an uncaughtException in thread "+t.getName());
Log.logException(e);
}
diff --git a/source/de/anomic/data/ymark/YMarkMetadata.java b/source/de/anomic/data/ymark/YMarkMetadata.java
index fc0e64061..032681deb 100644
--- a/source/de/anomic/data/ymark/YMarkMetadata.java
+++ b/source/de/anomic/data/ymark/YMarkMetadata.java
@@ -9,7 +9,7 @@
// $LastChangedBy: apfelmaennchen $
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -34,6 +34,7 @@ import java.util.TreeMap;
import net.yacy.cora.date.ISO8601Formatter;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.LibraryProvider;
@@ -42,7 +43,6 @@ import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.data.word.Word;
import net.yacy.repository.LoaderDispatcher;
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
import de.anomic.search.Segments;
@@ -50,7 +50,7 @@ public class YMarkMetadata {
private DigestURI uri;
Document document;
Segments indexSegment;
-
+
public enum METADATA {
TITLE,
DESCRIPTION,
@@ -70,37 +70,37 @@ public class YMarkMetadata {
SNIPPET,
AUTOTAG
}
-
+
public YMarkMetadata(final DigestURI uri) {
this.uri = uri;
this.document = null;
this.indexSegment = null;
}
-
+
public YMarkMetadata(final DigestURI uri, final Segments indexSegment) {
this.uri = uri;
this.document = null;
this.indexSegment = indexSegment;
}
-
+
public YMarkMetadata(final Document document) {
this.document = document;
try {
this.uri = new DigestURI(this.document.dc_identifier());
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
this.uri = null;
}
this.indexSegment = null;
- }
-
- public void loadDocument(LoaderDispatcher loader) throws IOException, Failure {
- if(document == null) {
+ }
+
+ public void loadDocument(final LoaderDispatcher loader) throws IOException, Failure {
+ if(this.document == null) {
Response response = null;
- response = loader.load(loader.request(this.uri, true, false), CrawlProfile.CacheStrategy.IFEXIST, Long.MAX_VALUE, true);
- this.document = Document.mergeDocuments(response.url(), response.getMimeType(), response.parse());
+ response = loader.load(loader.request(this.uri, true, false), CacheStrategy.IFEXIST, Long.MAX_VALUE, true);
+ this.document = Document.mergeDocuments(response.url(), response.getMimeType(), response.parse());
}
}
-
+
public EnumMap<METADATA, String> getMetadata() {
final EnumMap<METADATA, String> metadata = new EnumMap<METADATA, String>(METADATA.class);
final URIMetadataRow urlEntry = this.indexSegment.segment(Segments.Process.PUBLIC).urlMetadata().load(this.uri.hash());
@@ -113,22 +113,22 @@ public class YMarkMetadata {
metadata.put(METADATA.WORDCOUNT, String.valueOf(urlEntry.wordCount()));
metadata.put(METADATA.MIMETYPE, String.valueOf(urlEntry.doctype()));
metadata.put(METADATA.LANGUAGE, UTF8.String(urlEntry.language()));
-
+
final URIMetadataRow.Components meta = urlEntry.metadata();
- if (meta != null) {
- metadata.put(METADATA.TITLE, meta.dc_title());
+ if (meta != null) {
+ metadata.put(METADATA.TITLE, meta.dc_title());
metadata.put(METADATA.CREATOR, meta.dc_creator());
metadata.put(METADATA.KEYWORDS, meta.dc_subject());
metadata.put(METADATA.PUBLISHER, meta.dc_publisher());
}
- }
+ }
return metadata;
}
-
+
public EnumMap<METADATA, String> loadMetadata() {
final EnumMap<METADATA, String> metadata = new EnumMap<METADATA, String>(METADATA.class);
if(this.document != null) {
- metadata.put(METADATA.TITLE, this.document.dc_title());
+ metadata.put(METADATA.TITLE, this.document.dc_title());
metadata.put(METADATA.CREATOR, this.document.dc_creator());
metadata.put(METADATA.KEYWORDS, this.document.dc_subject(' '));
metadata.put(METADATA.PUBLISHER, this.document.dc_publisher());
@@ -140,18 +140,18 @@ public class YMarkMetadata {
}
return metadata;
}
-
+
public TreeMap<String,Word> getWordCounts() {
if (this.document != null) {
return sortWordCounts(new Condenser(this.document, true, true, LibraryProvider.dymLib).words());
}
return new TreeMap<String, Word>();
}
-
- public static TreeMap<String,Word> sortWordCounts(final Map<String, Word> unsorted_words) {
+
+ public static TreeMap<String,Word> sortWordCounts(final Map<String, Word> unsorted_words) {
final TreeMap<String, Word> sorted_words = new TreeMap<String, Word>(new YMarkWordCountComparator(unsorted_words));
sorted_words.putAll(unsorted_words);
- return sorted_words;
+ return sorted_words;
}
-
+
}
diff --git a/source/de/anomic/search/MediaSnippet.java b/source/de/anomic/search/MediaSnippet.java
index 4d13a7524..c59ebca87 100644
--- a/source/de/anomic/search/MediaSnippet.java
+++ b/source/de/anomic/search/MediaSnippet.java
@@ -34,11 +34,9 @@ import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
-import de.anomic.crawler.CrawlProfile;
-import de.anomic.data.MimeTable;
-
import net.yacy.cora.document.ASCII;
import net.yacy.cora.document.MultiProtocolURI;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Document;
import net.yacy.document.Parser;
import net.yacy.document.WordTokenizer;
@@ -49,6 +47,7 @@ import net.yacy.kelondro.index.RowSpaceExceededException;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.util.ByteArray;
+import de.anomic.data.MimeTable;
public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaSnippet> {
@@ -78,7 +77,7 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
if ((this.name == null) || (this.name.length() == 0)) this.name = "_";
if ((this.attr == null) || (this.attr.length() == 0)) this.attr = "_";
}
-
+
public MediaSnippet(final ContentDomain type, final DigestURI href, final String mime, final String name, final long fileSize, final int width, final int height, final long ranking, final DigestURI source) {
this.type = type;
this.href = href;
@@ -93,47 +92,47 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
if ((this.name == null) || (this.name.length() == 0)) this.name = "_";
if ((this.attr == null) || (this.attr.length() == 0)) this.attr = "_";
}
-
+
@Override
public int hashCode() {
- return ByteArray.hashCode(href.hash());
+ return ByteArray.hashCode(this.href.hash());
}
-
+
@Override
public String toString() {
- return ASCII.String(href.hash());
+ return ASCII.String(this.href.hash());
}
-
+
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof MediaSnippet)) return false;
- MediaSnippet other = (MediaSnippet) obj;
+ final MediaSnippet other = (MediaSnippet) obj;
return Base64Order.enhancedCoder.equal(this.href.hash(), other.href.hash());
}
-
- public int compareTo(MediaSnippet o) {
+
+ public int compareTo(final MediaSnippet o) {
return Base64Order.enhancedCoder.compare(this.href.hash(), o.href.hash());
}
-
- public int compare(MediaSnippet o1, MediaSnippet o2) {
+
+ public int compare(final MediaSnippet o1, final MediaSnippet o2) {
return o1.compareTo(o2);
}
-
- public static List<MediaSnippet> retrieveMediaSnippets(final DigestURI url, final HandleSet queryhashes, final ContentDomain mediatype, final CrawlProfile.CacheStrategy cacheStrategy, final int timeout, final boolean reindexing) {
+
+ public static List<MediaSnippet> retrieveMediaSnippets(final DigestURI url, final HandleSet queryhashes, final ContentDomain mediatype, final CacheStrategy cacheStrategy, final int timeout, final boolean reindexing) {
if (queryhashes.isEmpty()) {
Log.logFine("snippet fetch", "no query hashes given for url " + url);
return new ArrayList<MediaSnippet>();
}
-
+
Document document;
try {
document = Document.mergeDocuments(url, null, Switchboard.getSwitchboard().loader.loadDocuments(Switchboard.getSwitchboard().loader.request(url, false, reindexing), cacheStrategy, timeout, Long.MAX_VALUE));
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logFine("snippet fetch", "load error: " + e.getMessage());
return new ArrayList<MediaSnippet>();
- } catch (Parser.Failure e) {
+ } catch (final Parser.Failure e) {
Log.logFine("snippet fetch", "parser error: " + e.getMessage());
return new ArrayList<MediaSnippet>();
}
@@ -146,16 +145,16 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
}
return a;
}
-
+
public static List<MediaSnippet> computeMediaSnippets(final DigestURI source, final Document document, final HandleSet queryhashes, final ContentDomain mediatype) {
-
+
if (document == null) return new ArrayList<MediaSnippet>();
Map<MultiProtocolURI, String> media = null;
if (mediatype == ContentDomain.AUDIO) media = document.getAudiolinks();
else if (mediatype == ContentDomain.VIDEO) media = document.getVideolinks();
else if (mediatype == ContentDomain.APP) media = document.getApplinks();
if (media == null) return null;
-
+
final Iterator<Map.Entry<MultiProtocolURI, String>> i = media.entrySet().iterator();
Map.Entry<MultiProtocolURI, String> entry;
DigestURI url;
@@ -165,7 +164,7 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
entry = i.next();
url = new DigestURI(entry.getKey());
desc = entry.getValue();
- int ranking = removeAppearanceHashes(url.toNormalform(false, false), queryhashes).size() +
+ final int ranking = removeAppearanceHashes(url.toNormalform(false, false), queryhashes).size() +
removeAppearanceHashes(desc, queryhashes).size();
if (ranking < 2 * queryhashes.size()) {
result.add(new MediaSnippet(mediatype, url, MimeTable.url2mime(url), desc, document.getTextLength(), null, ranking, source));
@@ -173,13 +172,13 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
}
return result;
}
-
+
public static List<MediaSnippet> computeImageSnippets(final DigestURI source, final Document document, final HandleSet queryhashes) {
-
+
final SortedSet<ImageEntry> images = new TreeSet<ImageEntry>();
images.addAll(document.getImages().values()); // iterates images in descending size order!
// a measurement for the size of the images can be retrieved using the htmlFilterImageEntry.hashCode()
-
+
final Iterator<ImageEntry> i = images.iterator();
ImageEntry ientry;
DigestURI url;
@@ -188,20 +187,20 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
while (i.hasNext()) {
ientry = i.next();
url = new DigestURI(ientry.url());
- String u = url.toString();
+ final String u = url.toString();
if (u.indexOf(".ico") >= 0 || u.indexOf("favicon") >= 0) continue;
if (ientry.height() > 0 && ientry.height() < 32) continue;
if (ientry.width() > 0 && ientry.width() < 32) continue;
desc = ientry.alt();
- int appcount = queryhashes.size() * 2 -
+ final int appcount = queryhashes.size() * 2 -
removeAppearanceHashes(url.toNormalform(false, false), queryhashes).size() -
removeAppearanceHashes(desc, queryhashes).size();
- final long ranking = Long.MAX_VALUE - (ientry.height() + 1) * (ientry.width() + 1) * (appcount + 1);
+ final long ranking = Long.MAX_VALUE - (ientry.height() + 1) * (ientry.width() + 1) * (appcount + 1);
result.add(new MediaSnippet(ContentDomain.IMAGE, url, MimeTable.url2mime(url), desc, ientry.fileSize(), ientry.width(), ientry.height(), ranking, source));
}
return result;
}
-
+
/**
* removed all word hashes that can be computed as tokens from a given sentence from a given hash set
* @param sentence
@@ -222,12 +221,12 @@ public class MediaSnippet implements Comparable<MediaSnippet>, Comparator<MediaS
if (pos == null) {
try {
remaininghashes.put(hash);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
}
}
return remaininghashes;
}
-
+
}
diff --git a/source/de/anomic/search/QueryParams.java b/source/de/anomic/search/QueryParams.java
index c8a354049..e1ef4cd1f 100644
--- a/source/de/anomic/search/QueryParams.java
+++ b/source/de/anomic/search/QueryParams.java
@@ -1,4 +1,4 @@
-// QueryParams.java
+// QueryParams.java
// -----------------------
// part of YACY
// (C) by Michael Peter Christen; [email protected]
@@ -40,6 +40,7 @@ import java.util.regex.PatternSyntaxException;
import net.yacy.cora.document.ASCII;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.document.parser.html.AbstractScraper;
import net.yacy.document.parser.html.CharacterCoding;
@@ -53,12 +54,10 @@ import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.order.Bitfield;
import net.yacy.kelondro.order.NaturalOrder;
import net.yacy.kelondro.util.SetTools;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.yacy.yacySeed;
public final class QueryParams {
-
+
public static final int SEARCHDOM_LOCAL = 0;
public static final int SEARCHDOM_CLUSTERDHT = 1;
public static final int SEARCHDOM_CLUSTERALL = 2;
@@ -66,17 +65,17 @@ public final class QueryParams {
public static final int SEARCHDOM_GLOBALALL = 4;
private static final String ampersand = "&amp;";
-
+
public static enum FetchMode {
NO_FETCH_NO_VERIFY,
FETCH_BUT_ACCEPT_OFFLINE_OR_USE_CACHE,
FETCH_AND_VERIFY_ONLINE;
}
-
+
public static final Bitfield empty_constraint = new Bitfield(4, "AAAAAA");
public static final Pattern catchall_pattern = Pattern.compile(".*");
public static final Pattern matchnothing_pattern = Pattern.compile("");
-
+
public final String queryString;
public HandleSet fullqueryHashes, queryHashes, excludeHashes;
public Pattern snippetMatcher;
@@ -93,13 +92,13 @@ public final class QueryParams {
public final int maxDistance;
public final Bitfield constraint;
public final boolean allofconstraint;
- public final CrawlProfile.CacheStrategy snippetCacheStrategy;
+ public final CacheStrategy snippetCacheStrategy;
public final RankingProfile ranking;
private final Segment indexSegment;
public final String host; // this is the client host that starts the query, not a site operator
public final String sitehash; // this is a domain hash, 6 bytes long or null
public final String authorhash;
- public final String tenant;
+ public final String tenant;
public yacySeed remotepeer;
public final Long time;
// values that are set after a search:
@@ -109,7 +108,7 @@ public final class QueryParams {
public boolean specialRights; // is true if the user has a special authorization and my use more database-extensive options
public final String userAgent;
public boolean filterfailurls;
-
+
public QueryParams(
final String queryString,
final int itemsPerPage,
@@ -124,7 +123,7 @@ public final class QueryParams {
this.excludeHashes = new HandleSet(WordReferenceRow.urlEntryRow.primaryKeyLength, WordReferenceRow.urlEntryRow.objectOrder, 0);
try {
this.queryHashes.put(UTF8.getBytes(queryString));
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
} else {
@@ -164,7 +163,7 @@ public final class QueryParams {
this.transmitcount = 0;
this.filterfailurls = false;
}
-
+
public QueryParams(
final String queryString, final HandleSet queryHashes,
final HandleSet excludeHashes,
@@ -174,7 +173,7 @@ public final class QueryParams {
final int maxDistance, final String prefer, final ContentDomain contentdom,
final String language,
final String navigators,
- final CrawlProfile.CacheStrategy snippetCacheStrategy,
+ final CacheStrategy snippetCacheStrategy,
final int itemsPerPage, final int offset, final String urlMask,
final int domType, final int domMaxTargets,
final Bitfield constraint, final boolean allofconstraint,
@@ -231,57 +230,57 @@ public final class QueryParams {
this.transmitcount = 0;
this.filterfailurls = filterfailurls;
}
-
+
public Segment getSegment() {
return this.indexSegment;
}
-
+
public int neededResults() {
// the number of result lines that must be computed
return this.offset + this.itemsPerPage;
}
-
+
public int displayResults() {
// the number of result lines that are displayed at once (size of result page)
return this.itemsPerPage;
}
-
+
public void setOffset(final int newOffset) {
this.offset = newOffset;
}
-
+
public String contentdom() {
return this.contentdom.toString();
}
-
+
public boolean isLocal() {
return this.domType == SEARCHDOM_LOCAL;
}
-
+
public static HandleSet hashes2Set(final String query) {
final HandleSet keyhashes = new HandleSet(WordReferenceRow.urlEntryRow.primaryKeyLength, WordReferenceRow.urlEntryRow.objectOrder, 0);
if (query != null) {
for (int i = 0; i < (query.length() / Word.commonHashLength); i++) try {
keyhashes.put(ASCII.getBytes(query.substring(i * Word.commonHashLength, (i + 1) * Word.commonHashLength)));
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
}
return keyhashes;
}
-
+
public static HandleSet hashes2Handles(final String query) {
final HandleSet keyhashes = new HandleSet(WordReferenceRow.urlEntryRow.primaryKeyLength, WordReferenceRow.urlEntryRow.objectOrder, 0);
if (query != null) {
for (int i = 0; i < (query.length() / Word.commonHashLength); i++) try {
keyhashes.put(ASCII.getBytes(query.substring(i * Word.commonHashLength, (i + 1) * Word.commonHashLength)));
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
}
}
return keyhashes;
}
-
+
public static String hashSet2hashString(final HandleSet hashes) {
final byte[] bb = new byte[hashes.size() * Word.commonHashLength];
int p = 0;
@@ -310,7 +309,7 @@ public final class QueryParams {
sb.append("]");
return sb.toString();
}
-
+
/**
* check if the given text matches with the query
* this checks inclusion and exclusion words
@@ -325,25 +324,25 @@ public final class QueryParams {
}
return ret;
}
-
+
protected static final boolean anymatch(final String text, final HandleSet keyhashes) {
// returns true if any of the word hashes in keyhashes appear in the String text
// to do this, all words in the string must be recognized and transcoded to word hashes
final HandleSet wordhashes = Word.words2hashesHandles(Condenser.getWords(text, null).keySet());
return SetTools.anymatch(wordhashes, keyhashes);
}
-
+
private static String seps = "'.,/&_"; static {seps += '"';}
-
+
@SuppressWarnings("unchecked")
public static TreeSet<String>[] cleanQuery(String querystring) {
// returns three sets: a query set, a exclude set and a full query set
final TreeSet<String> query = new TreeSet<String>(NaturalOrder.naturalComparator);
final TreeSet<String> exclude = new TreeSet<String>(NaturalOrder.naturalComparator);
final TreeSet<String> fullquery = new TreeSet<String>(NaturalOrder.naturalComparator);
-
+
if ((querystring != null) && (!querystring.isEmpty())) {
-
+
// convert Umlaute
querystring = AbstractScraper.stripAll(querystring.toCharArray()).toLowerCase().trim();
int c;
@@ -376,7 +375,7 @@ public final class QueryParams {
}
return new TreeSet[]{query, exclude, fullquery};
}
-
+
public String queryString(final boolean encodeHTML) {
final String ret;
if (encodeHTML){
@@ -386,25 +385,25 @@ public final class QueryParams {
}
return ret;
}
-
+
public String queryStringForUrl() {
try {
return URLEncoder.encode(this.queryString, "UTF-8");
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
Log.logException(e);
return this.queryString;
}
}
-
+
public TreeSet<String>[] queryWords() {
return cleanQuery(this.queryString);
}
-
+
public void filterOut(final SortedSet<String> blueList) {
// filter out words that appear in this set
// this is applied to the queryHashes
final HandleSet blues = Word.words2hashesHandles(blueList);
- for (final byte[] b: blues) queryHashes.remove(b);
+ for (final byte[] b: blues) this.queryHashes.remove(b);
}
@@ -418,23 +417,23 @@ public final class QueryParams {
entry = i.next();
url = entry.getKey();
anchorText = entry.getValue();
- if (this.matchesText(anchorText)) {
+ if (matchesText(anchorText)) {
matcher.put(url, anchorText);
i.remove();
}
}
return matcher;
}
-
+
private String idCacheAnon = null, idCache = null;
final static private char asterisk = '*';
public String id(final boolean anonymized) {
if (anonymized) {
- if (idCacheAnon != null) return idCacheAnon;
+ if (this.idCacheAnon != null) return this.idCacheAnon;
} else {
- if (idCache != null) return idCache;
+ if (this.idCache != null) return this.idCache;
}
-
+
// generate a string that identifies a search so results can be re-used in a cache
final StringBuilder context = new StringBuilder(120);
if (anonymized) {
@@ -469,13 +468,13 @@ public final class QueryParams {
context.append(asterisk);
context.append(this.maxDistance);
if (anonymized) {
- idCacheAnon = context.toString();
+ this.idCacheAnon = context.toString();
} else {
- idCache = context.toString();
+ this.idCache = context.toString();
}
return context.toString();
}
-
+
/**
* make a query anchor tag
* @param page
@@ -484,9 +483,22 @@ public final class QueryParams {
* @param addToQuery
* @return
*/
- public static String navurl(
+ public static StringBuilder navurl(
final String ext, final int page, final QueryParams theQuery,
- String newQueryString, final String originalUrlMask, final String nav) {
+ final String newQueryString, final String originalUrlMask, final String nav) {
+
+ final StringBuilder sb = navurlBase(ext, theQuery, newQueryString, originalUrlMask, nav);
+
+ sb.append(ampersand);
+ sb.append("startRecord=");
+ sb.append(page * theQuery.displayResults());
+
+ return sb;
+ }
+
+ public static StringBuilder navurlBase(
+ final String ext, final QueryParams theQuery,
+ final String newQueryString, final String originalUrlMask, final String nav) {
final StringBuilder sb = new StringBuilder(120);
sb.append("/yacysearch.");
@@ -498,10 +510,6 @@ public final class QueryParams {
sb.append("maximumRecords=");
sb.append(theQuery.displayResults());
- sb.append(ampersand);
- sb.append("startRecord=");
- sb.append(page * theQuery.displayResults());
-
sb.append(ampersand);
sb.append("resource=");
sb.append((theQuery.isLocal()) ? "local" : "global");
@@ -537,9 +545,9 @@ public final class QueryParams {
sb.append("former=");
sb.append(theQuery.queryStringForUrl());
- return sb.toString();
+ return sb;
}
-
+
private static Pattern StringMatchPattern = Pattern.compile(".*?(\".*?\").*");
/**
* calculate a pattern to match with a string search
@@ -547,11 +555,11 @@ public final class QueryParams {
* @return
*/
public static Pattern stringSearchPattern(String query) {
- StringBuilder p = new StringBuilder(query.length());
+ final StringBuilder p = new StringBuilder(query.length());
p.append("(?iu)");
int seqc = 0;
while (query.length() > 0) {
- Matcher m = StringMatchPattern.matcher(query);
+ final Matcher m = StringMatchPattern.matcher(query);
if (!m.matches()) break;
p.append(".*?").append(query.substring(m.start(1) + 1, m.end(1) - 1));
query = query.substring(m.end(1));
@@ -561,9 +569,9 @@ public final class QueryParams {
p.append(".*");
return Pattern.compile(p.toString());
}
-
- public static void main(String[] args) {
- Pattern p = stringSearchPattern("die \"peer-to-peer Suchmaschine\" ohne Zensur als \"freie Software\" runterladen");
+
+ public static void main(final String[] args) {
+ final Pattern p = stringSearchPattern("die \"peer-to-peer Suchmaschine\" ohne Zensur als \"freie Software\" runterladen");
System.out.println(p.toString());
}
}
diff --git a/source/de/anomic/search/ResultFetcher.java b/source/de/anomic/search/ResultFetcher.java
index 8de83535d..543e3763c 100644
--- a/source/de/anomic/search/ResultFetcher.java
+++ b/source/de/anomic/search/ResultFetcher.java
@@ -33,6 +33,7 @@ import java.util.regex.Pattern;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.protocol.ResponseHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.cora.storage.ScoreMap;
import net.yacy.cora.storage.WeakPriorityBlockingQueue;
import net.yacy.cora.storage.WeakPriorityBlockingQueue.ReverseElement;
@@ -45,7 +46,6 @@ import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.EventTracker;
import net.yacy.kelondro.util.MemoryControl;
import net.yacy.repository.LoaderDispatcher;
-import de.anomic.crawler.CrawlProfile;
import de.anomic.data.WorkTables;
import de.anomic.http.client.Cache;
import de.anomic.yacy.yacySeedDB;
@@ -308,11 +308,11 @@ public class ResultFetcher {
private final long timeout; // the date until this thread should try to work
private long lastLifeSign; // when the last time the run()-loop was executed
private final int id;
- private final CrawlProfile.CacheStrategy cacheStrategy;
+ private final CacheStrategy cacheStrategy;
private final int neededResults;
private final Pattern snippetPattern;
- public Worker(final int id, final long maxlifetime, final CrawlProfile.CacheStrategy cacheStrategy, final Pattern snippetPattern, final int neededResults) {
+ public Worker(final int id, final long maxlifetime, final CacheStrategy cacheStrategy, final Pattern snippetPattern, final int neededResults) {
this.id = id;
this.cacheStrategy = cacheStrategy;
this.lastLifeSign = System.currentTimeMillis();
@@ -390,7 +390,7 @@ public class ResultFetcher {
}
}
- protected ResultEntry fetchSnippet(final URIMetadataRow page, final CrawlProfile.CacheStrategy cacheStrategy) {
+ protected ResultEntry fetchSnippet(final URIMetadataRow page, final CacheStrategy cacheStrategy) {
// Snippet Fetching can has 3 modes:
// 0 - do not fetch snippets
// 1 - fetch snippets offline only
diff --git a/source/de/anomic/search/Segment.java b/source/de/anomic/search/Segment.java
index 3cdfb34b9..d8a590d1f 100644
--- a/source/de/anomic/search/Segment.java
+++ b/source/de/anomic/search/Segment.java
@@ -37,6 +37,7 @@ import java.util.TreeSet;
import net.yacy.cora.document.ASCII;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.Parser;
@@ -61,8 +62,6 @@ import net.yacy.kelondro.rwi.ReferenceFactory;
import net.yacy.kelondro.util.ISO639;
import net.yacy.repository.Blacklist;
import net.yacy.repository.LoaderDispatcher;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
public class Segment {
@@ -73,19 +72,19 @@ public class Segment {
public static final int lowcachedivisor = 900;
public static final long targetFileSize = 256 * 1024 * 1024; // 256 MB
public static final int writeBufferSize = 4 * 1024 * 1024;
-
+
// the reference factory
public static final ReferenceFactory<WordReference> wordReferenceFactory = new WordReferenceFactory();
public static final ReferenceFactory<NavigationReference> navigationReferenceFactory = new NavigationReferenceFactory();
public static final ByteOrder wordOrder = Base64Order.enhancedCoder;
-
+
private final Log log;
protected final IndexCell<WordReference> termIndex;
//private final IndexCell<NavigationReference> authorNavIndex;
protected final MetadataRepository urlMetadata;
private final File segmentPath;
private final IODispatcher merger;
-
+
public Segment(
final Log log,
final File segmentPath,
@@ -93,18 +92,18 @@ public class Segment {
final long maxFileSize,
final boolean useTailCache,
final boolean exceed134217727) throws IOException {
-
+
migrateTextIndex(segmentPath, segmentPath);
migrateTextMetadata(segmentPath, segmentPath);
-
+
log.logInfo("Initializing Segment '" + segmentPath + ".");
this.log = log;
this.segmentPath = segmentPath;
-
+
this.merger = new IODispatcher(1, 1, writeBufferSize);
this.merger.start();
-
+
this.termIndex = new IndexCell<WordReference>(
segmentPath,
"text.index",
@@ -130,35 +129,35 @@ public class Segment {
*/
// create LURL-db
- urlMetadata = new MetadataRepository(segmentPath, "text.urlmd", useTailCache, exceed134217727);
+ this.urlMetadata = new MetadataRepository(segmentPath, "text.urlmd", useTailCache, exceed134217727);
}
-
- public static void migrateTextIndex(File oldSegmentPath, File newSegmentPath) {
- File oldCellPath = new File(oldSegmentPath, "RICELL");
+
+ public static void migrateTextIndex(final File oldSegmentPath, final File newSegmentPath) {
+ final File oldCellPath = new File(oldSegmentPath, "RICELL");
if (!oldCellPath.exists()) return;
- String[] oldIndexFiles = oldCellPath.list();
- for (String oldIndexFile: oldIndexFiles) {
+ final String[] oldIndexFiles = oldCellPath.list();
+ for (final String oldIndexFile: oldIndexFiles) {
if (oldIndexFile.startsWith("index.")) {
- File newFile = new File(newSegmentPath, "text.index." + oldIndexFile.substring(6));
+ final File newFile = new File(newSegmentPath, "text.index." + oldIndexFile.substring(6));
new File(oldCellPath, oldIndexFile).renameTo(newFile);
}
}
oldCellPath.delete();
}
-
- public static void migrateTextMetadata(File oldSegmentPath, File newSegmentPath) {
- File oldMetadataPath = new File(oldSegmentPath, "METADATA");
+
+ public static void migrateTextMetadata(final File oldSegmentPath, final File newSegmentPath) {
+ final File oldMetadataPath = new File(oldSegmentPath, "METADATA");
if (!oldMetadataPath.exists()) return;
- String[] oldMetadataFiles = oldMetadataPath.list();
- for (String oldMetadataFile: oldMetadataFiles) {
+ final String[] oldMetadataFiles = oldMetadataPath.list();
+ for (final String oldMetadataFile: oldMetadataFiles) {
if (oldMetadataFile.startsWith("urls.")) {
- File newFile = new File(newSegmentPath, "text.urlmd." + oldMetadataFile.substring(5));
+ final File newFile = new File(newSegmentPath, "text.urlmd." + oldMetadataFile.substring(5));
new File(oldMetadataPath, oldMetadataFile).renameTo(newFile);
}
}
oldMetadataPath.delete();
}
-
+
public MetadataRepository urlMetadata() {
return this.urlMetadata;
}
@@ -166,11 +165,11 @@ public class Segment {
public IndexCell<WordReference> termIndex() {
return this.termIndex;
}
-
+
public void clear() {
try {
- termIndex.clear();
- urlMetadata.clear();
+ this.termIndex.clear();
+ this.urlMetadata.clear();
} catch (final IOException e) {
Log.logException(e);
}
@@ -178,7 +177,7 @@ public class Segment {
Switchboard.getSwitchboard().peers != null &&
Switchboard.getSwitchboard().peers.mySeed() != null) Switchboard.getSwitchboard().peers.mySeed().resetCounters();
}
-
+
public File getLocation() {
return this.segmentPath;
}
@@ -186,7 +185,7 @@ public class Segment {
/**
* this is called by the switchboard to put in a new page into the index
* use all the words in one condenser object to simultanous create index entries
- *
+ *
* @param url
* @param urlModified
* @param document
@@ -208,18 +207,18 @@ public class Segment {
final int outlinksOther,
final SearchEvent searchEvent,
final String sourceName) {
- RankingProcess rankingProcess = (searchEvent == null) ? null : searchEvent.getRankingResult();
+ final RankingProcess rankingProcess = (searchEvent == null) ? null : searchEvent.getRankingResult();
if (rankingProcess != null) rankingProcess.moreFeeders(1);
int wordCount = 0;
final int urlLength = url.toNormalform(true, true).length();
final int urlComps = MultiProtocolURI.urlComps(url.toString()).length;
-
+
// iterate over all words of context text
final Iterator<Map.Entry<String, Word>> i = condenser.words().entrySet().iterator();
Map.Entry<String, Word> wentry;
String word;
- int len = (document == null) ? urlLength : document.dc_title().length();
- WordReferenceRow ientry = new WordReferenceRow(url.hash(),
+ final int len = (document == null) ? urlLength : document.dc_title().length();
+ final WordReferenceRow ientry = new WordReferenceRow(url.hash(),
urlLength, urlComps, len,
condenser.RESULT_NUMB_WORDS,
condenser.RESULT_NUMB_SENTENCES,
@@ -239,7 +238,7 @@ public class Segment {
wordhash = Word.word2hash(word);
try {
this.termIndex.add(wordhash, ientry);
- } catch (Exception e) {
+ } catch (final Exception e) {
Log.logException(e);
}
wordCount++;
@@ -249,7 +248,7 @@ public class Segment {
container = ReferenceContainer.emptyContainer(Segment.wordReferenceFactory, wordhash, 1);
container.add(ientry);
rankingProcess.add(container, true, sourceName, -1, !i.hasNext());
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
continue;
}
}
@@ -260,8 +259,8 @@ public class Segment {
public void close() {
if (this.merger != null) this.merger.terminate();
- termIndex.close();
- urlMetadata.close();
+ this.termIndex.close();
+ this.urlMetadata.close();
}
public URIMetadataRow storeDocument(
@@ -278,33 +277,33 @@ public class Segment {
final long startTime = System.currentTimeMillis();
// CREATE INDEX
-
+
// load some document metadata
final String dc_title = document.dc_title();
-
+
// do a identification of the language
String language = condenser.language(); // this is a statistical analysation of the content: will be compared with other attributes
- String bymetadata = document.dc_language(); // the languageByMetadata may return null if there was no declaration
+ final String bymetadata = document.dc_language(); // the languageByMetadata may return null if there was no declaration
if (language == null) {
// no statistics available, we take either the metadata (if given) or the TLD
language = (bymetadata == null) ? url.language() : bymetadata;
- if (log.isFine()) log.logFine("LANGUAGE-BY-STATISTICS: " + url + " FAILED, taking " + ((bymetadata == null) ? "TLD" : "metadata") + ": " + language);
+ if (this.log.isFine()) this.log.logFine("LANGUAGE-BY-STATISTICS: " + url + " FAILED, taking " + ((bymetadata == null) ? "TLD" : "metadata") + ": " + language);
} else {
if (bymetadata == null) {
// two possible results: compare and report conflicts
if (language.equals(url.language()))
- if (log.isFine()) log.logFine("LANGUAGE-BY-STATISTICS: " + url + " CONFIRMED - TLD IDENTICAL: " + language);
+ if (this.log.isFine()) this.log.logFine("LANGUAGE-BY-STATISTICS: " + url + " CONFIRMED - TLD IDENTICAL: " + language);
else {
- String error = "LANGUAGE-BY-STATISTICS: " + url + " CONFLICTING: " + language + " (the language given by the TLD is " + url.language() + ")";
+ final String error = "LANGUAGE-BY-STATISTICS: " + url + " CONFLICTING: " + language + " (the language given by the TLD is " + url.language() + ")";
// see if we have a hint in the url that the statistic was right
- String u = url.toNormalform(true, false).toLowerCase();
+ final String u = url.toNormalform(true, false).toLowerCase();
if (!u.contains("/" + language + "/") && !u.contains("/" + ISO639.country(language).toLowerCase() + "/")) {
// no confirmation using the url, use the TLD
language = url.language();
- if (log.isFine()) log.logFine(error + ", corrected using the TLD");
+ if (this.log.isFine()) this.log.logFine(error + ", corrected using the TLD");
} else {
// this is a strong hint that the statistics was in fact correct
- if (log.isFine()) log.logFine(error + ", but the url proves that the statistic is correct");
+ if (this.log.isFine()) this.log.logFine(error + ", but the url proves that the statistic is correct");
}
}
} else {
@@ -322,7 +321,7 @@ public class Segment {
}
}
}
-
+
// create a new loaded URL db entry
if (modDate.getTime() > loadDate.getTime()) modDate = loadDate;
final URIMetadataRow newEntry = new URIMetadataRow(
@@ -331,11 +330,11 @@ public class Segment {
document.dc_creator(), // author
document.dc_subject(' '), // tags
document.dc_publisher(), // publisher (may be important to get location data)
- document.lon(), // decimal degrees as in WGS84;
+ document.lon(), // decimal degrees as in WGS84;
document.lat(), // if unknown both values may be 0.0f;
modDate, // modification date
loadDate, // loaded date
- new Date(loadDate.getTime() + Math.max(0, loadDate.getTime() - modDate.getTime()) / 2), // freshdate, computed with Proxy-TTL formula
+ new Date(loadDate.getTime() + Math.max(0, loadDate.getTime() - modDate.getTime()) / 2), // freshdate, computed with Proxy-TTL formula
(referrerURL == null) ? null : ASCII.String(referrerURL.hash()), // referer hash
new byte[0], // md5
(int) sourcesize, // size
@@ -350,12 +349,12 @@ public class Segment {
document.getVideolinks().size(), // lvideo
document.getApplinks().size() // lapp
);
-
+
// STORE URL TO LOADED-URL-DB
- urlMetadata.store(newEntry); // TODO: should be serialized; integrated in IODispatcher
-
+ this.urlMetadata.store(newEntry); // TODO: should be serialized; integrated in IODispatcher
+
final long storageEndTime = System.currentTimeMillis();
-
+
// STORE PAGE INDEX INTO WORD INDEX DB
final int words = addPageIndex(
url, // document url
@@ -369,13 +368,13 @@ public class Segment {
searchEvent, // a search event that can have results directly
sourceName // the name of the source where the index was created
);
-
+
final long indexingEndTime = System.currentTimeMillis();
-
- if (log.isInfo()) {
+
+ if (this.log.isInfo()) {
// TODO: UTF-8 docDescription seems not to be displayed correctly because
// of string concatenation
- log.logInfo("*Indexed " + words + " words in URL " + url +
+ this.log.logInfo("*Indexed " + words + " words in URL " + url +
" [" + ASCII.String(url.hash()) + "]" +
"\n\tDescription: " + dc_title +
"\n\tMimeType: " + document.dc_format() + " | Charset: " + document.getCharset() + " | " +
@@ -384,21 +383,21 @@ public class Segment {
"\n\tLinkStorageTime: " + (storageEndTime - startTime) + " ms | " +
"indexStorageTime: " + (indexingEndTime - storageEndTime) + " ms");
}
-
+
// finished
return newEntry;
}
-
+
// method for index deletion
- public int removeAllUrlReferences(final DigestURI url, LoaderDispatcher loader, final CrawlProfile.CacheStrategy cacheStrategy) {
+ public int removeAllUrlReferences(final DigestURI url, final LoaderDispatcher loader, final CacheStrategy cacheStrategy) {
return removeAllUrlReferences(url.hash(), loader, cacheStrategy);
}
-
- public void removeAllUrlReferences(final HandleSet urls, LoaderDispatcher loader, final CrawlProfile.CacheStrategy cacheStrategy) {
- for (byte[] urlhash: urls) removeAllUrlReferences(urlhash, loader, cacheStrategy);
+
+ public void removeAllUrlReferences(final HandleSet urls, final LoaderDispatcher loader, final CacheStrategy cacheStrategy) {
+ for (final byte[] urlhash: urls) removeAllUrlReferences(urlhash, loader, cacheStrategy);
}
-
+
/**
* find all the words in a specific resource and remove the url reference from every word index
* finally, delete the url entry
@@ -407,7 +406,7 @@ public class Segment {
* @param cacheStrategy
* @return number of removed words
*/
- public int removeAllUrlReferences(final byte[] urlhash, LoaderDispatcher loader, final CrawlProfile.CacheStrategy cacheStrategy) {
+ public int removeAllUrlReferences(final byte[] urlhash, final LoaderDispatcher loader, final CacheStrategy cacheStrategy) {
if (urlhash == null) return 0;
// determine the url string
@@ -415,7 +414,7 @@ public class Segment {
if (entry == null) return 0;
final URIMetadataRow.Components metadata = entry.metadata();
if (metadata == null || metadata.url() == null) return 0;
-
+
try {
// parse the resource
final Document document = Document.mergeDocuments(metadata.url(), null, loader.loadDocuments(loader.request(metadata.url(), true, false), cacheStrategy, 10000, Long.MAX_VALUE));
@@ -427,30 +426,30 @@ public class Segment {
// get the word set
Set<String> words = null;
words = new Condenser(document, true, true, null).words().keySet();
-
+
// delete all word references
int count = 0;
if (words != null) count = termIndex().remove(Word.words2hashesHandles(words), urlhash);
-
+
// finally delete the url entry itself
urlMetadata().remove(urlhash);
return count;
} catch (final Parser.Failure e) {
return 0;
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
return 0;
}
}
-
+
// The Cleaner class was provided as "UrldbCleaner" by Hydrox
public synchronized ReferenceCleaner getReferenceCleaner(final byte[] startHash) {
return new ReferenceCleaner(startHash);
}
-
+
public class ReferenceCleaner extends Thread {
-
+
private final byte[] startHash;
private boolean run = true;
private boolean pause = false;
@@ -458,12 +457,12 @@ public class Segment {
public byte[] wordHashNow = null;
public byte[] lastWordHash = null;
public int lastDeletionCounter = 0;
-
+
public ReferenceCleaner(final byte[] startHash) {
this.startHash = startHash;
this.rwiCountAtStart = termIndex().sizesMax();
}
-
+
public void run() {
Log.logInfo("INDEXCLEANER", "IndexCleaner-Thread started");
ReferenceContainer<WordReference> container = null;
@@ -471,18 +470,18 @@ public class Segment {
DigestURI url = null;
final HandleSet urlHashs = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 0);
try {
- Iterator<ReferenceContainer<WordReference>> indexContainerIterator = termIndex.references(startHash, false, 100, false).iterator();
- while (indexContainerIterator.hasNext() && run) {
+ Iterator<ReferenceContainer<WordReference>> indexContainerIterator = Segment.this.termIndex.references(this.startHash, false, 100, false).iterator();
+ while (indexContainerIterator.hasNext() && this.run) {
waiter();
container = indexContainerIterator.next();
final Iterator<WordReference> containerIterator = container.entries();
- wordHashNow = container.getTermHash();
- while (containerIterator.hasNext() && run) {
+ this.wordHashNow = container.getTermHash();
+ while (containerIterator.hasNext() && this.run) {
waiter();
entry = new WordReferenceVars(containerIterator.next());
// System.out.println("Wordhash: "+wordHash+" UrlHash:
// "+entry.getUrlHash());
- final URIMetadataRow ue = urlMetadata.load(entry.urlhash());
+ final URIMetadataRow ue = Segment.this.urlMetadata.load(entry.urlhash());
if (ue == null) {
urlHashs.put(entry.urlhash());
} else {
@@ -493,18 +492,18 @@ public class Segment {
}
}
if (!urlHashs.isEmpty()) try {
- final int removed = termIndex.remove(container.getTermHash(), urlHashs);
+ final int removed = Segment.this.termIndex.remove(container.getTermHash(), urlHashs);
Log.logFine("INDEXCLEANER", ASCII.String(container.getTermHash()) + ": " + removed + " of " + container.size() + " URL-entries deleted");
- lastWordHash = container.getTermHash();
- lastDeletionCounter = urlHashs.size();
+ this.lastWordHash = container.getTermHash();
+ this.lastDeletionCounter = urlHashs.size();
urlHashs.clear();
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
-
+
if (!containerIterator.hasNext()) {
// We may not be finished yet, try to get the next chunk of wordHashes
- final TreeSet<ReferenceContainer<WordReference>> containers = termIndex.references(container.getTermHash(), false, 100, false);
+ final TreeSet<ReferenceContainer<WordReference>> containers = Segment.this.termIndex.references(container.getTermHash(), false, 100, false);
indexContainerIterator = containers.iterator();
// Make sure we don't get the same wordhash twice, but don't skip a word
if ((indexContainerIterator.hasNext()) && (!container.getTermHash().equals(indexContainerIterator.next().getTermHash()))) {
@@ -519,18 +518,18 @@ public class Segment {
}
Log.logInfo("INDEXCLEANER", "IndexCleaner-Thread stopped");
}
-
+
public void abort() {
synchronized(this) {
- run = false;
- this.notifyAll();
+ this.run = false;
+ notifyAll();
}
}
public void pause() {
synchronized (this) {
- if (!pause) {
- pause = true;
+ if (!this.pause) {
+ this.pause = true;
Log.logInfo("INDEXCLEANER", "IndexCleaner-Thread paused");
}
}
@@ -538,9 +537,9 @@ public class Segment {
public void endPause() {
synchronized (this) {
- if (pause) {
- pause = false;
- this.notifyAll();
+ if (this.pause) {
+ this.pause = false;
+ notifyAll();
Log.logInfo("INDEXCLEANER", "IndexCleaner-Thread resumed");
}
}
@@ -558,11 +557,11 @@ public class Segment {
}
}
}
-
+
public int rwisize() {
return termIndex().sizesMax();
}
-
+
public int urlsize() {
return urlMetadata().size();
}
diff --git a/source/de/anomic/search/Switchboard.java b/source/de/anomic/search/Switchboard.java
index ca163e669..68d63a69f 100644
--- a/source/de/anomic/search/Switchboard.java
+++ b/source/de/anomic/search/Switchboard.java
@@ -9,7 +9,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -92,6 +92,7 @@ import net.yacy.cora.protocol.http.ProxySettings;
import net.yacy.cora.services.federated.solr.SolrChardingConnector;
import net.yacy.cora.services.federated.solr.SolrChardingSelection;
import net.yacy.cora.services.federated.solr.SolrScheme;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.LibraryProvider;
@@ -116,8 +117,8 @@ import net.yacy.kelondro.util.EventTracker;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.util.MemoryControl;
import net.yacy.kelondro.util.MemoryTracker;
-import net.yacy.kelondro.util.SetTools;
import net.yacy.kelondro.util.OS;
+import net.yacy.kelondro.util.SetTools;
import net.yacy.kelondro.workflow.BusyThread;
import net.yacy.kelondro.workflow.InstantBusyThread;
import net.yacy.kelondro.workflow.WorkflowJob;
@@ -126,7 +127,6 @@ import net.yacy.kelondro.workflow.WorkflowThread;
import net.yacy.repository.Blacklist;
import net.yacy.repository.FilterEngine;
import net.yacy.repository.LoaderDispatcher;
-
import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.CrawlQueues;
import de.anomic.crawler.CrawlStacker;
@@ -135,63 +135,62 @@ import de.anomic.crawler.NoticedURL;
import de.anomic.crawler.ResourceObserver;
import de.anomic.crawler.ResultImages;
import de.anomic.crawler.ResultURLs;
-import de.anomic.crawler.RobotsTxt;
-import de.anomic.crawler.CrawlProfile.CacheStrategy;
import de.anomic.crawler.ResultURLs.EventOrigin;
+import de.anomic.crawler.RobotsTxt;
import de.anomic.crawler.ZURL.FailCategory;
import de.anomic.crawler.retrieval.Request;
import de.anomic.crawler.retrieval.Response;
-import de.anomic.data.WorkTables;
-import de.anomic.data.URLLicense;
import de.anomic.data.BlogBoard;
import de.anomic.data.BlogBoardComments;
import de.anomic.data.BookmarksDB;
import de.anomic.data.ListManager;
import de.anomic.data.MessageBoard;
+import de.anomic.data.URLLicense;
import de.anomic.data.UserDB;
+import de.anomic.data.WorkTables;
import de.anomic.data.wiki.WikiBoard;
import de.anomic.data.wiki.WikiCode;
import de.anomic.data.wiki.WikiParser;
import de.anomic.http.client.Cache;
import de.anomic.http.server.RobotsTxtConfig;
import de.anomic.net.UPnP;
-import de.anomic.server.serverSwitch;
import de.anomic.server.serverCore;
-import de.anomic.tools.crypt;
+import de.anomic.server.serverSwitch;
import de.anomic.tools.CryptoLib;
+import de.anomic.tools.crypt;
+import de.anomic.yacy.Tray;
import de.anomic.yacy.yacyBuildProperties;
import de.anomic.yacy.yacyChannel;
import de.anomic.yacy.yacyClient;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsPool;
+import de.anomic.yacy.yacyRelease;
import de.anomic.yacy.yacySeed;
-import de.anomic.yacy.Tray;
import de.anomic.yacy.yacySeedDB;
import de.anomic.yacy.yacyUpdateLocation;
-import de.anomic.yacy.yacyRelease;
import de.anomic.yacy.dht.Dispatcher;
import de.anomic.yacy.dht.PeerSelection;
import de.anomic.yacy.graphics.WebStructureGraph;
public final class Switchboard extends serverSwitch {
-
+
// load slots
public static int xstackCrawlSlots = 2000;
public static long lastPPMUpdate = System.currentTimeMillis()- 30000;
private static final int dhtMaxContainerCount = 500;
private int dhtMaxReferenceCount = 1000;
-
+
// colored list management
public static SortedSet<String> badwords = new TreeSet<String>(NaturalOrder.naturalComparator);
public static SortedSet<String> stopwords = new TreeSet<String>(NaturalOrder.naturalComparator);
public static SortedSet<String> blueList = null;
public static HandleSet badwordHashes = null;
public static HandleSet blueListHashes = null;
- public static HandleSet stopwordHashes = null;
+ public static HandleSet stopwordHashes = null;
public static Blacklist urlBlacklist = null;
-
+
public static WikiParser wikiParser = null;
-
+
// storage management
public File htCachePath;
public final File dictionariesPath;
@@ -233,49 +232,49 @@ public final class Switchboard extends serverSwitch {
public LinkedBlockingQueue<String> trail;
public yacySeedDB peers;
public WorkTables tables;
-
+
public WorkflowProcessor<indexingQueueEntry> indexingDocumentProcessor;
public WorkflowProcessor<indexingQueueEntry> indexingCondensementProcessor;
public WorkflowProcessor<indexingQueueEntry> indexingAnalysisProcessor;
public WorkflowProcessor<indexingQueueEntry> indexingStorageProcessor;
-
+
public RobotsTxtConfig robotstxtConfig = null;
public boolean useTailCache;
public boolean exceed134217727;
-
+
private final Semaphore shutdownSync = new Semaphore(0);
private boolean terminate = false;
public SolrChardingConnector solrConnector = null;
-
+
//private Object crawlingPausedSync = new Object();
- //private boolean crawlingIsPaused = false;
-
- public Hashtable<String, Object[]> crawlJobsStatus = new Hashtable<String, Object[]>();
-
+ //private boolean crawlingIsPaused = false;
+
+ public Hashtable<String, Object[]> crawlJobsStatus = new Hashtable<String, Object[]>();
+
private static Switchboard sb = null;
-
+
public Switchboard(final File dataPath, final File appPath, final String initPath, final String configPath) throws IOException {
super(dataPath, appPath, initPath, configPath);
MemoryTracker.startSystemProfiling();
sb = this;
-
+
// set loglevel and log
setLog(new Log("PLASMA"));
-
+
// set default peer name
yacySeed.ANON_PREFIX = getConfig("peernameprefix", "_anon");
-
+
// UPnP port mapping
if (getConfigBool(SwitchboardConstants.UPNP_ENABLED, false)) {
InstantBusyThread.oneTimeJob(UPnP.class, "addPortMapping", UPnP.log, 0);
}
-
+
// init TrayIcon if possible
Tray.init(this);
-
+
// remote proxy configuration
initRemoteProxy();
-
+
// memory configuration
this.useTailCache = getConfigBool("ramcopy", true);
if (MemoryControl.available() > 1024 * 1024 * 1024 * 1) {
@@ -285,8 +284,8 @@ public final class Switchboard extends serverSwitch {
if (MemoryControl.available() > 1024 * 1024 * 1024 * 2) {
this.exceed134217727 = true;
}
-
- // load values from configs
+
+ // load values from configs
final File indexPath = getDataPath(SwitchboardConstants.INDEX_PRIMARY_PATH, SwitchboardConstants.INDEX_PATH_DEFAULT);
this.log.logConfig("Index Primary Path: " + indexPath.toString());
this.listsPath = getDataPath(SwitchboardConstants.LISTS_PATH, SwitchboardConstants.LISTS_PATH_DEFAULT);
@@ -300,8 +299,8 @@ public final class Switchboard extends serverSwitch {
// init global host name cache
this.workPath.mkdirs();
- Domains.init(new File(workPath, "globalhosts.list"));
-
+ Domains.init(new File(this.workPath, "globalhosts.list"));
+
// init sessionid name file
final String sessionidNamesFile = getConfig("sessionidNamesFile","defaults/sessionid.names");
this.log.logConfig("Loading sessionid file " + sessionidNamesFile);
@@ -309,36 +308,36 @@ public final class Switchboard extends serverSwitch {
// init tables
this.tables = new WorkTables(this.workPath);
-
+
// init libraries
this.log.logConfig("initializing libraries");
new Thread() {
@Override
public void run() {
- LibraryProvider.initialize(dictionariesPath);
+ LibraryProvider.initialize(Switchboard.this.dictionariesPath);
}
}.start();
-
+
// set a high maximum cache size to current size; this is adopted later automatically
final int wordCacheMaxCount = (int) getConfigLong(SwitchboardConstants.WORDCACHE_MAX_COUNT, 20000);
setConfig(SwitchboardConstants.WORDCACHE_MAX_COUNT, Integer.toString(wordCacheMaxCount));
// load the network definition
overwriteNetworkDefinition();
-
+
// start indexing management
- log.logConfig("Starting Indexing Management");
+ this.log.logConfig("Starting Indexing Management");
final String networkName = getConfig(SwitchboardConstants.NETWORK_NAME, "");
- final long fileSizeMax = (OS.isWindows) ? sb.getConfigLong("filesize.max.win", (long) Integer.MAX_VALUE) : sb.getConfigLong("filesize.max.other", (long) Integer.MAX_VALUE);
+ final long fileSizeMax = (OS.isWindows) ? sb.getConfigLong("filesize.max.win", Integer.MAX_VALUE) : sb.getConfigLong("filesize.max.other", Integer.MAX_VALUE);
final int redundancy = (int) sb.getConfigLong("network.unit.dhtredundancy.senior", 1);
final int partitionExponent = (int) sb.getConfigLong("network.unit.dht.partitionExponent", 0);
this.networkRoot = new File(new File(indexPath, networkName), "NETWORK");
this.queuesRoot = new File(new File(indexPath, networkName), "QUEUES");
this.networkRoot.mkdirs();
this.queuesRoot.mkdirs();
- final File mySeedFile = new File(networkRoot, yacySeedDB.DBFILE_OWN_SEED);
- peers = new yacySeedDB(
- networkRoot,
+ final File mySeedFile = new File(this.networkRoot, yacySeedDB.DBFILE_OWN_SEED);
+ this.peers = new yacySeedDB(
+ this.networkRoot,
"seed.new.heap",
"seed.old.heap",
"seed.pot.heap",
@@ -347,11 +346,11 @@ public final class Switchboard extends serverSwitch {
partitionExponent,
this.useTailCache,
this.exceed134217727);
- File oldSingleSegment = new File(new File(indexPath, networkName), "TEXT");
- File newSegmentsPath = new File(new File(indexPath, networkName), "SEGMENTS");
+ final File oldSingleSegment = new File(new File(indexPath, networkName), "TEXT");
+ final File newSegmentsPath = new File(new File(indexPath, networkName), "SEGMENTS");
Segments.migrateOld(oldSingleSegment, newSegmentsPath, getConfig(SwitchboardConstants.SEGMENT_PUBLIC, "default"));
- indexSegments = new Segments(
- log,
+ this.indexSegments = new Segments(
+ this.log,
newSegmentsPath,
wordCacheMaxCount,
fileSizeMax,
@@ -359,54 +358,54 @@ public final class Switchboard extends serverSwitch {
this.exceed134217727);
// set the default segment names
setDefaultSegments();
-
+
// load domainList
try {
this.domainList = null;
if(!getConfig("network.unit.domainlist", "").equals("")) {
- Reader r = getConfigFileFromWebOrLocally(getConfig("network.unit.domainlist", ""), getAppPath().getAbsolutePath(), new File(this.networkRoot, "domainlist.txt"));
+ final Reader r = getConfigFileFromWebOrLocally(getConfig("network.unit.domainlist", ""), getAppPath().getAbsolutePath(), new File(this.networkRoot, "domainlist.txt"));
this.domainList = new FilterEngine();
this.domainList.loadList(new BufferedReader(r), null);
}
- } catch (FileNotFoundException e) {
- log.logSevere("CONFIG: domainlist not found: " + e.getMessage());
- } catch (IOException e) {
- log.logSevere("CONFIG: error while retrieving domainlist: " + e.getMessage());
+ } catch (final FileNotFoundException e) {
+ this.log.logSevere("CONFIG: domainlist not found: " + e.getMessage());
+ } catch (final IOException e) {
+ this.log.logSevere("CONFIG: error while retrieving domainlist: " + e.getMessage());
}
-
+
// create a crawler
- crawler = new CrawlSwitchboard(
+ this.crawler = new CrawlSwitchboard(
networkName,
- log,
+ this.log,
this.queuesRoot);
-
+
// start yacy core
- log.logConfig("Starting YaCy Protocol Core");
+ this.log.logConfig("Starting YaCy Protocol Core");
this.yc = new yacyCore(this);
InstantBusyThread.oneTimeJob(this, "loadSeedLists", yacyCore.log, 0);
//final long startedSeedListAquisition = System.currentTimeMillis();
-
+
// init a DHT transmission dispatcher
- this.dhtDispatcher = (peers.sizeConnected() == 0) ? null : new Dispatcher(
- indexSegments.segment(Segments.Process.LOCALCRAWLING),
- peers,
- true,
+ this.dhtDispatcher = (this.peers.sizeConnected() == 0) ? null : new Dispatcher(
+ this.indexSegments.segment(Segments.Process.LOCALCRAWLING),
+ this.peers,
+ true,
10000);
-
+
// set up local robots.txt
this.robotstxtConfig = RobotsTxtConfig.init(this);
-
+
// setting timestamp of last proxy access
this.proxyLastAccess = System.currentTimeMillis() - 10000;
this.localSearchLastAccess = System.currentTimeMillis() - 10000;
this.remoteSearchLastAccess = System.currentTimeMillis() - 10000;
- this.webStructure = new WebStructureGraph(new File(queuesRoot, "webStructure.map"));
-
+ this.webStructure = new WebStructureGraph(new File(this.queuesRoot, "webStructure.map"));
+
// configuring list path
- if (!(listsPath.exists())) {
- listsPath.mkdirs();
+ if (!(this.listsPath.exists())) {
+ this.listsPath.mkdirs();
}
-
+
// load coloured lists
if (blueList == null) {
// read only once upon first instantiation of this class
@@ -418,7 +417,7 @@ public final class Switchboard extends serverSwitch {
blueList.size() + " entries, " +
ppRamString(plasmaBlueListFile.length()/1024));
}
-
+
// load blacklist
this.log.logConfig("Loading blacklist ...");
final File blacklistsPath = getDataPath(SwitchboardConstants.LISTS_PATH, SwitchboardConstants.LISTS_PATH_DEFAULT);
@@ -450,7 +449,7 @@ public final class Switchboard extends serverSwitch {
// load ranking from distribution
final File rankingPath = new File(this.appPath, "ranking/YBR".replace('/', File.separatorChar));
BlockRank.loadBlockRankTable(rankingPath, 16);
-
+
// load distributed ranking
// very large memory configurations allow to re-compute a ranking table
/*
@@ -464,7 +463,7 @@ public final class Switchboard extends serverSwitch {
} else {
hostIndex = BlockRank.loadHostIndex(hostIndexFile);
}
-
+
// use an index segment to find hosts for given host hashes
String segmentName = getConfig(SwitchboardConstants.SEGMENT_PUBLIC, "default");
Segment segment = indexSegments.segment(segmentName);
@@ -475,11 +474,11 @@ public final class Switchboard extends serverSwitch {
} catch (IOException e) {
hostHashResolver = new HashMap<String, HostStat>();
}
-
+
// recursively compute a new ranking table
BlockRank.ybrTables = BlockRank.evaluate(hostIndex, hostHashResolver, null, 0);
hostIndex = null; // we don't need that here any more, so free the memory
-
+
// use the web structure and the hostHash resolver to analyse the ranking table
BlockRank.analyse(BlockRank.ybrTables, webStructure, hostHashResolver);
// store the new table
@@ -487,43 +486,43 @@ public final class Switchboard extends serverSwitch {
}
}.start();
*/
-
+
// load the robots.txt db
this.log.logConfig("Initializing robots.txt DB");
- robots = new RobotsTxt(this.tables.getHeap(WorkTables.TABLE_ROBOTS_NAME));
- this.log.logConfig("Loaded robots.txt DB: " + robots.size() + " entries");
-
+ this.robots = new RobotsTxt(this.tables.getHeap(WorkTables.TABLE_ROBOTS_NAME));
+ this.log.logConfig("Loaded robots.txt DB: " + this.robots.size() + " entries");
+
// start a cache manager
- log.logConfig("Starting HT Cache Manager");
-
+ this.log.logConfig("Starting HT Cache Manager");
+
// create the cache directory
- htCachePath = getDataPath(SwitchboardConstants.HTCACHE_PATH, SwitchboardConstants.HTCACHE_PATH_DEFAULT);
- this.log.logInfo("HTCACHE Path = " + htCachePath.getAbsolutePath());
+ this.htCachePath = getDataPath(SwitchboardConstants.HTCACHE_PATH, SwitchboardConstants.HTCACHE_PATH_DEFAULT);
+ this.log.logInfo("HTCACHE Path = " + this.htCachePath.getAbsolutePath());
final long maxCacheSize = 1024 * 1024 * Long.parseLong(getConfig(SwitchboardConstants.PROXY_CACHE_SIZE, "2")); // this is megabyte
- Cache.init(htCachePath, peers.mySeed().hash, maxCacheSize);
-
+ Cache.init(this.htCachePath, this.peers.mySeed().hash, maxCacheSize);
+
// create the surrogates directories
- surrogatesInPath = getDataPath(SwitchboardConstants.SURROGATES_IN_PATH, SwitchboardConstants.SURROGATES_IN_PATH_DEFAULT);
- this.log.logInfo("surrogates.in Path = " + surrogatesInPath.getAbsolutePath());
- surrogatesInPath.mkdirs();
- surrogatesOutPath = getDataPath(SwitchboardConstants.SURROGATES_OUT_PATH, SwitchboardConstants.SURROGATES_OUT_PATH_DEFAULT);
- this.log.logInfo("surrogates.out Path = " + surrogatesOutPath.getAbsolutePath());
- surrogatesOutPath.mkdirs();
-
+ this.surrogatesInPath = getDataPath(SwitchboardConstants.SURROGATES_IN_PATH, SwitchboardConstants.SURROGATES_IN_PATH_DEFAULT);
+ this.log.logInfo("surrogates.in Path = " + this.surrogatesInPath.getAbsolutePath());
+ this.surrogatesInPath.mkdirs();
+ this.surrogatesOutPath = getDataPath(SwitchboardConstants.SURROGATES_OUT_PATH, SwitchboardConstants.SURROGATES_OUT_PATH_DEFAULT);
+ this.log.logInfo("surrogates.out Path = " + this.surrogatesOutPath.getAbsolutePath());
+ this.surrogatesOutPath.mkdirs();
+
// create the release download directory
- releasePath = getDataPath(SwitchboardConstants.RELEASE_PATH, SwitchboardConstants.RELEASE_PATH_DEFAULT);
- releasePath.mkdirs();
- this.log.logInfo("RELEASE Path = " + releasePath.getAbsolutePath());
-
+ this.releasePath = getDataPath(SwitchboardConstants.RELEASE_PATH, SwitchboardConstants.RELEASE_PATH_DEFAULT);
+ this.releasePath.mkdirs();
+ this.log.logInfo("RELEASE Path = " + this.releasePath.getAbsolutePath());
+
// starting message board
initMessages();
-
+
// starting wiki
initWiki();
-
+
//starting blog
initBlog();
-
+
// init User DB
this.log.logConfig("Loading User DB");
final File userDbFile = new File(getDataPath(), "DATA/SETTINGS/user.heap");
@@ -531,19 +530,19 @@ public final class Switchboard extends serverSwitch {
this.log.logConfig("Loaded User DB from file " + userDbFile.getName() +
", " + this.userDB.size() + " entries" +
", " + ppRamString(userDbFile.length()/1024));
-
+
// init html parser evaluation scheme
File parserPropertiesPath = new File("defaults/");
String[] settingsList = parserPropertiesPath.list();
- for (String l: settingsList) {
+ for (final String l: settingsList) {
if (l.startsWith("parser.") && l.endsWith(".properties")) Evaluation.add(new File(parserPropertiesPath, l));
}
parserPropertiesPath = new File(getDataPath(), "DATA/SETTINGS/");
settingsList = parserPropertiesPath.list();
- for (String l: settingsList) {
+ for (final String l: settingsList) {
if (l.startsWith("parser.") && l.endsWith(".properties")) Evaluation.add(new File(parserPropertiesPath, l));
}
-
+
// init bookmarks DB: needs more time since this does a DNS lookup for each Bookmark.
// Can be started concurrently
new Thread(){
@@ -551,35 +550,35 @@ public final class Switchboard extends serverSwitch {
public void run() {
try {
initBookmarks();
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
}.start();
-
+
// define a realtime parsable mimetype list
- log.logConfig("Parser: Initializing Mime Type deny list");
+ this.log.logConfig("Parser: Initializing Mime Type deny list");
TextParser.setDenyMime(getConfig(SwitchboardConstants.PARSER_MIME_DENY, ""));
-
+
// set up the solr interface
- String solrurls = this.getConfig("federated.service.solr.indexing.url", "http://127.0.0.1:8983/solr");
- boolean usesolr = this.getConfigBool("federated.service.solr.indexing.enabled", false) & solrurls.length() > 0;
+ final String solrurls = getConfig("federated.service.solr.indexing.url", "http://127.0.0.1:8983/solr");
+ final boolean usesolr = getConfigBool("federated.service.solr.indexing.enabled", false) & solrurls.length() > 0;
try {
this.solrConnector = (usesolr) ? new SolrChardingConnector(solrurls, SolrScheme.SolrCellExtended, SolrChardingSelection.Method.MODULO_HOST_MD5) : null;
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
this.solrConnector = null;
}
-
+
// start a loader
- log.logConfig("Starting Crawl Loader");
+ this.log.logConfig("Starting Crawl Loader");
this.loader = new LoaderDispatcher(this);
- Map<String, File> oaiFriends = OAIListFriendsLoader.loadListFriendsSources(new File("defaults/oaiListFriendsSource.xml"), getDataPath());
+ final Map<String, File> oaiFriends = OAIListFriendsLoader.loadListFriendsSources(new File("defaults/oaiListFriendsSource.xml"), getDataPath());
OAIListFriendsLoader.init(this.loader, oaiFriends);
- this.crawlQueues = new CrawlQueues(this, queuesRoot);
+ this.crawlQueues = new CrawlQueues(this, this.queuesRoot);
this.crawlQueues.noticeURL.setMinimumDelta(
- this.getConfigLong("minimumLocalDelta", this.crawlQueues.noticeURL.getMinimumLocalDelta()),
- this.getConfigLong("minimumGlobalDelta", this.crawlQueues.noticeURL.getMinimumGlobalDelta()));
+ getConfigLong("minimumLocalDelta", this.crawlQueues.noticeURL.getMinimumLocalDelta()),
+ getConfigLong("minimumGlobalDelta", this.crawlQueues.noticeURL.getMinimumGlobalDelta()));
/*
* Creating sync objects and loading status for the crawl jobs
@@ -596,16 +595,16 @@ public final class Switchboard extends serverSwitch {
this.crawlJobsStatus.put(SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER, new Object[]{
new Object(),
Boolean.valueOf(getConfig(SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER + "_isPaused", "false"))});
-
+
// init cookie-Monitor
this.log.logConfig("Starting Cookie Monitor");
this.outgoingCookies = new ConcurrentHashMap<String, Object[]>();
this.incomingCookies = new ConcurrentHashMap<String, Object[]>();
-
+
// init search history trackers
this.localSearchTracker = new ConcurrentHashMap<String, TreeSet<Long>>(); // String:TreeSet - IP:set of Long(accessTime)
this.remoteSearchTracker = new ConcurrentHashMap<String, TreeSet<Long>>();
-
+
// init messages: clean up message symbol
final File notifierSource = new File(getAppPath(), getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT) + "/env/grafics/empty.gif");
final File notifierDest = new File(getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT), "notifier.gif");
@@ -613,19 +612,19 @@ public final class Switchboard extends serverSwitch {
FileUtils.copy(notifierSource, notifierDest);
} catch (final IOException e) {
}
-
+
// init nameCacheNoCachingList
Domains.setNoCachingPatterns(getConfig(SwitchboardConstants.HTTPC_NAME_CACHE_CACHING_PATTERNS_NO,""));
-
+
// generate snippets cache
- log.logConfig("Initializing Snippet Cache");
-
+ this.log.logConfig("Initializing Snippet Cache");
+
// init the wiki
wikiParser = new WikiCode();
-
+
// initializing the resourceObserver
InstantBusyThread.oneTimeJob(ResourceObserver.class, "initThread", ResourceObserver.log, 0);
-
+
// initializing the stackCrawlThread
this.crawlStacker = new CrawlStacker(
this.crawlQueues,
@@ -635,10 +634,10 @@ public final class Switchboard extends serverSwitch {
isIntranetMode(),
isGlobalMode(),
this.domainList); // Intranet and Global mode may be both true!
-
+
// possibly switch off localIP check
- Domains.setNoLocalCheck(this.isAllIPMode());
-
+ Domains.setNoLocalCheck(isAllIPMode());
+
// check status of account configuration: when local url crawling is allowed, it is not allowed
// that an automatic authorization of localhost is done, because in this case crawls from local
// addresses are blocked to prevent attack szenarios where remote pages contain links to localhost
@@ -649,17 +648,17 @@ public final class Switchboard extends serverSwitch {
// We must remove that here to prevent that a user cannot log in any more
setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "");
// after this a message must be generated to alert the user to set a new password
- log.logInfo("RANDOM PASSWORD REMOVED! User must set a new password");
+ this.log.logInfo("RANDOM PASSWORD REMOVED! User must set a new password");
}
}
-
+
// initializing dht chunk generation
this.dhtMaxReferenceCount = (int) getConfigLong(SwitchboardConstants.INDEX_DIST_CHUNK_SIZE_START, 50);
-
+
// init robinson cluster
// before we do that, we wait some time until the seed list is loaded.
this.clusterhashes = this.peers.clusterHashes(getConfig("cluster.peers.yacydomain", ""));
-
+
// deploy blocking threads
this.indexingStorageProcessor = new WorkflowProcessor<indexingQueueEntry>(
"storeDocumentIndex",
@@ -670,22 +669,22 @@ public final class Switchboard extends serverSwitch {
"webStructureAnalysis",
"This just stores the link structure of the document into a web structure database.",
new String[]{"storeDocumentIndex"},
- this, "webStructureAnalysis", 2 * WorkflowProcessor.availableCPU, indexingStorageProcessor, WorkflowProcessor.availableCPU);
+ this, "webStructureAnalysis", 2 * WorkflowProcessor.availableCPU, this.indexingStorageProcessor, WorkflowProcessor.availableCPU);
this.indexingCondensementProcessor = new WorkflowProcessor<indexingQueueEntry>(
"condenseDocument",
"This does a structural analysis of plain texts: markup of headlines, slicing into phrases (i.e. sentences), markup with position, counting of words, calculation of term frequency.",
new String[]{"webStructureAnalysis"},
- this, "condenseDocument", 4 * WorkflowProcessor.availableCPU, indexingAnalysisProcessor, WorkflowProcessor.availableCPU);
+ this, "condenseDocument", 4 * WorkflowProcessor.availableCPU, this.indexingAnalysisProcessor, WorkflowProcessor.availableCPU);
this.indexingDocumentProcessor = new WorkflowProcessor<indexingQueueEntry>(
"parseDocument",
"This does the parsing of the newly loaded documents from the web. The result is not only a plain text document, but also a list of URLs that are embedded into the document. The urls are handed over to the CrawlStacker. This process has two child process queues!",
new String[]{"condenseDocument", "CrawlStacker"},
- this, "parseDocument", 4 * WorkflowProcessor.availableCPU, indexingCondensementProcessor, WorkflowProcessor.availableCPU);
-
+ this, "parseDocument", 4 * WorkflowProcessor.availableCPU, this.indexingCondensementProcessor, WorkflowProcessor.availableCPU);
+
// deploy busy threads
- log.logConfig("Starting Threads");
+ this.log.logConfig("Starting Threads");
MemoryControl.gc(10000, "plasmaSwitchboard, help for profiler"); // help for profiler - thq
-
+
deployThread(SwitchboardConstants.CLEANUP, "Cleanup", "simple cleaning process for monitoring information", null,
new InstantBusyThread(
this,
@@ -704,7 +703,7 @@ public final class Switchboard extends serverSwitch {
10000);
deployThread(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL, "Remote Crawl Job", "thread that performes a single crawl/indexing step triggered by a remote peer", "/IndexCreateWWWRemoteQueue_p.html",
new InstantBusyThread(
- crawlQueues,
+ this.crawlQueues,
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_METHOD_START,
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_METHOD_JOBCOUNT,
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_METHOD_FREEMEM,
@@ -712,7 +711,7 @@ public final class Switchboard extends serverSwitch {
10000);
deployThread(SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER, "Remote Crawl URL Loader", "thread that loads remote crawl lists from other peers", null,
new InstantBusyThread(
- crawlQueues,
+ this.crawlQueues,
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_METHOD_START,
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_METHOD_JOBCOUNT,
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_METHOD_FREEMEM,
@@ -720,7 +719,7 @@ public final class Switchboard extends serverSwitch {
10000); // error here?
deployThread(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL, "Local Crawl", "thread that performes a single crawl step from the local crawl queue", "/IndexCreateWWWLocalQueue_p.html",
new InstantBusyThread(
- crawlQueues,
+ this.crawlQueues,
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_METHOD_START,
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_METHOD_JOBCOUNT,
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_METHOD_FREEMEM,
@@ -728,7 +727,7 @@ public final class Switchboard extends serverSwitch {
10000);
deployThread(SwitchboardConstants.SEED_UPLOAD, "Seed-List Upload", "task that a principal peer performes to generate and upload a seed-list to a ftp account", null,
new InstantBusyThread(
- yc,
+ this.yc,
SwitchboardConstants.SEED_UPLOAD_METHOD_START,
SwitchboardConstants.SEED_UPLOAD_METHOD_JOBCOUNT,
SwitchboardConstants.SEED_UPLOAD_METHOD_FREEMEM,
@@ -736,7 +735,7 @@ public final class Switchboard extends serverSwitch {
180000);
deployThread(SwitchboardConstants.PEER_PING, "YaCy Core", "this is the p2p-control and peer-ping task", null,
new InstantBusyThread(
- yc,
+ this.yc,
SwitchboardConstants.PEER_PING_METHOD_START,
SwitchboardConstants.PEER_PING_METHOD_JOBCOUNT,
SwitchboardConstants.PEER_PING_METHOD_FREEMEM,
@@ -758,7 +757,7 @@ public final class Switchboard extends serverSwitch {
if (this.firstInit) {
setRemotecrawlPPM(Math.max(1, (int) getConfigLong("network.unit.remotecrawl.speed", 60)));
}
-
+
// test routine for snippet fetch
//Set query = new HashSet();
//query.add(CrawlSwitchboardEntry.word2hash("Weitergabe"));
@@ -768,30 +767,30 @@ public final class Switchboard extends serverSwitch {
//plasmaSnippetCache.result scr = snippetCache.retrieve(new URL("http://www.heise.de/kiosk/archiv/ct/2003/4/20"), query, true, 260);
this.trail = new LinkedBlockingQueue<String>();
-
- log.logConfig("Finished Switchboard Initialization");
+
+ this.log.logConfig("Finished Switchboard Initialization");
sb = this;
}
private void setDefaultSegments() {
- indexSegments.setSegment(Segments.Process.RECEIPTS, getConfig(SwitchboardConstants.SEGMENT_RECEIPTS, "default"));
- indexSegments.setSegment(Segments.Process.QUERIES, getConfig(SwitchboardConstants.SEGMENT_QUERIES, "default"));
- indexSegments.setSegment(Segments.Process.DHTIN, getConfig(SwitchboardConstants.SEGMENT_DHTIN, "default"));
- indexSegments.setSegment(Segments.Process.DHTOUT, getConfig(SwitchboardConstants.SEGMENT_DHTOUT, "default"));
- indexSegments.setSegment(Segments.Process.PROXY, getConfig(SwitchboardConstants.SEGMENT_PROXY, "default"));
- indexSegments.setSegment(Segments.Process.LOCALCRAWLING, getConfig(SwitchboardConstants.SEGMENT_LOCALCRAWLING, "default"));
- indexSegments.setSegment(Segments.Process.REMOTECRAWLING, getConfig(SwitchboardConstants.SEGMENT_REMOTECRAWLING, "default"));
- indexSegments.setSegment(Segments.Process.PUBLIC, getConfig(SwitchboardConstants.SEGMENT_PUBLIC, "default"));
- }
-
+ this.indexSegments.setSegment(Segments.Process.RECEIPTS, getConfig(SwitchboardConstants.SEGMENT_RECEIPTS, "default"));
+ this.indexSegments.setSegment(Segments.Process.QUERIES, getConfig(SwitchboardConstants.SEGMENT_QUERIES, "default"));
+ this.indexSegments.setSegment(Segments.Process.DHTIN, getConfig(SwitchboardConstants.SEGMENT_DHTIN, "default"));
+ this.indexSegments.setSegment(Segments.Process.DHTOUT, getConfig(SwitchboardConstants.SEGMENT_DHTOUT, "default"));
+ this.indexSegments.setSegment(Segments.Process.PROXY, getConfig(SwitchboardConstants.SEGMENT_PROXY, "default"));
+ this.indexSegments.setSegment(Segments.Process.LOCALCRAWLING, getConfig(SwitchboardConstants.SEGMENT_LOCALCRAWLING, "default"));
+ this.indexSegments.setSegment(Segments.Process.REMOTECRAWLING, getConfig(SwitchboardConstants.SEGMENT_REMOTECRAWLING, "default"));
+ this.indexSegments.setSegment(Segments.Process.PUBLIC, getConfig(SwitchboardConstants.SEGMENT_PUBLIC, "default"));
+ }
+
public int getIndexingProcessorsQueueSize() {
return
- this.indexingDocumentProcessor.queueSize() +
- this.indexingCondensementProcessor.queueSize() +
- this.indexingAnalysisProcessor.queueSize() +
+ this.indexingDocumentProcessor.queueSize() +
+ this.indexingCondensementProcessor.queueSize() +
+ this.indexingAnalysisProcessor.queueSize() +
this.indexingStorageProcessor.queueSize();
}
-
+
public void overwriteNetworkDefinition() throws FileNotFoundException, IOException {
// load network configuration into settings
@@ -802,10 +801,10 @@ public final class Switchboard extends serverSwitch {
networkUnitDefinition = "defaults/yacy.network.freeworld.unit";
setConfig("network.unit.definition", networkUnitDefinition);
}
-
+
// remove old release and bootstrap locations
- Iterator<String> ki = configKeys();
- ArrayList<String> d = new ArrayList<String>();
+ final Iterator<String> ki = configKeys();
+ final ArrayList<String> d = new ArrayList<String>();
String k;
while (ki.hasNext()) {
k = ki.next();
@@ -813,25 +812,25 @@ public final class Switchboard extends serverSwitch {
d.add(k);
}
}
- for (final String s : d) this.removeConfig(s); // must be removed afterwards otherwise a ki.remove() would not remove the property on file
-
+ for (final String s : d) removeConfig(s); // must be removed afterwards otherwise a ki.remove() would not remove the property on file
+
// include additional network definition properties into our settings
// note that these properties cannot be set in the application because they are
// _always_ overwritten each time with the default values. This is done so on purpose.
// the network definition should be made either consistent for all peers,
// or independently using a bootstrap URL
Map<String, String> initProps;
- Reader netDefReader = getConfigFileFromWebOrLocally(networkUnitDefinition, getAppPath().getAbsolutePath(), new File(workPath, "network.definition.backup"));
+ final Reader netDefReader = getConfigFileFromWebOrLocally(networkUnitDefinition, getAppPath().getAbsolutePath(), new File(this.workPath, "network.definition.backup"));
initProps = FileUtils.table(netDefReader);
setConfig(initProps);
-
+
// set release locations
int i = 0;
CryptoLib cryptoLib;
try {
cryptoLib = new CryptoLib();
while (true) {
- String location = getConfig("network.unit.update.location" + i, "");
+ final String location = getConfig("network.unit.update.location" + i, "");
if (location.isEmpty()) {
break;
}
@@ -850,25 +849,25 @@ public final class Switchboard extends serverSwitch {
final byte[] publicKeyBytes = Base64Order.standardCoder.decode(publicKeyString.trim());
publicKey = cryptoLib.getPublicKeyFromBytes(publicKeyBytes);
}
- } catch (InvalidKeySpecException e) {
+ } catch (final InvalidKeySpecException e) {
Log.logException(e);
}
- yacyUpdateLocation updateLocation = new yacyUpdateLocation(locationURL, publicKey);
+ final yacyUpdateLocation updateLocation = new yacyUpdateLocation(locationURL, publicKey);
yacyRelease.latestReleaseLocations.add(updateLocation);
i++;
}
- } catch (NoSuchAlgorithmException e1) {
+ } catch (final NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
Log.logException(e1);
}
-
+
// initiate url license object
- licensedURLs = new URLLicense(8);
-
+ this.licensedURLs = new URLLicense(8);
+
// set white/blacklists
this.networkWhitelist = Domains.makePatterns(getConfig(SwitchboardConstants.NETWORK_WHITELIST, ""));
this.networkBlacklist = Domains.makePatterns(getConfig(SwitchboardConstants.NETWORK_BLACKLIST, ""));
-
+
/*
// in intranet and portal network set robinson mode
if (networkUnitDefinition.equals("defaults/yacy.network.webportal.unit") ||
@@ -878,7 +877,7 @@ public final class Switchboard extends serverSwitch {
setConfig(plasmaSwitchboardConstants.INDEX_DIST_ALLOW, false);
setConfig(plasmaSwitchboardConstants.INDEX_RECEIVE_ALLOW, false);
}
-
+
// in freeworld network set full p2p mode
if (networkUnitDefinition.equals("defaults/yacy.network.freeworld.unit")) {
// switch to robinson mode
@@ -889,12 +888,12 @@ public final class Switchboard extends serverSwitch {
*/
// write the YaCy network identification inside the yacybot client user agent to distinguish networks
String newagent = ClientIdentification.generateYaCyBot(getConfig(SwitchboardConstants.NETWORK_NAME, "") + (isRobinsonMode() ? "-" : "/") + getConfig(SwitchboardConstants.NETWORK_DOMAIN, "global"));
- if (!this.getConfigBool("network.unit.dht", false) && this.getConfig("network.unit.tenant.agent", "").length() > 0) newagent = this.getConfig("network.unit.tenant.agent", "");
+ if (!getConfigBool("network.unit.dht", false) && getConfig("network.unit.tenant.agent", "").length() > 0) newagent = getConfig("network.unit.tenant.agent", "");
ClientIdentification.setUserAgent(newagent);
}
-
+
public void switchNetwork(final String networkDefinition) throws FileNotFoundException, IOException {
- log.logInfo("SWITCH NETWORK: switching to '" + networkDefinition + "'");
+ this.log.logInfo("SWITCH NETWORK: switching to '" + networkDefinition + "'");
// pause crawls
final boolean lcp = crawlJobIsPaused(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL);
if (!lcp) {
@@ -905,14 +904,14 @@ public final class Switchboard extends serverSwitch {
pauseCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
}
// trigger online caution
- proxyLastAccess = System.currentTimeMillis() + 3000; // at least 3 seconds online caution to prevent unnecessary action on database meanwhile
- log.logInfo("SWITCH NETWORK: SHUT DOWN OF OLD INDEX DATABASE...");
+ this.proxyLastAccess = System.currentTimeMillis() + 3000; // at least 3 seconds online caution to prevent unnecessary action on database meanwhile
+ this.log.logInfo("SWITCH NETWORK: SHUT DOWN OF OLD INDEX DATABASE...");
// clean search events which have cached relations to the old index
SearchEventCache.cleanupEvents(true);
-
+
// switch the networks
synchronized (this) {
-
+
// shut down
this.crawler.close();
if (this.dhtDispatcher != null) this.dhtDispatcher.close();
@@ -922,9 +921,9 @@ public final class Switchboard extends serverSwitch {
this.crawlStacker.announceClose();
this.crawlStacker.close();
this.webStructure.close();
-
- log.logInfo("SWITCH NETWORK: START UP OF NEW INDEX DATABASE...");
-
+
+ this.log.logInfo("SWITCH NETWORK: START UP OF NEW INDEX DATABASE...");
+
// new properties
setConfig("network.unit.definition", networkDefinition);
overwriteNetworkDefinition();
@@ -941,62 +940,62 @@ public final class Switchboard extends serverSwitch {
// clear statistic data
ResultURLs.clearStacks();
-
+
// remove heuristics
setConfig("heuristic.site", false);
setConfig("heuristic.scroogle", false);
setConfig("heuristic.blekko", false);
-
+
// relocate
this.crawlQueues.relocate(this.queuesRoot); // cannot be closed because the busy threads are working with that object
- peers.relocate(
+ this.peers.relocate(
this.networkRoot,
redundancy,
partitionExponent,
this.useTailCache,
this.exceed134217727);
- indexSegments = new Segments(
- log,
+ this.indexSegments = new Segments(
+ this.log,
new File(new File(indexPrimaryPath, networkName), "SEGMENTS"),
wordCacheMaxCount,
fileSizeMax,
this.useTailCache,
-
+
this.exceed134217727);
// set the default segment names
setDefaultSegments();
-
+
// create a crawler
- crawler = new CrawlSwitchboard(
+ this.crawler = new CrawlSwitchboard(
networkName,
- log,
+ this.log,
this.queuesRoot);
-
+
// init a DHT transmission dispatcher
- dhtDispatcher = (peers.sizeConnected() == 0) ? null : new Dispatcher(
- indexSegments.segment(Segments.Process.LOCALCRAWLING),
- peers,
- true,
+ this.dhtDispatcher = (this.peers.sizeConnected() == 0) ? null : new Dispatcher(
+ this.indexSegments.segment(Segments.Process.LOCALCRAWLING),
+ this.peers,
+ true,
10000);
// create new web structure
- this.webStructure = new WebStructureGraph(new File(queuesRoot, "webStructure.map"));
-
-
+ this.webStructure = new WebStructureGraph(new File(this.queuesRoot, "webStructure.map"));
+
+
// load domainList
try {
this.domainList = null;
if(!getConfig("network.unit.domainlist", "").equals("")) {
- Reader r = getConfigFileFromWebOrLocally(getConfig("network.unit.domainlist", ""), getAppPath().getAbsolutePath(), new File(this.networkRoot, "domainlist.txt"));
+ final Reader r = getConfigFileFromWebOrLocally(getConfig("network.unit.domainlist", ""), getAppPath().getAbsolutePath(), new File(this.networkRoot, "domainlist.txt"));
this.domainList = new FilterEngine();
this.domainList.loadList(new BufferedReader(r), null);
}
- } catch (FileNotFoundException e) {
- log.logSevere("CONFIG: domainlist not found: " + e.getMessage());
- } catch (IOException e) {
- log.logSevere("CONFIG: error while retrieving domainlist: " + e.getMessage());
+ } catch (final FileNotFoundException e) {
+ this.log.logSevere("CONFIG: domainlist not found: " + e.getMessage());
+ } catch (final IOException e) {
+ this.log.logSevere("CONFIG: error while retrieving domainlist: " + e.getMessage());
}
-
+
this.crawlStacker = new CrawlStacker(
this.crawlQueues,
this.crawler,
@@ -1007,27 +1006,27 @@ public final class Switchboard extends serverSwitch {
this.domainList);
}
- Domains.setNoLocalCheck(this.isAllIPMode()); // possibly switch off localIP check
-
+ Domains.setNoLocalCheck(isAllIPMode()); // possibly switch off localIP check
+
// start up crawl jobs
continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL);
continueCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
- log.logInfo("SWITCH NETWORK: FINISHED START UP, new network is now '" + networkDefinition + "'.");
-
+ this.log.logInfo("SWITCH NETWORK: FINISHED START UP, new network is now '" + networkDefinition + "'.");
+
// set the network-specific remote crawl ppm
setRemotecrawlPPM(Math.max(1, (int) getConfigLong("network.unit.remotecrawl.speed", 60)));
}
-
+
public void setRemotecrawlPPM(final int ppm) {
final long newBusySleep = Math.max(100, 60000 / ppm);
-
+
// propagate to crawler
final BusyThread rct = getThread(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
setConfig(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, newBusySleep);
setConfig(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_IDLESLEEP, Math.min(10000, newBusySleep * 10));
rct.setBusySleep(getConfigLong(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, 1000));
rct.setIdleSleep(getConfigLong(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_IDLESLEEP, 10000));
-
+
// propagate to loader
final BusyThread rcl = getThread(SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER);
setConfig(SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_BUSYSLEEP, newBusySleep * 4);
@@ -1035,51 +1034,51 @@ public final class Switchboard extends serverSwitch {
rcl.setBusySleep(getConfigLong(SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_BUSYSLEEP, 1000));
rcl.setIdleSleep(getConfigLong(SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_IDLESLEEP, 10000));
}
-
+
public void initMessages() throws IOException {
this.log.logConfig("Starting Message Board");
- final File messageDbFile = new File(workPath, "message.heap");
+ final File messageDbFile = new File(this.workPath, "message.heap");
this.messageDB = new MessageBoard(messageDbFile);
this.log.logConfig("Loaded Message Board DB from file " + messageDbFile.getName() +
", " + this.messageDB.size() + " entries" +
", " + ppRamString(messageDbFile.length()/1024));
}
-
+
public void initWiki() throws IOException {
this.log.logConfig("Starting Wiki Board");
- final File wikiDbFile = new File(workPath, "wiki.heap");
- this.wikiDB = new WikiBoard(wikiDbFile, new File(workPath, "wiki-bkp.heap"));
+ final File wikiDbFile = new File(this.workPath, "wiki.heap");
+ this.wikiDB = new WikiBoard(wikiDbFile, new File(this.workPath, "wiki-bkp.heap"));
this.log.logConfig("Loaded Wiki Board DB from file " + wikiDbFile.getName() +
", " + this.wikiDB.size() + " entries" +
", " + ppRamString(wikiDbFile.length()/1024));
}
-
+
public void initBlog() throws IOException {
this.log.logConfig("Starting Blog");
- final File blogDbFile = new File(workPath, "blog.heap");
+ final File blogDbFile = new File(this.workPath, "blog.heap");
this.blogDB = new BlogBoard(blogDbFile);
this.log.logConfig("Loaded Blog DB from file " + blogDbFile.getName() +
", " + this.blogDB.size() + " entries" +
", " + ppRamString(blogDbFile.length()/1024));
- final File blogCommentDbFile = new File(workPath, "blogComment.heap");
+ final File blogCommentDbFile = new File(this.workPath, "blogComment.heap");
this.blogCommentDB = new BlogBoardComments(blogCommentDbFile);
this.log.logConfig("Loaded Blog-Comment DB from file " + blogCommentDbFile.getName() +
", " + this.blogCommentDB.size() + " entries" +
", " + ppRamString(blogCommentDbFile.length()/1024));
}
-
+
public void initBookmarks() throws IOException{
this.log.logConfig("Loading Bookmarks DB");
- final File bookmarksFile = new File(workPath, "bookmarks.heap");
- final File tagsFile = new File(workPath, "bookmarkTags.heap");
- final File datesFile = new File(workPath, "bookmarkDates.heap");
+ final File bookmarksFile = new File(this.workPath, "bookmarks.heap");
+ final File tagsFile = new File(this.workPath, "bookmarkTags.heap");
+ final File datesFile = new File(this.workPath, "bookmarkDates.heap");
tagsFile.delete();
this.bookmarksDB = new BookmarksDB(bookmarksFile, datesFile);
this.log.logConfig("Loaded Bookmarks DB from files "+ bookmarksFile.getName()+ ", "+tagsFile.getName());
this.log.logConfig(this.bookmarksDB.tagsSize()+" Tag, "+this.bookmarksDB.bookmarksSize()+" Bookmarks");
}
-
+
public static Switchboard getSwitchboard(){
return sb;
}
@@ -1087,15 +1086,15 @@ public final class Switchboard extends serverSwitch {
public boolean isIntranetMode() {
return "local.any".indexOf(getConfig(SwitchboardConstants.NETWORK_DOMAIN, "global")) >= 0;
}
-
+
public boolean isGlobalMode() {
return "global.any".indexOf(getConfig(SwitchboardConstants.NETWORK_DOMAIN, "global")) >= 0;
- }
-
+ }
+
public boolean isAllIPMode() {
return "any".indexOf(getConfig(SwitchboardConstants.NETWORK_DOMAIN, "global")) >= 0;
}
-
+
/**
* in nocheck mode the isLocal property is not checked to omit DNS lookup. Can only be done in allip mode
* @return
@@ -1103,7 +1102,7 @@ public final class Switchboard extends serverSwitch {
public boolean isIPNoCheckMode() {
return isAllIPMode() && getConfigBool(SwitchboardConstants.NETWORK_DOMAIN_NOCHECK, false);
}
-
+
public boolean isRobinsonMode() {
// we are in robinson mode, if we do not exchange index by dht distribution
// we need to take care that search requests and remote indexing requests go only
@@ -1117,7 +1116,7 @@ public final class Switchboard extends serverSwitch {
final String clustermode = getConfig(SwitchboardConstants.CLUSTER_MODE, SwitchboardConstants.CLUSTER_MODE_PUBLIC_PEER);
return (clustermode.equals(SwitchboardConstants.CLUSTER_MODE_PUBLIC_CLUSTER)) || (clustermode.equals(SwitchboardConstants.CLUSTER_MODE_PUBLIC_PEER));
}
-
+
public boolean isInMyCluster(final String peer) {
// check if the given peer is in the own network, if this is a robinson cluster
// depending on the robinson cluster type, the peer String may be a peerhash (b64-hash)
@@ -1137,7 +1136,7 @@ public final class Switchboard extends serverSwitch {
return false;
}
}
-
+
public boolean isInMyCluster(final yacySeed seed) {
// check if the given peer is in the own network, if this is a robinson cluster
// if this robinson mode does not define a cluster membership, false is returned
@@ -1160,34 +1159,34 @@ public final class Switchboard extends serverSwitch {
// tests if hash occurrs in any database
// if it exists, the name of the database is returned,
// if it not exists, null is returned
- if (indexSegments.urlMetadata(process).exists(hash)) return "loaded";
+ if (this.indexSegments.urlMetadata(process).exists(hash)) return "loaded";
return this.crawlQueues.urlExists(hash);
}
-
+
public void urlRemove(final Segment segment, final byte[] hash) {
segment.urlMetadata().remove(hash);
ResultURLs.remove(ASCII.String(hash));
- crawlQueues.urlRemove(hash);
+ this.crawlQueues.urlRemove(hash);
}
-
+
public DigestURI getURL(final Segments.Process process, final byte[] urlhash) {
if (urlhash == null) return null;
if (urlhash.length == 0) return null;
- final URIMetadataRow le = indexSegments.urlMetadata(process).load(urlhash);
+ final URIMetadataRow le = this.indexSegments.urlMetadata(process).load(urlhash);
if (le != null) {
- Components metadata = le.metadata();
+ final Components metadata = le.metadata();
if (metadata == null) return null;
return metadata.url();
}
- return crawlQueues.getURL(urlhash);
+ return this.crawlQueues.getURL(urlhash);
}
-
+
public RankingProfile getRanking() {
return (getConfig("rankingProfile", "").length() == 0) ?
new RankingProfile(ContentDomain.TEXT) :
new RankingProfile("", crypt.simpleDecode(sb.getConfig("rankingProfile", ""), null));
}
-
+
/**
* checks if the proxy, the local search or remote search was accessed some time before
* If no limit is exceeded, null is returned. If a limit is exceeded,
@@ -1243,62 +1242,62 @@ public final class Switchboard extends serverSwitch {
*/
public boolean cleanProfiles() throws InterruptedException {
if (getIndexingProcessorsQueueSize() > 0 ||
- crawlQueues.workerSize() > 0 ||
- crawlQueues.coreCrawlJobSize() > 0 ||
- crawlQueues.limitCrawlJobSize() > 0 ||
- crawlQueues.remoteTriggeredCrawlJobSize() > 0 ||
- (crawlStacker != null && !crawlStacker.isEmpty()) ||
- crawlQueues.noticeURL.notEmpty())
+ this.crawlQueues.workerSize() > 0 ||
+ this.crawlQueues.coreCrawlJobSize() > 0 ||
+ this.crawlQueues.limitCrawlJobSize() > 0 ||
+ this.crawlQueues.remoteTriggeredCrawlJobSize() > 0 ||
+ (this.crawlStacker != null && !this.crawlStacker.isEmpty()) ||
+ this.crawlQueues.noticeURL.notEmpty())
return false;
return this.crawler.cleanProfiles();
}
-
+
public void close() {
- log.logConfig("SWITCHBOARD SHUTDOWN STEP 1: sending termination signal to managed threads:");
+ this.log.logConfig("SWITCHBOARD SHUTDOWN STEP 1: sending termination signal to managed threads:");
MemoryTracker.stopSystemProfiling();
terminateAllThreads(true);
net.yacy.gui.framework.Switchboard.shutdown();
- log.logConfig("SWITCHBOARD SHUTDOWN STEP 2: sending termination signal to threaded indexing");
+ this.log.logConfig("SWITCHBOARD SHUTDOWN STEP 2: sending termination signal to threaded indexing");
// closing all still running db importer jobs
- indexingDocumentProcessor.announceShutdown();
- indexingDocumentProcessor.awaitShutdown(12000);
- crawlStacker.announceClose();
- indexingCondensementProcessor.announceShutdown();
- indexingAnalysisProcessor.announceShutdown();
- indexingStorageProcessor.announceShutdown();
- if (dhtDispatcher != null) dhtDispatcher.close();
- indexingCondensementProcessor.awaitShutdown(12000);
- indexingAnalysisProcessor.awaitShutdown(12000);
- indexingStorageProcessor.awaitShutdown(12000);
- crawlStacker.close();
+ this.indexingDocumentProcessor.announceShutdown();
+ this.indexingDocumentProcessor.awaitShutdown(12000);
+ this.crawlStacker.announceClose();
+ this.indexingCondensementProcessor.announceShutdown();
+ this.indexingAnalysisProcessor.announceShutdown();
+ this.indexingStorageProcessor.announceShutdown();
+ if (this.dhtDispatcher != null) this.dhtDispatcher.close();
+ this.indexingCondensementProcessor.awaitShutdown(12000);
+ this.indexingAnalysisProcessor.awaitShutdown(12000);
+ this.indexingStorageProcessor.awaitShutdown(12000);
+ this.crawlStacker.close();
// de.anomic.http.client.Client.closeAllConnections();
- wikiDB.close();
- blogDB.close();
- blogCommentDB.close();
- userDB.close();
- if (bookmarksDB != null) bookmarksDB.close(); // may null if concurrent initialization was not finished
- messageDB.close();
- webStructure.close();
- crawlQueues.close();
- crawler.close();
- log.logConfig("SWITCHBOARD SHUTDOWN STEP 3: sending termination signal to database manager (stand by...)");
- indexSegments.close();
- peers.close();
+ this.wikiDB.close();
+ this.blogDB.close();
+ this.blogCommentDB.close();
+ this.userDB.close();
+ if (this.bookmarksDB != null) this.bookmarksDB.close(); // may null if concurrent initialization was not finished
+ this.messageDB.close();
+ this.webStructure.close();
+ this.crawlQueues.close();
+ this.crawler.close();
+ this.log.logConfig("SWITCHBOARD SHUTDOWN STEP 3: sending termination signal to database manager (stand by...)");
+ this.indexSegments.close();
+ this.peers.close();
Cache.close();
- tables.close();
+ this.tables.close();
Domains.close();
- if (solrConnector != null && this.getConfigBool("federated.service.solr.indexing.enabled", false)) solrConnector.close();
+ if (this.solrConnector != null && getConfigBool("federated.service.solr.indexing.enabled", false)) this.solrConnector.close();
AccessTracker.dumpLog(new File("DATA/LOG/queries.log"));
UPnP.deletePortMapping();
Tray.removeTray();
try {
HTTPClient.closeConnectionManager();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
Log.logException(e);
}
- log.logConfig("SWITCHBOARD SHUTDOWN TERMINATED");
+ this.log.logConfig("SWITCHBOARD SHUTDOWN TERMINATED");
}
-
+
/**
* pass a response to the indexer
* @param response
@@ -1306,22 +1305,22 @@ public final class Switchboard extends serverSwitch {
*/
public String toIndexer(final Response response) {
assert response != null;
-
+
// get next queue entry and start a queue processing
if (response == null) {
if (this.log.isFine()) {
- log.logFine("deQueue: queue entry is null");
+ this.log.logFine("deQueue: queue entry is null");
}
return "queue entry is null";
}
if (response.profile() == null) {
- if (this.log.isFine()) log.logFine("deQueue: profile is null");
+ if (this.log.isFine()) this.log.logFine("deQueue: profile is null");
return "profile is null";
}
-
+
// check if the document should be indexed based on proxy/crawler rules
String noIndexReason = "unspecified indexing error";
- if (response.processCase(peers.mySeed().hash) == EventOrigin.PROXY_LOAD) {
+ if (response.processCase(this.peers.mySeed().hash) == EventOrigin.PROXY_LOAD) {
// proxy-load
noIndexReason = response.shallIndexCacheForProxy();
} else {
@@ -1340,12 +1339,12 @@ public final class Switchboard extends serverSwitch {
if (noIndexReason == null && response.requestProhibitsIndexing()) {
noIndexReason = "X-YACY-Index-Control header prohibits indexing";
}
-
+
// check accepted domain / localhost accesses
if (noIndexReason == null) {
- noIndexReason = crawlStacker.urlInAcceptedDomain(response.url());
+ noIndexReason = this.crawlStacker.urlInAcceptedDomain(response.url());
}
-
+
// in the noIndexReason is set, indexing is not allowed
if (noIndexReason != null) {
// log cause and close queue
@@ -1357,34 +1356,34 @@ public final class Switchboard extends serverSwitch {
}
// put document into the concurrent processing queue
- if (log.isFinest()) {
- log.logFinest("deQueue: passing to indexing queue: " + response.url().toNormalform(true, false));
+ if (this.log.isFinest()) {
+ this.log.logFinest("deQueue: passing to indexing queue: " + response.url().toNormalform(true, false));
}
try {
this.indexingDocumentProcessor.enQueue(new indexingQueueEntry(Segments.Process.LOCALCRAWLING, response, null, null));
return null;
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
Log.logException(e);
return "interrupted: " + e.getMessage();
}
}
-
+
public boolean processSurrogate(final String s) {
- File infile = new File(this.surrogatesInPath, s);
+ final File infile = new File(this.surrogatesInPath, s);
if (!infile.exists() || !infile.canWrite() || !infile.canRead()) return false;
- File outfile = new File(this.surrogatesOutPath, s);
+ final File outfile = new File(this.surrogatesOutPath, s);
//if (outfile.exists()) return false;
boolean moved = false;
if (s.endsWith("xml.zip")) {
// open the zip file with all the xml files in it
try {
- InputStream is = new BufferedInputStream(new FileInputStream(infile));
- ZipInputStream zis = new ZipInputStream(is);
+ final InputStream is = new BufferedInputStream(new FileInputStream(infile));
+ final ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
int size;
- byte[] buffer = new byte[2048];
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final byte[] buffer = new byte[2048];
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, size);
}
@@ -1392,7 +1391,7 @@ public final class Switchboard extends serverSwitch {
processSurrogate(new ByteArrayInputStream(baos.toByteArray()), entry.getName());
baos.close();
}
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
} finally {
moved = infile.renameTo(outfile);
@@ -1405,25 +1404,25 @@ public final class Switchboard extends serverSwitch {
is = new GZIPInputStream(is);
}
processSurrogate(is, infile.getName());
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
} finally {
moved = infile.renameTo(outfile);
if (moved) {
// check if this file is already compressed, if not, compress now
if (!outfile.getName().endsWith(".gz")) {
- String gzname = outfile.getName() + ".gz";
- File gzfile = new File(outfile.getParentFile(), gzname);
+ final String gzname = outfile.getName() + ".gz";
+ final File gzfile = new File(outfile.getParentFile(), gzname);
try {
- OutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(gzfile)));
+ final OutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(gzfile)));
FileUtils.copy(new BufferedInputStream(new FileInputStream(outfile)), os);
os.close();
if (gzfile.exists()) {
FileUtils.deletedelete(outfile);
}
- } catch (FileNotFoundException e) {
+ } catch (final FileNotFoundException e) {
Log.logException(e);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
@@ -1432,44 +1431,44 @@ public final class Switchboard extends serverSwitch {
return moved;
}
}
-
- public void processSurrogate(final InputStream is, String name) throws IOException {
- SurrogateReader reader = new SurrogateReader(is, 100);
- Thread readerThread = new Thread(reader, name);
+
+ public void processSurrogate(final InputStream is, final String name) throws IOException {
+ final SurrogateReader reader = new SurrogateReader(is, 100);
+ final Thread readerThread = new Thread(reader, name);
readerThread.start();
DCEntry surrogate;
Response response;
while ((surrogate = reader.take()) != DCEntry.poison) {
// check if url is in accepted domain
assert surrogate != null;
- assert crawlStacker != null;
- final String urlRejectReason = crawlStacker.urlInAcceptedDomain(surrogate.getIdentifier(true));
+ assert this.crawlStacker != null;
+ final String urlRejectReason = this.crawlStacker.urlInAcceptedDomain(surrogate.getIdentifier(true));
if (urlRejectReason != null) {
this.log.logWarning("Rejected URL '" + surrogate.getIdentifier(true) + "': " + urlRejectReason);
continue;
}
-
+
// create a queue entry
- Document document = surrogate.document();
- Request request = new Request(
- ASCII.getBytes(peers.mySeed().hash),
- surrogate.getIdentifier(true),
- null,
- "",
+ final Document document = surrogate.document();
+ final Request request = new Request(
+ ASCII.getBytes(this.peers.mySeed().hash),
+ surrogate.getIdentifier(true),
+ null,
+ "",
surrogate.getDate(),
this.crawler.defaultSurrogateProfile.handle(),
- 0,
- 0,
+ 0,
+ 0,
0,
0
);
response = new Response(request, null, null, "200", this.crawler.defaultSurrogateProfile);
- indexingQueueEntry queueEntry = new indexingQueueEntry(Segments.Process.SURROGATES, response, new Document[]{document}, null);
-
+ final indexingQueueEntry queueEntry = new indexingQueueEntry(Segments.Process.SURROGATES, response, new Document[]{document}, null);
+
// place the queue entry into the concurrent process of the condenser (document analysis)
try {
- indexingCondensementProcessor.enQueue(queueEntry);
- } catch (InterruptedException e) {
+ this.indexingCondensementProcessor.enQueue(queueEntry);
+ } catch (final InterruptedException e) {
Log.logException(e);
break;
}
@@ -1478,7 +1477,7 @@ public final class Switchboard extends serverSwitch {
public int surrogateQueueSize() {
// count surrogates
- String[] surrogatelist = this.surrogatesInPath.list();
+ final String[] surrogatelist = this.surrogatesInPath.list();
if (surrogatelist.length > 100) return 100;
int count = 0;
for (final String s: surrogatelist) {
@@ -1491,29 +1490,29 @@ public final class Switchboard extends serverSwitch {
}
return count;
}
-
+
public void surrogateFreeMem() {
// do nothing
}
-
+
public boolean surrogateProcess() {
// work off fresh entries from the proxy or from the crawler
- String cautionCause = onlineCaution();
+ final String cautionCause = onlineCaution();
if (cautionCause != null) {
if (this.log.isFine()) {
- log.logFine("deQueue: online caution for " + cautionCause
+ this.log.logFine("deQueue: online caution for " + cautionCause
+ ", omitting resource stack processing");
}
return false;
}
-
+
try {
// check surrogates
final String[] surrogatelist = this.surrogatesInPath.list();
if (surrogatelist.length > 0) {
// look if the is any xml inside
for (final String surrogate: surrogatelist) {
-
+
// check for interruption
checkInterruption();
@@ -1524,12 +1523,12 @@ public final class Switchboard extends serverSwitch {
}
}
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
return false;
}
return false;
}
-
+
public static class indexingQueueEntry extends WorkflowJob {
public Segments.Process process;
public Response queueEntry;
@@ -1547,17 +1546,17 @@ public final class Switchboard extends serverSwitch {
this.condenser = condenser;
}
}
-
+
public int cleanupJobSize() {
int c = 0;
- if ((crawlQueues.delegatedURL.stackSize() > 1000)) c++;
- if ((crawlQueues.errorURL.stackSize() > 1000)) c++;
+ if ((this.crawlQueues.delegatedURL.stackSize() > 1000)) c++;
+ if ((this.crawlQueues.errorURL.stackSize() > 1000)) c++;
for (final EventOrigin origin: EventOrigin.values()) {
if (ResultURLs.getStackSize(origin) > 1000) c++;
}
return c;
}
-
+
public boolean cleanupJob() {
try {
// clear caches if necessary
@@ -1566,22 +1565,22 @@ public final class Switchboard extends serverSwitch {
SearchEventCache.cleanupEvents(true);
this.trail.clear();
}
-
+
// set a random password if no password is configured
if (getConfigBool("adminAccountForLocalhost", false) && getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "").length() == 0) {
// make a 'random' password
setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "0000" + this.genRandomPassword());
setConfig("adminAccount", "");
}
-
+
// refresh recrawl dates
try{
CrawlProfile selentry;
- for (final byte[] handle: crawler.getActive()) {
- selentry = crawler.getActive(handle);
+ for (final byte[] handle: this.crawler.getActive()) {
+ selentry = this.crawler.getActive(handle);
assert selentry.handle() != null : "profile.name = " + selentry.name();
if (selentry.handle() == null) {
- crawler.removeActive(handle);
+ this.crawler.removeActive(handle);
continue;
}
boolean insert = false;
@@ -1615,12 +1614,12 @@ public final class Switchboard extends serverSwitch {
Long.toString(CrawlProfile.getRecrawlDate(CrawlSwitchboard.CRAWL_PROFILE_SURROGATE_RECRAWL_CYCLE)));
insert = true;
}
- if (insert) crawler.putActive(UTF8.getBytes(selentry.handle()), selentry);
+ if (insert) this.crawler.putActive(UTF8.getBytes(selentry.handle()), selentry);
}
} catch (final Exception e) {
Log.logException(e);
}
-
+
// execute scheduled API actions
Tables.Row row;
final List<String> pks = new ArrayList<String>();
@@ -1631,76 +1630,76 @@ public final class Switchboard extends serverSwitch {
while (mapIterator.hasNext()) {
row = mapIterator.next();
if (row == null) continue;
- Date date_next_exec = row.get(WorkTables.TABLE_API_COL_DATE_NEXT_EXEC, (Date) null);
+ final Date date_next_exec = row.get(WorkTables.TABLE_API_COL_DATE_NEXT_EXEC, (Date) null);
if (date_next_exec == null) continue;
if (date_next_exec.after(now)) continue;
- pks.add(UTF8.String(row.getPK()));
+ pks.add(UTF8.String(row.getPK()));
}
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
for (final String pk: pks) try {
row = this.tables.select(WorkTables.TABLE_API_NAME, UTF8.getBytes(pk));
- WorkTables.calculateAPIScheduler(row, true); // calculate next update time
+ WorkTables.calculateAPIScheduler(row, true); // calculate next update time
this.tables.update(WorkTables.TABLE_API_NAME, row);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
continue;
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
continue;
}
- final Map<String, Integer> callResult = this.tables.execAPICalls("localhost", (int) this.getConfigLong("port", 8090), this.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, ""), pks);
+ final Map<String, Integer> callResult = this.tables.execAPICalls("localhost", (int) getConfigLong("port", 8090), getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, ""), pks);
for (final Map.Entry<String, Integer> call: callResult.entrySet()) {
- log.logInfo("Scheduler executed api call, response " + call.getValue() + ": " + call.getKey());
+ this.log.logInfo("Scheduler executed api call, response " + call.getValue() + ": " + call.getKey());
}
-
+
// close unused connections
ConnectionInfo.cleanUp();
-
+
// clean up delegated stack
checkInterruption();
- if ((crawlQueues.delegatedURL.stackSize() > 1000)) {
+ if ((this.crawlQueues.delegatedURL.stackSize() > 1000)) {
if (this.log.isFine()) {
- log.logFine("Cleaning Delegated-URLs report stack, " + crawlQueues.delegatedURL.stackSize() + " entries on stack");
+ this.log.logFine("Cleaning Delegated-URLs report stack, " + this.crawlQueues.delegatedURL.stackSize() + " entries on stack");
}
- crawlQueues.delegatedURL.clearStack();
+ this.crawlQueues.delegatedURL.clearStack();
}
-
+
// clean up error stack
checkInterruption();
- if ((crawlQueues.errorURL.stackSize() > 1000)) {
+ if ((this.crawlQueues.errorURL.stackSize() > 1000)) {
if (this.log.isFine()) {
- log.logFine("Cleaning Error-URLs report stack, " + crawlQueues.errorURL.stackSize() + " entries on stack");
+ this.log.logFine("Cleaning Error-URLs report stack, " + this.crawlQueues.errorURL.stackSize() + " entries on stack");
}
- crawlQueues.errorURL.clearStack();
+ this.crawlQueues.errorURL.clearStack();
}
-
+
// clean up loadedURL stack
for (final EventOrigin origin: EventOrigin.values()) {
checkInterruption();
if (ResultURLs.getStackSize(origin) > 1000) {
if (this.log.isFine()) {
- log.logFine("Cleaning Loaded-URLs report stack, " + ResultURLs.getStackSize(origin) + " entries on stack " + origin.getCode());
+ this.log.logFine("Cleaning Loaded-URLs report stack, " + ResultURLs.getStackSize(origin) + " entries on stack " + origin.getCode());
}
ResultURLs.clearStack(origin);
}
}
-
+
// clean up image stack
ResultImages.clearQueues();
-
+
// clean up profiles
checkInterruption();
cleanProfiles();
// clean up news
checkInterruption();
- try {
+ try {
if (this.log.isFine()) {
- log.logFine("Cleaning Incoming News, " + this.peers.newsPool.size(yacyNewsPool.INCOMING_DB) + " entries on stack");
+ this.log.logFine("Cleaning Incoming News, " + this.peers.newsPool.size(yacyNewsPool.INCOMING_DB) + " entries on stack");
}
- this.peers.newsPool.automaticProcess(peers);
+ this.peers.newsPool.automaticProcess(this.peers);
} catch (final Exception e) {
Log.logException(e);
}
@@ -1710,7 +1709,7 @@ public final class Switchboard extends serverSwitch {
if (getConfigBool("cleanup.deletionPublishedNews", true)) {
this.peers.newsPool.clear(yacyNewsPool.PUBLISHED_DB);
}
-
+
// clean up seed-dbs
if (getConfigBool("routing.deleteOldSeeds.permission",true)) {
final long deleteOldSeedsTime = getConfigLong("routing.deleteOldSeeds.time",7)*24*3600000;
@@ -1742,28 +1741,28 @@ public final class Switchboard extends serverSwitch {
}
for (int i = 0; i < deleteQueue.size(); ++i) this.peers.removePotential(deleteQueue.get(i));
}
-
+
// check if update is available and
// if auto-update is activated perform an automatic installation and restart
final yacyRelease updateVersion = yacyRelease.rulebasedUpdateInfo(false);
if (updateVersion != null) {
// there is a version that is more recent. Load it and re-start with it
- log.logInfo("AUTO-UPDATE: downloading more recent release " + updateVersion.getUrl());
+ this.log.logInfo("AUTO-UPDATE: downloading more recent release " + updateVersion.getUrl());
final File downloaded = updateVersion.downloadRelease();
final boolean devenvironment = new File(this.getAppPath(), ".svn").exists();
if (devenvironment) {
- log.logInfo("AUTO-UPDATE: omitting update because this is a development environment");
+ this.log.logInfo("AUTO-UPDATE: omitting update because this is a development environment");
} else if ((downloaded == null) || (!downloaded.exists()) || (downloaded.length() == 0)) {
- log.logInfo("AUTO-UPDATE: omitting update because download failed (file cannot be found, is too small or signature is bad)");
+ this.log.logInfo("AUTO-UPDATE: omitting update because download failed (file cannot be found, is too small or signature is bad)");
} else {
yacyRelease.deployRelease(downloaded);
terminate(10, "auto-update to install " + downloaded.getName());
- log.logInfo("AUTO-UPDATE: deploy and restart initiated");
+ this.log.logInfo("AUTO-UPDATE: deploy and restart initiated");
}
}
-
+
// initiate broadcast about peer startup to spread supporter url
- if (!this.isRobinsonMode() && this.peers.newsPool.size(yacyNewsPool.OUTGOING_DB) == 0) {
+ if (!isRobinsonMode() && this.peers.newsPool.size(yacyNewsPool.OUTGOING_DB) == 0) {
// read profile
final Properties profile = new Properties();
FileInputStream fileIn = null;
@@ -1782,36 +1781,36 @@ public final class Switchboard extends serverSwitch {
if ((homepage != null) && (homepage.length() > 10)) {
final Properties news = new Properties();
news.put("homepage", profile.get("homepage"));
- this.peers.newsPool.publishMyNews(peers.mySeed(), yacyNewsPool.CATEGORY_PROFILE_BROADCAST, news);
+ this.peers.newsPool.publishMyNews(this.peers.mySeed(), yacyNewsPool.CATEGORY_PROFILE_BROADCAST, news);
}
}
-
+
// update the cluster set
this.clusterhashes = this.peers.clusterHashes(getConfig("cluster.peers.yacydomain", ""));
-
+
// check if we are reachable and try to map port again if not (e.g. when router rebooted)
if (getConfigBool(SwitchboardConstants.UPNP_ENABLED, false) && sb.peers.mySeed().isJunior()) {
UPnP.addPortMapping();
}
-
+
// after all clean up is done, check the resource usage
- observer.resourceObserverJob();
-
+ this.observer.resourceObserverJob();
+
// cleanup cached search failures
- if (getConfigBool(SwitchboardConstants.NETWORK_SEARCHVERIFY, false) && peers.mySeed().getFlagAcceptRemoteIndex()) {
- this.tables.cleanFailURLS(this.getConfigLong("cleanup.failedSearchURLtimeout", -1));
+ if (getConfigBool(SwitchboardConstants.NETWORK_SEARCHVERIFY, false) && this.peers.mySeed().getFlagAcceptRemoteIndex()) {
+ this.tables.cleanFailURLS(getConfigLong("cleanup.failedSearchURLtimeout", -1));
}
-
+
return true;
} catch (final InterruptedException e) {
this.log.logInfo("cleanupJob: Shutdown detected");
return false;
}
}
-
+
/**
* With this function the crawling process can be paused
- * @param jobType
+ * @param jobType
*/
public void pauseCrawlJob(final String jobType) {
final Object[] status = this.crawlJobsStatus.get(jobType);
@@ -1819,11 +1818,11 @@ public final class Switchboard extends serverSwitch {
status[SwitchboardConstants.CRAWLJOB_STATUS] = Boolean.TRUE;
}
setConfig(jobType + "_isPaused", "true");
- }
-
+ }
+
/**
* Continue the previously paused crawling
- * @param jobType
+ * @param jobType
*/
public void continueCrawlJob(final String jobType) {
final Object[] status = this.crawlJobsStatus.get(jobType);
@@ -1834,10 +1833,10 @@ public final class Switchboard extends serverSwitch {
}
}
setConfig(jobType + "_isPaused", "false");
- }
-
+ }
+
/**
- * @param jobType
+ * @param jobType
* @return <code>true</code> if crawling was paused or <code>false</code> otherwise
*/
public boolean crawlJobIsPaused(final String jobType) {
@@ -1849,12 +1848,12 @@ public final class Switchboard extends serverSwitch {
public indexingQueueEntry parseDocument(final indexingQueueEntry in) {
in.queueEntry.updateStatus(Response.QUEUE_STATE_PARSING);
-
+
// debug
- if (log.isFinest()) {
- log.logFinest("PARSE "+ in.queueEntry);
+ if (this.log.isFinest()) {
+ this.log.logFinest("PARSE "+ in.queueEntry);
}
-
+
Document[] documents = null;
try {
documents = parseDocument(in.queueEntry);
@@ -1868,13 +1867,13 @@ public final class Switchboard extends serverSwitch {
}
return new indexingQueueEntry(in.process, in.queueEntry, documents, null);
}
-
+
private Document[] parseDocument(final Response response) throws InterruptedException {
Document[] documents = null;
- final EventOrigin processCase = response.processCase(peers.mySeed().hash);
-
+ final EventOrigin processCase = response.processCase(this.peers.mySeed().hash);
+
if (this.log.isFine()) {
- log.logFine("processResourceStack processCase=" + processCase +
+ this.log.logFine("processResourceStack processCase=" + processCase +
", depth=" + response.depth() +
", maxDepth=" + ((response.profile() == null) ? "null" : Integer.toString(response.profile().depth())) +
", must-match=" + ((response.profile() == null) ? "null" : response.profile().mustMatchPattern().toString()) +
@@ -1883,7 +1882,7 @@ public final class Switchboard extends serverSwitch {
//", responseHeader=" + ((entry.responseHeader() == null) ? "null" : entry.responseHeader().toString()) +
", url=" + response.url()); // DEBUG
}
-
+
// PARSE CONTENT
final long parsingStartTime = System.currentTimeMillis();
// fetch the document from the response
@@ -1909,9 +1908,9 @@ public final class Switchboard extends serverSwitch {
addURLtoErrorDB(response.url(), response.referrerHash(), response.initiator(), response.name(), FailCategory.FINAL_PROCESS_CONTEXT, e.getMessage());
return null;
}
-
+
final long parsingEndTime = System.currentTimeMillis();
-
+
// put anchors on crawl stack
final long stackStartTime = System.currentTimeMillis();
if (
@@ -1920,23 +1919,23 @@ public final class Switchboard extends serverSwitch {
) {
// get the hyperlinks
final Map<MultiProtocolURI, String> hl = Document.getHyperlinks(documents);
-
+
// add all images also to the crawl stack
hl.putAll(Document.getImagelinks(documents));
-
+
// insert those hyperlinks to the crawler
MultiProtocolURI nextUrl;
- for (Map.Entry<MultiProtocolURI, String> nextEntry : hl.entrySet()) {
+ for (final Map.Entry<MultiProtocolURI, String> nextEntry : hl.entrySet()) {
// check for interruption
checkInterruption();
-
+
// process the next hyperlink
nextUrl = nextEntry.getKey();
- String u = nextUrl.toNormalform(true, true, false, true);
+ final String u = nextUrl.toNormalform(true, true, false, true);
if (!(u.startsWith("http://") || u.startsWith("https://") || u.startsWith("ftp://") || u.startsWith("smb://") || u.startsWith("file://"))) continue;
// enqueue the hyperlink into the pre-notice-url db
try {
- crawlStacker.enqueueEntry(new Request(
+ this.crawlStacker.enqueueEntry(new Request(
response.initiator(),
new DigestURI(u),
response.url().hash(),
@@ -1948,80 +1947,80 @@ public final class Switchboard extends serverSwitch {
0,
response.size() < 0 ? 0 : response.size()
));
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logException(e);
}
}
final long stackEndTime = System.currentTimeMillis();
- if (log.isInfo()) {
- log.logInfo("CRAWL: ADDED " + hl.size() + " LINKS FROM " + response.url().toNormalform(false, true) +
+ if (this.log.isInfo()) {
+ this.log.logInfo("CRAWL: ADDED " + hl.size() + " LINKS FROM " + response.url().toNormalform(false, true) +
", STACKING TIME = " + (stackEndTime-stackStartTime) +
", PARSING TIME = " + (parsingEndTime-parsingStartTime));
}
}
return documents;
}
-
+
public indexingQueueEntry condenseDocument(final indexingQueueEntry in) {
in.queueEntry.updateStatus(Response.QUEUE_STATE_CONDENSING);
- if (this.solrConnector != null && this.getConfigBool("federated.service.solr.indexing.enabled", false)/*in.queueEntry.profile().pushSolr()*/) {
+ if (this.solrConnector != null && getConfigBool("federated.service.solr.indexing.enabled", false)/*in.queueEntry.profile().pushSolr()*/) {
// send the documents to solr
- for (Document doc: in.documents) {
+ for (final Document doc: in.documents) {
try {
- String id = UTF8.String(new DigestURI(doc.dc_identifier(), null).hash());
- String iquh = UTF8.String(in.queueEntry.url().hash());
+ final String id = UTF8.String(new DigestURI(doc.dc_identifier(), null).hash());
+ final String iquh = UTF8.String(in.queueEntry.url().hash());
if (!id.equals(iquh)) {
- log.logWarning("doc=" + id + ":" + doc.dc_identifier() + ", query=" + iquh + ":" + in.queueEntry.url());
+ this.log.logWarning("doc=" + id + ":" + doc.dc_identifier() + ", query=" + iquh + ":" + in.queueEntry.url());
// in case that this happens it appears that the doc id is the right one
}
try {
this.solrConnector.add(id, in.queueEntry.getResponseHeader(), doc);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logWarning("SOLR", "failed to send " + in.queueEntry.url().toNormalform(true, false) + " to solr: " + e.getMessage());
}
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logException(e);
continue;
}
}
}
-
+
// check if we should accept the document for our index
- if (!this.getConfigBool("federated.service.yacy.indexing.enabled", false)) {
- if (log.isInfo()) {
- log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': indexing not wanted by federated rule for YaCy");
+ if (!getConfigBool("federated.service.yacy.indexing.enabled", false)) {
+ if (this.log.isInfo()) {
+ this.log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': indexing not wanted by federated rule for YaCy");
}
return new indexingQueueEntry(in.process, in.queueEntry, in.documents, null);
}
if (!in.queueEntry.profile().indexText() && !in.queueEntry.profile().indexMedia()) {
- if (log.isInfo()) {
- log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': indexing not wanted by crawl profile");
+ if (this.log.isInfo()) {
+ this.log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': indexing not wanted by crawl profile");
}
return new indexingQueueEntry(in.process, in.queueEntry, in.documents, null);
}
- List<Document> doclist = new ArrayList<Document>();
-
+ final List<Document> doclist = new ArrayList<Document>();
+
// check which files may take part in the indexing process
for (final Document document: in.documents) {
if (document.indexingDenied()) {
- if (log.isInfo()) {
- log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': denied by document-attached noindexing rule");
+ if (this.log.isInfo()) {
+ this.log.logInfo("Not Condensed Resource '" + in.queueEntry.url().toNormalform(false, true) + "': denied by document-attached noindexing rule");
}
addURLtoErrorDB(in.queueEntry.url(), in.queueEntry.referrerHash(), in.queueEntry.initiator(), in.queueEntry.name(), FailCategory.FINAL_PROCESS_CONTEXT, "denied by document-attached noindexing rule");
continue;
}
doclist.add(document);
}
-
+
if (doclist.isEmpty()) return new indexingQueueEntry(in.process, in.queueEntry, in.documents, null);
in.documents = doclist.toArray(new Document[doclist.size()]);
final Condenser[] condenser = new Condenser[in.documents.length];
if (this.log.isFine()) {
- log.logFine("Condensing for '" + in.queueEntry.url().toNormalform(false, true) + "'");
+ this.log.logFine("Condensing for '" + in.queueEntry.url().toNormalform(false, true) + "'");
}
for (int i = 0; i < in.documents.length; i++) {
condenser[i] = new Condenser(in.documents[i], in.queueEntry.profile().indexText(), in.queueEntry.profile().indexMedia(), LibraryProvider.dymLib);
-
+
// update image result list statistics
// its good to do this concurrently here, because it needs a DNS lookup
// to compute a URL hash which is necessary for a double-check
@@ -2030,20 +2029,20 @@ public final class Switchboard extends serverSwitch {
}
return new indexingQueueEntry(in.process, in.queueEntry, in.documents, condenser);
}
-
+
public indexingQueueEntry webStructureAnalysis(final indexingQueueEntry in) {
in.queueEntry.updateStatus(Response.QUEUE_STATE_STRUCTUREANALYSIS);
for (int i = 0; i < in.documents.length; i++) {
- assert webStructure != null;
+ assert this.webStructure != null;
assert in != null;
assert in.queueEntry != null;
assert in.documents != null;
assert in.queueEntry != null;
- webStructure.generateCitationReference(in.queueEntry.url(), in.documents[i], (in.condenser == null) ? null : in.condenser[i]); // [outlinksSame, outlinksOther]
+ this.webStructure.generateCitationReference(in.queueEntry.url(), in.documents[i], (in.condenser == null) ? null : in.condenser[i]); // [outlinksSame, outlinksOther]
}
return in;
}
-
+
public void storeDocumentIndex(final indexingQueueEntry in) {
in.queueEntry.updateStatus(Response.QUEUE_STATE_INDEXSTORAGE);
// the condenser may be null in case that an indexing is not wanted (there may be a no-indexing flag in the file)
@@ -2054,13 +2053,13 @@ public final class Switchboard extends serverSwitch {
}
in.queueEntry.updateStatus(Response.QUEUE_STATE_FINISHED);
}
-
- private void storeDocumentIndex(final Segments.Process process, final Response queueEntry, final Document document, final Condenser condenser, final SearchEvent searchEvent, String sourceName) {
-
+
+ private void storeDocumentIndex(final Segments.Process process, final Response queueEntry, final Document document, final Condenser condenser, final SearchEvent searchEvent, final String sourceName) {
+
// CREATE INDEX
final String dc_title = document.dc_title();
final DigestURI referrerURL = queueEntry.referrerURL();
- EventOrigin processCase = queueEntry.processCase(peers.mySeed().hash);
+ EventOrigin processCase = queueEntry.processCase(this.peers.mySeed().hash);
if (process == Segments.Process.SURROGATES) {
processCase = EventOrigin.SURROGATES;
}
@@ -2070,20 +2069,20 @@ public final class Switchboard extends serverSwitch {
addURLtoErrorDB(queueEntry.url(), (referrerURL == null) ? null : referrerURL.hash(), queueEntry.initiator(), dc_title, FailCategory.FINAL_PROCESS_CONTEXT, "denied by rule in document, process case=" + processCase);
return;
}
-
+
if (!queueEntry.profile().indexText() && !queueEntry.profile().indexMedia()) {
//if (this.log.isInfo()) log.logInfo("Not Indexed Resource '" + queueEntry.url().toNormalform(false, true) + "': denied by profile rule, process case=" + processCase + ", profile name = " + queueEntry.profile().name());
addURLtoErrorDB(queueEntry.url(), (referrerURL == null) ? null : referrerURL.hash(), queueEntry.initiator(), dc_title, FailCategory.FINAL_LOAD_CONTEXT, "denied by profile rule, process case=" + processCase + ", profile name = " + queueEntry.profile().name());
return;
}
-
+
// remove stopwords
- log.logInfo("Excluded " + condenser.excludeWords(stopwords) + " words in URL " + queueEntry.url());
+ this.log.logInfo("Excluded " + condenser.excludeWords(stopwords) + " words in URL " + queueEntry.url());
// STORE WORD INDEX
URIMetadataRow newEntry = null;
try {
- newEntry = indexSegments.segment(process).storeDocument(
+ newEntry = this.indexSegments.segment(process).storeDocument(
queueEntry.url(),
referrerURL,
queueEntry.lastModified(),
@@ -2093,13 +2092,13 @@ public final class Switchboard extends serverSwitch {
condenser,
searchEvent,
sourceName);
- yacyChannel.channels(Base64Order.enhancedCoder.equal(queueEntry.initiator(), ASCII.getBytes(peers.mySeed().hash)) ? yacyChannel.LOCALINDEXING : yacyChannel.REMOTEINDEXING).addMessage(new RSSMessage("Indexed web page", dc_title, queueEntry.url().toNormalform(true, false)));
+ yacyChannel.channels(Base64Order.enhancedCoder.equal(queueEntry.initiator(), ASCII.getBytes(this.peers.mySeed().hash)) ? yacyChannel.LOCALINDEXING : yacyChannel.REMOTEINDEXING).addMessage(new RSSMessage("Indexed web page", dc_title, queueEntry.url().toNormalform(true, false)));
} catch (final IOException e) {
//if (this.log.isFine()) log.logFine("Not Indexed Resource '" + queueEntry.url().toNormalform(false, true) + "': process case=" + processCase);
addURLtoErrorDB(queueEntry.url(), (referrerURL == null) ? null : referrerURL.hash(), queueEntry.initiator(), dc_title, FailCategory.FINAL_LOAD_CONTEXT, "error storing url: " + queueEntry.url().toNormalform(false, true) + "': process case=" + processCase + ", error = " + e.getMessage());
return;
}
-
+
// store rss feeds in document into rss table
for (final Map.Entry<MultiProtocolURI, String> rssEntry : document.getRSS().entrySet()) {
final Tables.Data rssRow = new Tables.Data();
@@ -2109,11 +2108,11 @@ public final class Switchboard extends serverSwitch {
rssRow.put("recording_date", new Date());
try {
this.tables.update("rss", new DigestURI(rssEntry.getKey()).hash(), rssRow);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
-
+
// update url result list statistics
ResultURLs.stack(
newEntry, // loaded url db entry
@@ -2121,10 +2120,10 @@ public final class Switchboard extends serverSwitch {
UTF8.getBytes(this.peers.mySeed().hash), // executor peer hash
processCase // process case
);
-
+
// increment number of indexed urls
- indexedPages++;
-
+ this.indexedPages++;
+
// update profiling info
if (System.currentTimeMillis() - lastPPMUpdate > 20000) {
// we don't want to do this too often
@@ -2133,54 +2132,54 @@ public final class Switchboard extends serverSwitch {
lastPPMUpdate = System.currentTimeMillis();
}
EventTracker.update(EventTracker.EClass.INDEX, queueEntry.url().toNormalform(true, false), false);
-
+
// if this was performed for a remote crawl request, notify requester
if ((processCase == EventOrigin.GLOBAL_CRAWLING) && (queueEntry.initiator() != null)) {
- final yacySeed initiatorPeer = peers.get(ASCII.String(queueEntry.initiator()));
+ final yacySeed initiatorPeer = this.peers.get(ASCII.String(queueEntry.initiator()));
if (initiatorPeer != null) {
- if (clusterhashes != null) {
- initiatorPeer.setAlternativeAddress(clusterhashes.get(queueEntry.initiator()));
+ if (this.clusterhashes != null) {
+ initiatorPeer.setAlternativeAddress(this.clusterhashes.get(queueEntry.initiator()));
}
// start a thread for receipt sending to avoid a blocking here
new Thread(new receiptSending(initiatorPeer, newEntry), "sending receipt to " + ASCII.String(queueEntry.initiator())).start();
}
}
}
-
+
public final void addAllToIndex(final DigestURI url, final Map<MultiProtocolURI, String> links, final SearchEvent searchEvent, final String heuristicName) {
// add the landing page to the index. should not load that again since it should be in the cache
if (url != null) {
try {
- this.addToIndex(url, searchEvent, heuristicName);
- } catch (IOException e) {
- } catch (Parser.Failure e) {
+ addToIndex(url, searchEvent, heuristicName);
+ } catch (final IOException e) {
+ } catch (final Parser.Failure e) {
}
}
-
+
// check if some of the links match with the query
final Map<MultiProtocolURI, String> matcher = searchEvent.getQuery().separateMatches(links);
-
+
// take the matcher and load them all
for (final Map.Entry<MultiProtocolURI, String> entry: matcher.entrySet()) {
try {
- this.addToIndex(new DigestURI(entry.getKey(), (byte[]) null), searchEvent, heuristicName);
- } catch (IOException e) {
- } catch (Parser.Failure e) {
+ addToIndex(new DigestURI(entry.getKey(), (byte[]) null), searchEvent, heuristicName);
+ } catch (final IOException e) {
+ } catch (final Parser.Failure e) {
}
}
-
+
// take then the no-matcher and load them also
for (final Map.Entry<MultiProtocolURI, String> entry: links.entrySet()) {
try {
- this.addToIndex(new DigestURI(entry.getKey(), (byte[]) null), searchEvent, heuristicName);
- } catch (IOException e) {
- } catch (Parser.Failure e) {
+ addToIndex(new DigestURI(entry.getKey(), (byte[]) null), searchEvent, heuristicName);
+ } catch (final IOException e) {
+ } catch (final Parser.Failure e) {
}
}
}
-
+
/**
* load the content of a URL, parse the content and add the content to the index
* This process is started concurrently. The method returns immediately after the call.
@@ -2194,19 +2193,19 @@ public final class Switchboard extends serverSwitch {
if (searchEvent != null) {
searchEvent.addHeuristic(url.hash(), heuristicName, true);
}
- if (indexSegments.segment(process).urlMetadata.exists(url.hash())) return; // don't do double-work
- final Request request = loader.request(url, true, true);
+ if (this.indexSegments.segment(process).urlMetadata.exists(url.hash())) return; // don't do double-work
+ final Request request = this.loader.request(url, true, true);
final CrawlProfile profile = sb.crawler.getActive(ASCII.getBytes(request.profileHandle()));
- String acceptedError = this.crawlStacker.checkAcceptance(url, profile, 0);
+ final String acceptedError = this.crawlStacker.checkAcceptance(url, profile, 0);
if (acceptedError != null) {
- log.logWarning("addToIndex: cannot load " + url.toNormalform(false, false) + ": " + acceptedError);
+ this.log.logWarning("addToIndex: cannot load " + url.toNormalform(false, false) + ": " + acceptedError);
return;
}
new Thread() {
@Override
public void run() {
try {
- final Response response = loader.load(request, CacheStrategy.IFFRESH, Long.MAX_VALUE, true);
+ final Response response = Switchboard.this.loader.load(request, CacheStrategy.IFFRESH, Long.MAX_VALUE, true);
if (response == null) {
throw new IOException("response == null");
}
@@ -2224,49 +2223,49 @@ public final class Switchboard extends serverSwitch {
}
final Condenser condenser = new Condenser(document, true, true, LibraryProvider.dymLib);
ResultImages.registerImages(url, document, true);
- webStructure.generateCitationReference(url, document, condenser);
+ Switchboard.this.webStructure.generateCitationReference(url, document, condenser);
storeDocumentIndex(process, response, document, condenser, searchEvent, "heuristic:" + heuristicName);
- log.logInfo("addToIndex fill of url " + url.toNormalform(true, true) + " finished");
+ Switchboard.this.log.logInfo("addToIndex fill of url " + url.toNormalform(true, true) + " finished");
}
}
- } catch (IOException e) {
- log.logWarning("addToIndex: failed loading " + url.toNormalform(false, false) + ": " + e.getMessage());
- } catch (Parser.Failure e) {
- log.logWarning("addToIndex: failed parsing " + url.toNormalform(false, false) + ": " + e.getMessage());
+ } catch (final IOException e) {
+ Switchboard.this.log.logWarning("addToIndex: failed loading " + url.toNormalform(false, false) + ": " + e.getMessage());
+ } catch (final Parser.Failure e) {
+ Switchboard.this.log.logWarning("addToIndex: failed parsing " + url.toNormalform(false, false) + ": " + e.getMessage());
}
}
}.start();
}
-
+
public class receiptSending implements Runnable {
- private yacySeed initiatorPeer;
- private URIMetadataRow reference;
-
+ private final yacySeed initiatorPeer;
+ private final URIMetadataRow reference;
+
public receiptSending(final yacySeed initiatorPeer, final URIMetadataRow reference) {
this.initiatorPeer = initiatorPeer;
this.reference = reference;
}
public void run() {
final long t = System.currentTimeMillis();
- final Map<String, String> response = yacyClient.crawlReceipt(peers.mySeed(), initiatorPeer, "crawl", "fill", "indexed", reference, "");
+ final Map<String, String> response = yacyClient.crawlReceipt(Switchboard.this.peers.mySeed(), this.initiatorPeer, "crawl", "fill", "indexed", this.reference, "");
if (response == null) {
- log.logInfo("Sending crawl receipt for '" + reference.metadata().url().toNormalform(false, true) + "' to " + initiatorPeer.getName() + " FAILED, send time = " + (System.currentTimeMillis() - t));
+ Switchboard.this.log.logInfo("Sending crawl receipt for '" + this.reference.metadata().url().toNormalform(false, true) + "' to " + this.initiatorPeer.getName() + " FAILED, send time = " + (System.currentTimeMillis() - t));
return;
}
final String delay = response.get("delay");
- log.logInfo("Sending crawl receipt for '" + reference.metadata().url().toNormalform(false, true) + "' to " + initiatorPeer.getName() + " success, delay = " + delay + ", send time = " + (System.currentTimeMillis() - t));
+ Switchboard.this.log.logInfo("Sending crawl receipt for '" + this.reference.metadata().url().toNormalform(false, true) + "' to " + this.initiatorPeer.getName() + " success, delay = " + delay + ", send time = " + (System.currentTimeMillis() - t));
}
}
-
+
public boolean accessFromLocalhost(final RequestHeader requestHeader) {
-
+
// authorization for localhost, only if flag is set to grant localhost access as admin
final String clientIP = requestHeader.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "");
if (!Domains.isLocalhost(clientIP)) return false;
final String refererHost = requestHeader.refererHost();
return refererHost == null || refererHost.length() == 0 || Domains.isLocalhost(refererHost);
}
-
+
/**
* check authentication status for request
* access shall be granted if return value >= 2;
@@ -2280,34 +2279,34 @@ public final class Switchboard extends serverSwitch {
* @return the auth-level as described above or 1 which means 'not authorized'. a 0 is returned in case of fraud attempts
*/
public int adminAuthenticated(final RequestHeader requestHeader) {
-
+
// authorization in case that there is no account stored
final String adminAccountBase64MD5 = getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "");
if (adminAccountBase64MD5.length() == 0) return 2; // no password stored; this should not happen for older peers
-
+
// authorization for localhost, only if flag is set to grant localhost access as admin
final boolean accessFromLocalhost = accessFromLocalhost(requestHeader);
if (getConfigBool("adminAccountForLocalhost", false) && accessFromLocalhost) return 3; // soft-authenticated for localhost
-
+
// get the authorization string from the header
- String realmProp = (requestHeader.get(RequestHeader.AUTHORIZATION, "xxxxxx")).trim();
+ final String realmProp = (requestHeader.get(RequestHeader.AUTHORIZATION, "xxxxxx")).trim();
final String realmValue = realmProp.substring(6);
-
+
// security check against too long authorization strings
if (realmValue.length() > 256) return 0;
-
+
// authorization by encoded password, only for localhost access
if (accessFromLocalhost && (adminAccountBase64MD5.equals(realmValue))) return 3; // soft-authenticated for localhost
// authorization by hit in userDB
- if (userDB.hasAdminRight(realmProp, requestHeader.getHeaderCookies())) return 4; //return, because 4=max
+ if (this.userDB.hasAdminRight(realmProp, requestHeader.getHeaderCookies())) return 4; //return, because 4=max
// authorization with admin keyword in configuration
if (realmValue == null || realmValue.length() == 0) return 1;
if (adminAccountBase64MD5.equals(Digest.encodeMD5Hex(realmValue))) return 4; // hard-authenticated, all ok
return 1;
}
-
+
public boolean verifyAuthentication(final RequestHeader header, final boolean strict) {
// handle access rights
switch (adminAuthenticated(header)) {
@@ -2326,7 +2325,7 @@ public final class Switchboard extends serverSwitch {
return false;
}
}
-
+
public void setPerformance(final int wantedPPM) {
int wPPM = wantedPPM;
// we consider 3 cases here
@@ -2342,20 +2341,20 @@ public final class Switchboard extends serverSwitch {
final int newBusySleep = 60000 / wPPM; // for wantedPPM = 10: 6000; for wantedPPM = 1000: 60
BusyThread thread;
-
+
thread = getThread(SwitchboardConstants.INDEX_DIST);
if (thread != null) {
setConfig(SwitchboardConstants.INDEX_DIST_BUSYSLEEP , thread.setBusySleep(Math.max(2000, thread.setBusySleep(newBusySleep * 2))));
thread.setIdleSleep(30000);
}
-
+
thread = getThread(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL);
if (thread != null) {
setConfig(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP , thread.setBusySleep(newBusySleep));
thread.setIdleSleep(2000);
- }
+ }
}
-
+
public static int accessFrequency(final Map<String, SortedSet<Long>> tracker, final String host) {
// returns the access frequency in queries per hour for a given host and a specific tracker
final long timeInterval = 1000 * 60 * 60;
@@ -2363,7 +2362,7 @@ public final class Switchboard extends serverSwitch {
if (accessSet == null) return 0;
return accessSet.tailSet(Long.valueOf(System.currentTimeMillis() - timeInterval)).size();
}
-
+
public String dhtShallTransfer(final String segment) {
final String cautionCause = onlineCaution();
if (cautionCause != null) {
@@ -2381,7 +2380,7 @@ public final class Switchboard extends serverSwitch {
if (this.peers.noDHTActivity()) {
return "no DHT distribution: network too small";
}
- if (!this.getConfigBool("network.unit.dht", true)) {
+ if (!getConfigBool("network.unit.dht", true)) {
return "no DHT distribution: disabled by network.unit.dht";
}
if (getConfig(SwitchboardConstants.INDEX_DIST_ALLOW, "false").equalsIgnoreCase("false")) {
@@ -2394,11 +2393,11 @@ public final class Switchboard extends serverSwitch {
if (indexSegment.termIndex().sizesMax() < 100) {
return "no DHT distribution: not enough words - wordIndex.size() = " + indexSegment.termIndex().sizesMax();
}
- if ((getConfig(SwitchboardConstants.INDEX_DIST_ALLOW_WHILE_CRAWLING, "false").equalsIgnoreCase("false")) && (crawlQueues.noticeURL.notEmptyLocal())) {
- return "no DHT distribution: crawl in progress: noticeURL.stackSize() = " + crawlQueues.noticeURL.size() + ", sbQueue.size() = " + getIndexingProcessorsQueueSize();
+ if ((getConfig(SwitchboardConstants.INDEX_DIST_ALLOW_WHILE_CRAWLING, "false").equalsIgnoreCase("false")) && (this.crawlQueues.noticeURL.notEmptyLocal())) {
+ return "no DHT distribution: crawl in progress: noticeURL.stackSize() = " + this.crawlQueues.noticeURL.size() + ", sbQueue.size() = " + getIndexingProcessorsQueueSize();
}
if ((getConfig(SwitchboardConstants.INDEX_DIST_ALLOW_WHILE_INDEXING, "false").equalsIgnoreCase("false")) && (getIndexingProcessorsQueueSize() > 1)) {
- return "no DHT distribution: indexing in progress: noticeURL.stackSize() = " + crawlQueues.noticeURL.size() + ", sbQueue.size() = " + getIndexingProcessorsQueueSize();
+ return "no DHT distribution: indexing in progress: noticeURL.stackSize() = " + this.crawlQueues.noticeURL.size() + ", sbQueue.size() = " + getIndexingProcessorsQueueSize();
}
return null; // this means; yes, please do dht transfer
}
@@ -2406,13 +2405,13 @@ public final class Switchboard extends serverSwitch {
public boolean dhtTransferJob() {
return dhtTransferJob(getConfig(SwitchboardConstants.SEGMENT_DHTOUT, "default"));
}
-
+
public boolean dhtTransferJob(final String segment) {
- if (dhtDispatcher == null) return false;
+ if (this.dhtDispatcher == null) return false;
final String rejectReason = dhtShallTransfer(segment);
if (rejectReason != null) {
if (this.log.isFine()) {
- log.logFine(rejectReason);
+ this.log.logFine(rejectReason);
}
return false;
}
@@ -2420,15 +2419,15 @@ public final class Switchboard extends serverSwitch {
final long kbytesUp = ConnectionInfo.getActiveUpbytes() / 1024;
// accumulate RWIs to transmission cloud
if (this.dhtDispatcher.cloudSize() > this.peers.scheme.verticalPartitions() * 2) {
- log.logInfo("dhtTransferJob: no selection, too many entries in transmission cloud: " + this.dhtDispatcher.cloudSize());
+ this.log.logInfo("dhtTransferJob: no selection, too many entries in transmission cloud: " + this.dhtDispatcher.cloudSize());
} else if (MemoryControl.available() < 1024*1024*25) {
- log.logInfo("dhtTransferJob: no selection, too less memory available : " + (MemoryControl.available() / 1024 / 1024) + " MB");
+ this.log.logInfo("dhtTransferJob: no selection, too less memory available : " + (MemoryControl.available() / 1024 / 1024) + " MB");
} else if (ConnectionInfo.getLoadPercent() > 50) {
- log.logInfo("dhtTransferJob: too many connections in httpc pool : " + ConnectionInfo.getCount());
+ this.log.logInfo("dhtTransferJob: too many connections in httpc pool : " + ConnectionInfo.getCount());
// close unused connections
// Client.cleanup();
} else if (kbytesUp > 128) {
- log.logInfo("dhtTransferJob: too much upload(1), currently uploading: " + kbytesUp + " Kb");
+ this.log.logInfo("dhtTransferJob: too much upload(1), currently uploading: " + kbytesUp + " Kb");
} else {
byte[] startHash = null, limitHash = null;
int tries = 10;
@@ -2441,62 +2440,62 @@ public final class Switchboard extends serverSwitch {
}
}
if (limitHash == null || startHash == null) {
- log.logInfo("dhtTransferJob: approaching full DHT dispersion.");
+ this.log.logInfo("dhtTransferJob: approaching full DHT dispersion.");
return false;
}
- log.logInfo("dhtTransferJob: selected " + ASCII.String(startHash) + " as start hash");
- log.logInfo("dhtTransferJob: selected " + ASCII.String(limitHash) + " as limit hash");
- boolean enqueued = this.dhtDispatcher.selectContainersEnqueueToCloud(
+ this.log.logInfo("dhtTransferJob: selected " + ASCII.String(startHash) + " as start hash");
+ this.log.logInfo("dhtTransferJob: selected " + ASCII.String(limitHash) + " as limit hash");
+ final boolean enqueued = this.dhtDispatcher.selectContainersEnqueueToCloud(
startHash,
limitHash,
dhtMaxContainerCount,
- dhtMaxReferenceCount,
+ this.dhtMaxReferenceCount,
5000);
hasDoneSomething = hasDoneSomething | enqueued;
- log.logInfo("dhtTransferJob: result from enqueueing: " + ((enqueued) ? "true" : "false"));
+ this.log.logInfo("dhtTransferJob: result from enqueueing: " + ((enqueued) ? "true" : "false"));
}
-
+
// check if we can deliver entries to other peers
if (this.dhtDispatcher.transmissionSize() >= 10) {
- log.logInfo("dhtTransferJob: no dequeueing from cloud to transmission: too many concurrent sessions: " + this.dhtDispatcher.transmissionSize());
+ this.log.logInfo("dhtTransferJob: no dequeueing from cloud to transmission: too many concurrent sessions: " + this.dhtDispatcher.transmissionSize());
} else if (ConnectionInfo.getLoadPercent() > 75) {
- log.logInfo("dhtTransferJob: too many connections in httpc pool : " + ConnectionInfo.getCount());
+ this.log.logInfo("dhtTransferJob: too many connections in httpc pool : " + ConnectionInfo.getCount());
// close unused connections
// Client.cleanup();
} else if (kbytesUp > 256) {
- log.logInfo("dhtTransferJob: too much upload(2), currently uploading: " + kbytesUp + " Kb");
+ this.log.logInfo("dhtTransferJob: too much upload(2), currently uploading: " + kbytesUp + " Kb");
} else {
- boolean dequeued = this.dhtDispatcher.dequeueContainer();
+ final boolean dequeued = this.dhtDispatcher.dequeueContainer();
hasDoneSomething = hasDoneSomething | dequeued;
- log.logInfo("dhtTransferJob: result from dequeueing: " + ((dequeued) ? "true" : "false"));
+ this.log.logInfo("dhtTransferJob: result from dequeueing: " + ((dequeued) ? "true" : "false"));
}
return hasDoneSomething;
}
private void addURLtoErrorDB(
- final DigestURI url,
- final byte[] referrerHash,
- final byte[] initiator,
- final String name,
+ final DigestURI url,
+ final byte[] referrerHash,
+ final byte[] initiator,
+ final String name,
final FailCategory failCategory,
final String failreason
) {
// assert initiator != null; // null == proxy
// create a new errorURL DB entry
final Request bentry = new Request(
- initiator,
- url,
- referrerHash,
- (name == null) ? "" : name,
+ initiator,
+ url,
+ referrerHash,
+ (name == null) ? "" : name,
new Date(),
null,
- 0,
- 0,
+ 0,
+ 0,
0,
0);
- crawlQueues.errorURL.push(bentry, initiator, new Date(), 0, failCategory, failreason, -1);
+ this.crawlQueues.errorURL.push(bentry, initiator, new Date(), 0, failCategory, failreason, -1);
}
-
+
public final void heuristicSite(final SearchEvent searchEvent, final String host) {
new Thread() {
@Override
@@ -2510,15 +2509,15 @@ public final class Switchboard extends serverSwitch {
DigestURI url;
try {
url = new DigestURI(r);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
Log.logException(e);
return;
}
final Map<MultiProtocolURI, String> links;
try {
- links = loader.loadLinks(url, CrawlProfile.CacheStrategy.NOCACHE);
- } catch (IOException e) {
+ links = Switchboard.this.loader.loadLinks(url, CacheStrategy.NOCACHE);
+ } catch (final IOException e) {
Log.logException(e);
return;
}
@@ -2540,7 +2539,7 @@ public final class Switchboard extends serverSwitch {
@Override
public void run() {
String query = searchEvent.getQuery().queryString(true);
- int meta = query.indexOf("heuristic:");
+ final int meta = query.indexOf("heuristic:");
if (meta >= 0) {
final int q = query.indexOf(' ', meta);
query = (q >= 0) ? query.substring(0, meta) + query.substring(q + 1) : query.substring(0, meta);
@@ -2549,15 +2548,15 @@ public final class Switchboard extends serverSwitch {
final DigestURI url;
try {
url = new DigestURI(MultiProtocolURI.unescape(urlString));
- } catch (MalformedURLException e1) {
+ } catch (final MalformedURLException e1) {
Log.logWarning("heuristicScroogle", "url not well-formed: '" + urlString + "'");
return;
}
Map<MultiProtocolURI, String> links = null;
try {
- links = loader.loadLinks(url, CrawlProfile.CacheStrategy.NOCACHE);
- } catch (IOException e) {
+ links = Switchboard.this.loader.loadLinks(url, CacheStrategy.NOCACHE);
+ } catch (final IOException e) {
Log.logException(e);
return;
}
@@ -2567,13 +2566,13 @@ public final class Switchboard extends serverSwitch {
i.remove();
}
}
- log.logInfo("Heuristic: adding " + links.size() + " links from scroogle");
+ Switchboard.this.log.logInfo("Heuristic: adding " + links.size() + " links from scroogle");
// add all pages to the index
addAllToIndex(null, links, searchEvent, "scroogle");
}
}.start();
}
-
+
// blekko pattern: http://blekko.com/ws/$+/rss
public final void heuristicRSS(final String urlpattern, final SearchEvent searchEvent, final String feedName) {
final int p = urlpattern.indexOf('$');
@@ -2582,7 +2581,7 @@ public final class Switchboard extends serverSwitch {
@Override
public void run() {
String query = searchEvent.getQuery().queryString(true);
- int meta = query.indexOf("heuristic:");
+ final int meta = query.indexOf("heuristic:");
if (meta >= 0) {
final int q = query.indexOf(' ', meta);
if (q >= 0) query = query.substring(0, meta) + query.substring(q + 1); else query = query.substring(0, meta);
@@ -2592,7 +2591,7 @@ public final class Switchboard extends serverSwitch {
final DigestURI url;
try {
url = new DigestURI(MultiProtocolURI.unescape(urlString));
- } catch (MalformedURLException e1) {
+ } catch (final MalformedURLException e1) {
Log.logWarning("heuristicRSS", "url not well-formed: '" + urlString + "'");
return;
}
@@ -2600,37 +2599,37 @@ public final class Switchboard extends serverSwitch {
// if we have an url then try to load the rss
RSSReader rss = null;
try {
- final Response response = sb.loader.load(sb.loader.request(url, true, false), CrawlProfile.CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
- byte[] resource = (response == null) ? null : response.getContent();
+ final Response response = sb.loader.load(sb.loader.request(url, true, false), CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
+ final byte[] resource = (response == null) ? null : response.getContent();
//System.out.println("BLEKKO: " + UTF8.String(resource));
rss = resource == null ? null : RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, resource);
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
if (rss == null) {
Log.logInfo("heuristicRSS", "rss result not parsed from " + feedName);
return;
}
-
+
final Map<MultiProtocolURI, String> links = new TreeMap<MultiProtocolURI, String>();
MultiProtocolURI uri;
for (final RSSMessage message: rss.getFeed()) try {
uri = new MultiProtocolURI(message.getLink());
links.put(uri, message.getTitle());
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
}
-
+
Log.logInfo("heuristicRSS", "Heuristic: adding " + links.size() + " links from '" + feedName + "' rss feed");
// add all pages to the index
addAllToIndex(null, links, searchEvent, feedName);
}
}.start();
}
-
+
public int currentPPM() {
return EventTracker.countEvents(EventTracker.EClass.INDEX, 20000) * 3;
}
-
+
public float averageQPM() {
final long uptime = (System.currentTimeMillis() - serverCore.startupTime) / 1000;
return (this.searchQueriesRobinsonFromRemote + this.searchQueriesGlobal) * 60f / Math.max(uptime, 1f);
@@ -2647,41 +2646,41 @@ public final class Switchboard extends serverSwitch {
final long uptime = (System.currentTimeMillis() - serverCore.startupTime) / 1000;
return (this.searchQueriesRobinsonFromRemote) * 60f / Math.max(uptime, 1f);
}
-
+
public void updateMySeed() {
- peers.mySeed().put(yacySeed.PORT, Integer.toString(serverCore.getPortNr(getConfig("port", "8090"))));
-
+ this.peers.mySeed().put(yacySeed.PORT, Integer.toString(serverCore.getPortNr(getConfig("port", "8090"))));
+
//the speed of indexing (pages/minute) of the peer
final long uptime = (System.currentTimeMillis() - serverCore.startupTime) / 1000;
- peers.mySeed().put(yacySeed.ISPEED, Integer.toString(currentPPM()));
- peers.mySeed().put(yacySeed.RSPEED, Float.toString(averageQPM()));
- peers.mySeed().put(yacySeed.UPTIME, Long.toString(uptime/60)); // the number of minutes that the peer is up in minutes/day (moving average MA30)
- peers.mySeed().put(yacySeed.LCOUNT, Long.toString(indexSegments.URLCount())); // the number of links that the peer has stored (LURL's)
- peers.mySeed().put(yacySeed.NCOUNT, Integer.toString(crawlQueues.noticeURL.size())); // the number of links that the peer has noticed, but not loaded (NURL's)
- peers.mySeed().put(yacySeed.RCOUNT, Integer.toString(crawlQueues.noticeURL.stackSize(NoticedURL.StackType.LIMIT))); // the number of links that the peer provides for remote crawling (ZURL's)
- peers.mySeed().put(yacySeed.ICOUNT, Long.toString(indexSegments.RWICount())); // the minimum number of words that the peer has indexed (as it says)
- peers.mySeed().put(yacySeed.SCOUNT, Integer.toString(peers.sizeConnected())); // the number of seeds that the peer has stored
- peers.mySeed().put(yacySeed.CCOUNT, Float.toString(((int) ((peers.sizeConnected() + peers.sizeDisconnected() + peers.sizePotential()) * 60.0f / (uptime + 1.01f)) * 100.0f) / 100.0f)); // the number of clients that the peer connects (as connects/hour)
- peers.mySeed().put(yacySeed.VERSION, yacyBuildProperties.getLongVersion());
- peers.mySeed().setFlagDirectConnect(true);
- peers.mySeed().setLastSeenUTC();
- peers.mySeed().put(yacySeed.UTC, GenericFormatter.UTCDiffString());
- peers.mySeed().setFlagAcceptRemoteCrawl(getConfig("crawlResponse", "").equals("true"));
- peers.mySeed().setFlagAcceptRemoteIndex(getConfig("allowReceiveIndex", "").equals("true"));
+ this.peers.mySeed().put(yacySeed.ISPEED, Integer.toString(currentPPM()));
+ this.peers.mySeed().put(yacySeed.RSPEED, Float.toString(averageQPM()));
+ this.peers.mySeed().put(yacySeed.UPTIME, Long.toString(uptime/60)); // the number of minutes that the peer is up in minutes/day (moving average MA30)
+ this.peers.mySeed().put(yacySeed.LCOUNT, Long.toString(this.indexSegments.URLCount())); // the number of links that the peer has stored (LURL's)
+ this.peers.mySeed().put(yacySeed.NCOUNT, Integer.toString(this.crawlQueues.noticeURL.size())); // the number of links that the peer has noticed, but not loaded (NURL's)
+ this.peers.mySeed().put(yacySeed.RCOUNT, Integer.toString(this.crawlQueues.noticeURL.stackSize(NoticedURL.StackType.LIMIT))); // the number of links that the peer provides for remote crawling (ZURL's)
+ this.peers.mySeed().put(yacySeed.ICOUNT, Long.toString(this.indexSegments.RWICount())); // the minimum number of words that the peer has indexed (as it says)
+ this.peers.mySeed().put(yacySeed.SCOUNT, Integer.toString(this.peers.sizeConnected())); // the number of seeds that the peer has stored
+ this.peers.mySeed().put(yacySeed.CCOUNT, Float.toString(((int) ((this.peers.sizeConnected() + this.peers.sizeDisconnected() + this.peers.sizePotential()) * 60.0f / (uptime + 1.01f)) * 100.0f) / 100.0f)); // the number of clients that the peer connects (as connects/hour)
+ this.peers.mySeed().put(yacySeed.VERSION, yacyBuildProperties.getLongVersion());
+ this.peers.mySeed().setFlagDirectConnect(true);
+ this.peers.mySeed().setLastSeenUTC();
+ this.peers.mySeed().put(yacySeed.UTC, GenericFormatter.UTCDiffString());
+ this.peers.mySeed().setFlagAcceptRemoteCrawl(getConfig("crawlResponse", "").equals("true"));
+ this.peers.mySeed().setFlagAcceptRemoteIndex(getConfig("allowReceiveIndex", "").equals("true"));
//mySeed.setFlagAcceptRemoteIndex(true);
}
public void loadSeedLists() {
// uses the superseed to initialize the database with known seeds
-
+
yacySeed ys;
String seedListFileURL;
DigestURI url;
Iterator<String> enu;
int lc;
- final int sc = peers.sizeConnected();
+ final int sc = this.peers.sizeConnected();
ResponseHeader header;
-
+
final RequestHeader reqHeader = new RequestHeader();
reqHeader.put(HeaderFramework.PRAGMA, "no-cache");
reqHeader.put(HeaderFramework.CACHE_CONTROL, "no-cache");
@@ -2689,9 +2688,9 @@ public final class Switchboard extends serverSwitch {
final HTTPClient client = new HTTPClient();
client.setHeader(reqHeader.entrySet());
client.setTimout((int) getConfigLong("bootstrapLoadTimeout", 20000));
-
+
yacyCore.log.logInfo("BOOTSTRAP: " + sc + " seeds known from previous run");
-
+
// - use the superseed to further fill up the seedDB
int ssc = 0, c = 0;
while (true) {
@@ -2704,12 +2703,12 @@ public final class Switchboard extends serverSwitch {
}
c++;
if (
- seedListFileURL.startsWith("http://") ||
+ seedListFileURL.startsWith("http://") ||
seedListFileURL.startsWith("https://")
) {
// load the seed list
try {
-
+
url = new DigestURI(seedListFileURL);
//final long start = System.currentTimeMillis();
client.HEADResponse(url.toString());
@@ -2734,21 +2733,21 @@ public final class Switchboard extends serverSwitch {
try {
ys = yacySeed.genRemoteSeed(enu.next(), null, false, null);
if ((ys != null) &&
- (!peers.mySeedIsDefined() || !peers.mySeed().hash.equals(ys.hash))) {
+ (!this.peers.mySeedIsDefined() || !this.peers.mySeed().hash.equals(ys.hash))) {
final long lastseen = Math.abs((System.currentTimeMillis() - ys.getLastSeenUTC()) / 1000 / 60);
if (lastseen < 240) {
- if (peers.peerActions.connectPeer(ys, false)) {
+ if (this.peers.peerActions.connectPeer(ys, false)) {
lc++;
}
}
}
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logInfo("BOOTSTRAP: bad seed: " + e.getMessage());
}
}
yacyCore.log.logInfo("BOOTSTRAP: " + lc + " seeds from seed-list URL " + seedListFileURL + ", AGE=" + (header.age() / 3600000) + "h");
}
-
+
} catch (final IOException e) {
// this is when wget fails, commonly because of timeout
yacyCore.log.logWarning("BOOTSTRAP: failed (1) to load seeds from seed-list URL " + seedListFileURL + ": " + e.getMessage());
@@ -2758,7 +2757,7 @@ public final class Switchboard extends serverSwitch {
}
}
}
- yacyCore.log.logInfo("BOOTSTRAP: " + (peers.sizeConnected() - sc) + " new seeds while bootstraping.");
+ yacyCore.log.logInfo("BOOTSTRAP: " + (this.peers.sizeConnected() - sc) + " new seeds while bootstraping.");
}
public void initRemoteProxy() {
@@ -2777,19 +2776,19 @@ public final class Switchboard extends serverSwitch {
ProxySettings.port = port;
ProxySettings.host = host;
ProxySettings.use = ((ProxySettings.host != null) && (ProxySettings.host.length() > 0));
-
+
// determining if remote proxy usage is enabled
ProxySettings.use = getConfigBool("remoteProxyUse", false);
-
+
// determining if remote proxy should be used for yacy -> yacy communication
ProxySettings.use4YaCy = getConfig("remoteProxyUse4Yacy", "true").equalsIgnoreCase("true");
-
+
// determining if remote proxy should be used for ssl connections
- ProxySettings.use4ssl = getConfig("remoteProxyUse4SSL", "true").equalsIgnoreCase("true");
-
+ ProxySettings.use4ssl = getConfig("remoteProxyUse4SSL", "true").equalsIgnoreCase("true");
+
ProxySettings.user = getConfig("remoteProxyUser", "").trim();
ProxySettings.password = getConfig("remoteProxyPwd", "").trim();
-
+
// determining addresses for which the remote proxy should not be used
final String remoteProxyNoProxy = getConfig("remoteProxyNoProxy","").trim();
ProxySettings.noProxy = remoteProxyNoProxy.split(",");
@@ -2800,7 +2799,7 @@ public final class Switchboard extends serverSwitch {
i++;
}
}
-
+
public void checkInterruption() throws InterruptedException {
final Thread curThread = Thread.currentThread();
if ((curThread instanceof WorkflowThread) && ((WorkflowThread)curThread).shutdownInProgress()) {
@@ -2814,20 +2813,20 @@ public final class Switchboard extends serverSwitch {
if (delay <= 0) {
throw new IllegalArgumentException("The shutdown delay must be greater than 0.");
}
- log.logInfo("caught delayed terminate request: " + reason);
+ this.log.logInfo("caught delayed terminate request: " + reason);
(new delayedShutdown(this, delay, reason)).start();
}
-
+
public void terminate(final String reason) {
this.terminate = true;
- log.logInfo("caught terminate request: " + reason);
+ this.log.logInfo("caught terminate request: " + reason);
this.shutdownSync.release();
}
-
+
public boolean isTerminated() {
return this.terminate;
}
-
+
public boolean waitForShutdown() throws InterruptedException {
this.shutdownSync.acquire();
return this.terminate;
@@ -2835,9 +2834,9 @@ public final class Switchboard extends serverSwitch {
/**
* loads the url as Map
- *
+ *
* Strings like abc=123 are parsed as pair: abc => 123
- *
+ *
* @param url
* @return
*/
@@ -2870,16 +2869,16 @@ class delayedShutdown extends Thread {
this.delay = delay;
this.reason = reason;
}
-
+
@Override
public void run() {
try {
- Thread.sleep(delay);
+ Thread.sleep(this.delay);
} catch (final InterruptedException e) {
- sb.getLog().logInfo("interrupted delayed shutdown");
+ this.sb.getLog().logInfo("interrupted delayed shutdown");
} catch (final Exception e) {
Log.logException(e);
}
- this.sb.terminate(reason);
+ this.sb.terminate(this.reason);
}
}
diff --git a/source/de/anomic/search/TextSnippet.java b/source/de/anomic/search/TextSnippet.java
index e7352a815..f8634a173 100644
--- a/source/de/anomic/search/TextSnippet.java
+++ b/source/de/anomic/search/TextSnippet.java
@@ -28,11 +28,13 @@ import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
+import java.util.Set;
import java.util.SortedMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.yacy.cora.document.ASCII;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.cora.storage.ARC;
import net.yacy.cora.storage.ConcurrentARC;
import net.yacy.document.Document;
@@ -48,8 +50,6 @@ import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.util.ByteArray;
import net.yacy.kelondro.util.ByteBuffer;
import net.yacy.repository.LoaderDispatcher;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
import de.anomic.yacy.yacySearch;
@@ -82,29 +82,29 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
public static class Cache {
private final ARC<String, String> cache;
public Cache() {
- cache = new ConcurrentARC<String, String>(maxCache, Math.max(32, 4 * Runtime.getRuntime().availableProcessors()));
+ this.cache = new ConcurrentARC<String, String>(maxCache, Math.max(32, 4 * Runtime.getRuntime().availableProcessors()));
}
public void put(final String wordhashes, final String urlhash, final String snippet) {
// generate key
final String key = urlhash + wordhashes;
// do nothing if snippet is known or otherwise learn new snippet
- cache.insertIfAbsent(key, snippet);
+ this.cache.insertIfAbsent(key, snippet);
}
-
+
public String get(final String wordhashes, final String urlhash) {
// generate key
final String key = urlhash + wordhashes;
- return cache.get(key);
+ return this.cache.get(key);
}
-
+
public boolean contains(final String wordhashes, final String urlhash) {
- return cache.containsKey(urlhash + wordhashes);
+ return this.cache.containsKey(urlhash + wordhashes);
}
}
-
+
public static final Cache snippetsCache = new Cache();
-
+
public static enum ResultClass {
SOURCE_CACHE(false),
SOURCE_FILE(false),
@@ -124,7 +124,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
return this.fail;
}
}
-
+
private byte[] urlhash;
private String line;
private String error;
@@ -142,7 +142,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
final LoaderDispatcher loader,
final URIMetadataRow.Components comp,
final HandleSet queryhashes,
- final CrawlProfile.CacheStrategy cacheStrategy,
+ final CacheStrategy cacheStrategy,
final boolean pre,
final int snippetMaxLength,
final int maxDocLen,
@@ -154,7 +154,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
init(url.hash(), null, ResultClass.ERROR_NO_HASH_GIVEN, "no query hashes given");
return;
}
-
+
// try to get snippet from snippetCache
ResultClass source = ResultClass.SOURCE_CACHE;
final String wordhashes = yacySearch.set2string(queryhashes);
@@ -165,8 +165,8 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
init(url.hash(), snippetLine, source, null);
return;
}
-
-
+
+
/* ===========================================================================
* LOAD RESOURCE DATA
* =========================================================================== */
@@ -175,7 +175,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
try {
// first try to get the snippet from metadata
String loc;
- boolean noCacheUsage = url.isFile() || url.isSMB() || cacheStrategy == null;
+ final boolean noCacheUsage = url.isFile() || url.isSMB() || cacheStrategy == null;
if (containsAllHashes(loc = comp.dc_title(), queryhashes)) {
// try to create the snippet from information given in the url itself
init(url.hash(), loc, ResultClass.SOURCE_METADATA, null);
@@ -194,14 +194,14 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
return;
} else {
// try to load the resource from the cache
- response = loader == null ? null : loader.load(loader.request(url, true, reindexing), noCacheUsage ? CrawlProfile.CacheStrategy.NOCACHE : cacheStrategy, Long.MAX_VALUE, true);
+ response = loader == null ? null : loader.load(loader.request(url, true, reindexing), noCacheUsage ? CacheStrategy.NOCACHE : cacheStrategy, Long.MAX_VALUE, true);
if (response == null) {
// in case that we did not get any result we can still return a success when we are not allowed to go online
if (cacheStrategy == null || cacheStrategy.mustBeOffline()) {
init(url.hash(), null, ResultClass.ERROR_SOURCE_LOADING, "omitted network load (not allowed), no cache entry");
return;
}
-
+
// if it is still not available, report an error
init(url.hash(), null, ResultClass.ERROR_RESOURCE_LOADING, "error loading resource from net, no cache entry");
return;
@@ -215,8 +215,8 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
//Log.logException(e);
init(url.hash(), null, ResultClass.ERROR_SOURCE_LOADING, "error loading resource: " + e.getMessage());
return;
- }
-
+ }
+
/* ===========================================================================
* PARSE RESOURCE
* =========================================================================== */
@@ -231,10 +231,10 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
init(url.hash(), null, ResultClass.ERROR_PARSER_FAILED, "parser error/failed"); // cannot be parsed
return;
}
-
+
/* ===========================================================================
* COMPUTE SNIPPET
- * =========================================================================== */
+ * =========================================================================== */
// we have found a parseable non-empty file: use the lines
// compute snippet from text
@@ -250,25 +250,25 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
tsr = new SnippetExtractor(sentences, queryhashes, snippetMaxLength);
textline = tsr.getSnippet();
remainingHashes = tsr.getRemainingWords();
- } catch (UnsupportedOperationException e) {
+ } catch (final UnsupportedOperationException e) {
init(url.hash(), null, ResultClass.ERROR_NO_MATCH, "no matching snippet found");
return;
}
-
+
// compute snippet from media
//String audioline = computeMediaSnippet(document.getAudiolinks(), queryhashes);
//String videoline = computeMediaSnippet(document.getVideolinks(), queryhashes);
//String appline = computeMediaSnippet(document.getApplinks(), queryhashes);
//String hrefline = computeMediaSnippet(document.getAnchors(), queryhashes);
//String imageline = computeMediaSnippet(document.getAudiolinks(), queryhashes);
-
+
snippetLine = "";
//if (audioline != null) line += (line.length() == 0) ? audioline : "<br />" + audioline;
//if (videoline != null) line += (line.length() == 0) ? videoline : "<br />" + videoline;
//if (appline != null) line += (line.length() == 0) ? appline : "<br />" + appline;
//if (hrefline != null) line += (line.length() == 0) ? hrefline : "<br />" + hrefline;
if (textline != null) snippetLine += (snippetLine.length() == 0) ? textline : "<br />" + textline;
-
+
if (snippetLine == null || !remainingHashes.isEmpty()) {
init(url.hash(), null, ResultClass.ERROR_NO_MATCH, "no matching snippet found");
return;
@@ -277,42 +277,42 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
// finally store this snippet in our own cache
snippetsCache.put(wordhashes, urls, snippetLine);
-
+
document.close();
init(url.hash(), snippetLine, source, null);
}
-
+
private void init(final byte[] urlhash, final String line, final ResultClass errorCode, final String errortext) {
this.urlhash = urlhash;
this.line = line;
this.resultStatus = errorCode;
this.error = errortext;
}
-
+
public boolean exists() {
- return line != null;
+ return this.line != null;
}
-
+
public String getLineRaw() {
- return (line == null) ? "" : line;
+ return (this.line == null) ? "" : this.line;
}
-
+
public String getError() {
- return (error == null) ? "" : error.trim();
+ return (this.error == null) ? "" : this.error.trim();
}
-
+
public ResultClass getErrorCode() {
- return resultStatus;
+ return this.resultStatus;
}
-
+
private final static Pattern splitPattern = Pattern.compile(" |-");
public String getLineMarked(final HandleSet queryHashes) {
- if (line == null) return "";
- if (queryHashes == null || queryHashes.isEmpty()) return line.trim();
- if (line.endsWith(".")) line = line.substring(0, line.length() - 1);
+ if (this.line == null) return "";
+ if (queryHashes == null || queryHashes.isEmpty()) return this.line.trim();
+ if (this.line.endsWith(".")) this.line = this.line.substring(0, this.line.length() - 1);
final Iterator<byte[]> i = queryHashes.iterator();
byte[] h;
- final String[] words = splitPattern.split(line);
+ final String[] words = splitPattern.split(this.line);
while (i.hasNext()) {
h = i.next();
for (int j = 0; j < words.length; j++) {
@@ -327,32 +327,32 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
}
}
}
- final StringBuilder l = new StringBuilder(line.length() + queryHashes.size() * 8);
- for (int j = 0; j < words.length; j++) {
- l.append(words[j]);
+ final StringBuilder l = new StringBuilder(this.line.length() + queryHashes.size() * 8);
+ for (final String word : words) {
+ l.append(word);
l.append(' ');
}
return l.toString().trim();
}
- public int compareTo(TextSnippet o) {
+ public int compareTo(final TextSnippet o) {
return Base64Order.enhancedCoder.compare(this.urlhash, o.urlhash);
}
-
- public int compare(TextSnippet o1, TextSnippet o2) {
+
+ public int compare(final TextSnippet o1, final TextSnippet o2) {
return o1.compareTo(o2);
}
-
+
@Override
public int hashCode() {
return ByteArray.hashCode(this.urlhash);
}
-
+
@Override
public String toString() {
- return (line == null) ? "" : line;
+ return (this.line == null) ? "" : this.line;
}
-
+
/**
* mark words with &lt;b&gt;-tags
* @param word the word to mark
@@ -367,8 +367,8 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
//especially p. 123 and p. 390/391 (in the German version of the 2nd edition)
StringBuilder theWord = new StringBuilder(word);
- StringBuilder prefix = new StringBuilder(40);
- StringBuilder postfix = new StringBuilder(40);
+ final StringBuilder prefix = new StringBuilder(40);
+ final StringBuilder postfix = new StringBuilder(40);
int len = 0;
// cut off prefix if it contains of non-characters or non-numbers
@@ -422,7 +422,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
theWord.append(CharacterCoding.unicode2html(postfix.toString(), false));
return theWord.toString();
}
-
+
/**
* words that already has been marked has index <code>(i % 2 == 1)</code>
* words that has not yet been marked has index <code>(i % 2 == 0)</code>
@@ -431,7 +431,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
* @author [DW], 08.11.2008
*/
private static List<String> markedWordArrayList(String string){
- List<String> al = new java.util.ArrayList<String>(1);
+ final List<String> al = new java.util.ArrayList<String>(1);
Matcher m = p01.matcher(string);
while (m.find()) {
al.add(m.group(1));
@@ -442,7 +442,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip
al.add(string);
return al;
}
-
+
private static boolean containsAllHashes(final String sentence, final HandleSet queryhashes) {
final SortedMap<byte[], Integer> m = WordTokenizer.hashSentence(sentence, null);
for (final byte[] b: queryhashes) {
diff --git a/source/de/anomic/yacy/graphics/OSMTile.java b/source/de/anomic/yacy/graphics/OSMTile.java
index ee054f82a..2b06c06d5 100644
--- a/source/de/anomic/yacy/graphics/OSMTile.java
+++ b/source/de/anomic/yacy/graphics/OSMTile.java
@@ -2,7 +2,7 @@
* OSMTile
* Copyright 2008 by Michael Peter Christen
* First released 12.02.2008 at http://yacy.net
- *
+ *
* $LastChangedDate$
* $LastChangedRevision$
* $LastChangedBy$
@@ -11,12 +11,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -34,19 +34,18 @@ import java.util.List;
import javax.imageio.ImageIO;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.visualization.RasterPlotter;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
import de.anomic.http.client.Cache;
import de.anomic.search.Switchboard;
public class OSMTile {
-
+
// helper methods to load map images from openstreetmap.org
-
+
/**
* generate a image according to a given coordinate of a middle tile
* and a width and height of tile numbers. The tile number width and height must
@@ -62,7 +61,7 @@ public class OSMTile {
final int h = (height - 1) / 2;
height = h * 2 + 1;
final RasterPlotter m = new RasterPlotter(256 * width, 256 * height, RasterPlotter.DrawMode.MODE_REPLACE, "FFFFFF");
- List<Place> tileLoader = new ArrayList<Place>();
+ final List<Place> tileLoader = new ArrayList<Place>();
Place place;
// start tile loading concurrently
for (int i = 0; i < width; i++) {
@@ -70,36 +69,36 @@ public class OSMTile {
place = new Place(m, t.xtile - w + i, t.ytile - h + j, 256 * i, 256 * j, t.zoom);
place.start();
tileLoader.add(place);
- if (t.zoom >= 17) try {Thread.sleep(100);} catch (InterruptedException e) {} // be nice with tile server for uncached tiles
+ if (t.zoom >= 17) try {Thread.sleep(100);} catch (final InterruptedException e) {} // be nice with tile server for uncached tiles
}
}
// wait until all tiles are loaded
- for (Place p: tileLoader) try { p.join(); } catch (InterruptedException e) {}
+ for (final Place p: tileLoader) try { p.join(); } catch (final InterruptedException e) {}
return m;
}
-
+
static class Place extends Thread {
RasterPlotter m;
int xt, yt, xc, yc, z;
- public Place(RasterPlotter m, int xt, int yt, int xc, int yc, int z) {
+ public Place(final RasterPlotter m, final int xt, final int yt, final int xc, final int yc, final int z) {
this.m = m; this.xt = xt; this.yt = yt; this.xc = xc; this.yc = yc; this.z = z;
}
public void run() {
- tileCoordinates t = new tileCoordinates(xt, yt, z);
+ final tileCoordinates t = new tileCoordinates(this.xt, this.yt, this.z);
BufferedImage bi = null;
for (int i = 0; i < 5; i++) {
bi = getSingleTile(t, i);
if (bi != null) {
- m.insertBitmap(bi, xc, yc);
+ this.m.insertBitmap(bi, this.xc, this.yc);
return;
}
// don't DoS OSM when trying again
- try {Thread.sleep(300 + 100 * i);} catch (InterruptedException e) {}
+ try {Thread.sleep(300 + 100 * i);} catch (final InterruptedException e) {}
}
}
}
-
- public static BufferedImage getSingleTile(final tileCoordinates tile, int retry) {
+
+ public static BufferedImage getSingleTile(final tileCoordinates tile, final int retry) {
DigestURI tileURL;
try {
tileURL = new DigestURI(tile.url(retry));
@@ -112,8 +111,8 @@ public class OSMTile {
// download resource using the crawler and keep resource in memory if possible
Response entry = null;
try {
- entry = Switchboard.getSwitchboard().loader.load(Switchboard.getSwitchboard().loader.request(tileURL, false, false), CrawlProfile.CacheStrategy.IFEXIST, Long.MAX_VALUE, true);
- } catch (IOException e) {
+ entry = Switchboard.getSwitchboard().loader.load(Switchboard.getSwitchboard().loader.request(tileURL, false, false), CacheStrategy.IFEXIST, Long.MAX_VALUE, true);
+ } catch (final IOException e) {
Log.logWarning("OSMTile", "cannot load: " + e.getMessage());
return null;
}
@@ -130,7 +129,7 @@ public class OSMTile {
}
public static class tileCoordinates {
-
+
int xtile, ytile, zoom;
public tileCoordinates(final double lat, final double lon, final int zoom) {
@@ -139,18 +138,18 @@ public class OSMTile {
this.xtile = (int) Math.floor((lon + 180) / 360 * (1 << zoom));
this.ytile = (int) Math.floor((1 - Math.log(Math.tan(lat * RasterPlotter.PI180) + 1 / Math.cos(lat * RasterPlotter.PI180)) / Math.PI) / 2 * (1 << zoom));
}
-
+
public tileCoordinates(final int xtile, final int ytile, final int zoom) {
this.zoom = zoom;
this.xtile = xtile;
this.ytile = ytile;
}
-
- public String url(int retry) {
+
+ public String url(final int retry) {
// see http://wiki.openstreetmap.org/wiki/Public_Domain_Map
- int hash = (xtile + 7 * ytile + 13 * zoom + retry) % 4;
- String host = (hash == 3) ? "tile.openstreetmap.org" : ((char) ((int)'a' + hash)) + ".tile.openstreetmap.org";
- String url = "http://" + host + "/" + zoom + "/" + xtile + "/" + ytile + ".png";
+ final int hash = (this.xtile + 7 * this.ytile + 13 * this.zoom + retry) % 4;
+ final String host = (hash == 3) ? "tile.openstreetmap.org" : ((char) ('a' + hash)) + ".tile.openstreetmap.org";
+ final String url = "http://" + host + "/" + this.zoom + "/" + this.xtile + "/" + this.ytile + ".png";
//System.out.println("OSM URL = " + url);
return url;
}
diff --git a/source/de/anomic/yacy/yacyClient.java b/source/de/anomic/yacy/yacyClient.java
index 48a77ee51..b42c3a9dd 100644
--- a/source/de/anomic/yacy/yacyClient.java
+++ b/source/de/anomic/yacy/yacyClient.java
@@ -74,6 +74,7 @@ import net.yacy.cora.protocol.ClientIdentification;
import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.http.HTTPClient;
import net.yacy.cora.services.federated.opensearch.SRURSSConnector;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.URIMetadataRow;
import net.yacy.kelondro.data.word.Word;
import net.yacy.kelondro.data.word.WordReference;
@@ -91,13 +92,12 @@ import net.yacy.repository.Blacklist;
import org.apache.http.entity.mime.content.ContentBody;
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.ResultURLs;
import de.anomic.crawler.ResultURLs.EventOrigin;
import de.anomic.search.ContentDomain;
import de.anomic.search.QueryParams;
-import de.anomic.search.RankingProfile;
import de.anomic.search.RankingProcess;
+import de.anomic.search.RankingProfile;
import de.anomic.search.SearchEvent;
import de.anomic.search.Segment;
import de.anomic.search.Switchboard;
@@ -116,16 +116,16 @@ public final class yacyClient {
private static byte[] postToFile(final yacySeedDB seedDB, final String targetHash, final String filename, final Map<String,ContentBody> parts, final int timeout) throws IOException {
return postToFile(seedDB.targetAddress(targetHash), targetHash, filename, parts, timeout);
}
- private static byte[] postToFile(final String targetAddress, String targetPeerHash, final String filename, final Map<String,ContentBody> parts, final int timeout) throws IOException {
+ private static byte[] postToFile(final String targetAddress, final String targetPeerHash, final String filename, final Map<String,ContentBody> parts, final int timeout) throws IOException {
final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
return httpClient.POSTbytes(new MultiProtocolURI("http://" + targetAddress + "/yacy/" + filename), yacySeed.b64Hash2hexHash(targetPeerHash) + ".yacyh", parts, false);
}
-
+
/**
* this is called to enrich the seed information by
* - own address (if peer is behind a nat/router)
* - check peer type (virgin/junior/senior/principal)
- *
+ *
* to do this, we send a 'Hello' to another peer
* this carries the following information:
* 'iam' - own hash
@@ -136,15 +136,15 @@ public final class yacyClient {
* - 'yourip' the ip of the connection peer (we)
* - 'yourtype' the type of this peer that the other peer checked by asking for a specific word
* and the remote seed string
- *
+ *
* one exceptional failure case is when we know the other's peers hash, the other peers responds correctly
* but they appear to be another peer by comparisment of the other peer's hash
* this works of course only if we know the other peer's hash.
- *
- * @return the number of new seeds
+ *
+ * @return the number of new seeds
*/
public static int hello(final yacySeed mySeed, final yacyPeerActions peerActions, final String address, final String otherHash) {
-
+
Map<String, String> result = null;
final String salt = crypt.randomSalt();
try {
@@ -169,7 +169,7 @@ public final class yacyClient {
// try again (go into loop)
result = null;
}
-
+
if (result == null) {
yacyCore.log.logInfo("yacyClient.hello result error: " +
((result == null) ? "result null" : ("result=" + result.toString())));
@@ -186,15 +186,15 @@ public final class yacyClient {
yacyCore.log.logInfo("hello/client 0: rejected contacting seed; too large (" + seed.length() + " > " + yacySeed.maxsize + ")");
} else {
try {
- int p = address.indexOf(':');
+ final int p = address.indexOf(':');
if (p < 0) return -1;
- String host = Domains.dnsResolve(address.substring(0, p)).getHostAddress();
+ final String host = Domains.dnsResolve(address.substring(0, p)).getHostAddress();
otherPeer = yacySeed.genRemoteSeed(seed, salt, false, host);
if (!otherPeer.hash.equals(otherHash)) {
yacyCore.log.logInfo("yacyClient.hello: consistency error: otherPeer.hash = " + otherPeer.hash + ", otherHash = " + otherHash);
return -1; // no success
}
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logInfo("yacyClient.hello: consistency error: other seed bad:" + e.getMessage() + ", seed=" + seed);
return -1; // no success
}
@@ -213,7 +213,7 @@ public final class yacyClient {
// change our seed-type
String mytype = result.get(yacySeed.YOURTYPE);
- if (mytype == null) { mytype = ""; }
+ if (mytype == null) { mytype = ""; }
final yacyAccessible accessible = new yacyAccessible();
if (mytype.equals(yacySeed.PEERTYPE_SENIOR)||mytype.equals(yacySeed.PEERTYPE_PRINCIPAL)) {
accessible.IWasAccessed = true;
@@ -226,7 +226,7 @@ public final class yacyClient {
accessible.lastUpdated = System.currentTimeMillis();
yacyCore.amIAccessibleDB.put(otherHash, accessible);
- /*
+ /*
* If we were reported as junior we have to check if your port forwarding channel is broken
* If this is true we try to reconnect the sch channel to the remote server now.
*/
@@ -264,15 +264,15 @@ public final class yacyClient {
} else {
try {
if (i == 1) {
- int p = address.indexOf(':');
+ final int p = address.indexOf(':');
if (p < 0) return -1;
- String host = Domains.dnsResolve(address.substring(0, p)).getHostAddress();
+ final String host = Domains.dnsResolve(address.substring(0, p)).getHostAddress();
s = yacySeed.genRemoteSeed(seedStr, salt, false, host);
} else {
s = yacySeed.genRemoteSeed(seedStr, salt, false, null);
}
if (peerActions.peerArrival(s, (i == 1))) count++;
- } catch (IOException e) {
+ } catch (final IOException e) {
yacyCore.log.logInfo("hello/client: rejected contacting seed; bad (" + e.getMessage() + ")");
}
}
@@ -283,7 +283,7 @@ public final class yacyClient {
public static yacySeed querySeed(final yacySeed target, final String seedHash) {
// prepare request
final String salt = crypt.randomSalt();
-
+
// send request
try {
final Map<String,ContentBody> parts = yacyNetwork.basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
@@ -291,7 +291,7 @@ public final class yacyClient {
parts.put("env", UTF8.StringBody(seedHash));
final byte[] content = postToFile(target, "query.html", parts, 10000);
final Map<String, String> result = FileUtils.table(content);
-
+
if (result == null || result.isEmpty()) { return null; }
//final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time
return yacySeed.genRemoteSeed(result.get("response"), salt, false, target.getIP());
@@ -304,7 +304,7 @@ public final class yacyClient {
public static int queryRWICount(final yacySeed target, final String wordHash) {
// prepare request
final String salt = crypt.randomSalt();
-
+
// send request
try {
final Map<String,ContentBody> parts = yacyNetwork.basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
@@ -313,7 +313,7 @@ public final class yacyClient {
parts.put("env", UTF8.StringBody(wordHash));
final byte[] content = postToFile(target, "query.html", parts, 5000);
final Map<String, String> result = FileUtils.table(content);
-
+
if (result == null || result.isEmpty()) { return -1; }
return Integer.parseInt(result.get("response"));
} catch (final Exception e) {
@@ -327,12 +327,12 @@ public final class yacyClient {
* @param target
* @return an array of two long: [0] is the count of urls, [1] is a magic
*/
- public static long[] queryUrlCount(final yacySeed target) {
+ public static long[] queryUrlCount(final yacySeed target) {
if (target == null) return new long[]{-1, -1};
-
+
// prepare request
final String salt = crypt.randomSalt();
-
+
// send request
try {
final Map<String,ContentBody> parts = yacyNetwork.basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
@@ -341,7 +341,7 @@ public final class yacyClient {
parts.put("env", UTF8.StringBody(""));
final byte[] content = postToFile(target, "query.html", parts, 5000);
final Map<String, String> result = FileUtils.table(content);
-
+
if (result == null || result.isEmpty()) return new long[]{-1, -1};
final String resp = result.get("response");
if (resp == null) return new long[]{-1, -1};
@@ -358,16 +358,16 @@ public final class yacyClient {
}
public static RSSFeed queryRemoteCrawlURLs(final yacySeedDB seedDB, final yacySeed target, final int maxCount, final long maxTime) {
- // returns a list of
+ // returns a list of
if (target == null) { return null; }
- int targetCount = Integer.parseInt(target.get(yacySeed.RCOUNT, "0"));
+ final int targetCount = Integer.parseInt(target.get(yacySeed.RCOUNT, "0"));
if (targetCount <= 0) {
yacyCore.log.logWarning("yacyClient.queryRemoteCrawlURLs wrong peer '" + target.getName() + "' selected: not enough links available");
return null;
}
// prepare request
final String salt = crypt.randomSalt();
-
+
// send request
try {
/* a long time-out is needed */
@@ -375,7 +375,7 @@ public final class yacyClient {
parts.put("call", UTF8.StringBody("remotecrawl"));
parts.put("count", UTF8.StringBody(Integer.toString(maxCount)));
parts.put("time", UTF8.StringBody(Long.toString(maxTime)));
- // final byte[] result = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/urls.xml"), (int) maxTime, target.getHexHash() + ".yacyh", parts);
+ // final byte[] result = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/urls.xml"), (int) maxTime, target.getHexHash() + ".yacyh", parts);
final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), (int) maxTime);
final byte[] result = httpClient.POSTbytes(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false);
final RSSReader reader = RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, result);
@@ -405,10 +405,10 @@ public final class yacyClient {
return null;
}
}
-
- public static RSSFeed search(final yacySeed targetSeed, String query, CrawlProfile.CacheStrategy verify, boolean global, long timeout, int startRecord, int maximumRecords) throws IOException {
- String address = (targetSeed == null || targetSeed == Switchboard.getSwitchboard().peers.mySeed()) ? "localhost:" + Switchboard.getSwitchboard().getConfig("port", "8090") : targetSeed.getClusterAddress();
- String urlBase = "http://" + address + "/yacysearch.rss";
+
+ public static RSSFeed search(final yacySeed targetSeed, final String query, final CacheStrategy verify, final boolean global, final long timeout, final int startRecord, final int maximumRecords) throws IOException {
+ final String address = (targetSeed == null || targetSeed == Switchboard.getSwitchboard().peers.mySeed()) ? "localhost:" + Switchboard.getSwitchboard().getConfig("port", "8090") : targetSeed.getClusterAddress();
+ final String urlBase = "http://" + address + "/yacysearch.rss";
return SRURSSConnector.loadSRURSS(urlBase, query, timeout, startRecord, maximumRecords, verify, global, null);
}
@@ -427,7 +427,7 @@ public final class yacyClient {
final int count,
final long time,
final int maxDistance,
- final boolean global,
+ final boolean global,
final int partitions,
final yacySeed target,
final Segment indexSegment,
@@ -467,7 +467,7 @@ public final class yacyClient {
}
// computation time
final long totalrequesttime = System.currentTimeMillis() - timestamp;
-
+
// create containers
final int words = wordhashes.length() / Word.commonHashLength;
assert words > 0 : "wordhashes = " + wordhashes;
@@ -475,14 +475,14 @@ public final class yacyClient {
for (int i = 0; i < words; i++) {
try {
container[i] = ReferenceContainer.emptyContainer(Segment.wordReferenceFactory, ASCII.getBytes(wordhashes.substring(i * Word.commonHashLength, (i + 1) * Word.commonHashLength)), count);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
return -1;
}
}
// insert results to containers
- for (URIMetadataRow urlEntry: result.links) {
+ for (final URIMetadataRow urlEntry: result.links) {
// get one single search result
if (urlEntry == null) continue;
assert (urlEntry.hash().length == 12) : "urlEntry.hash() = " + ASCII.String(urlEntry.hash());
@@ -493,7 +493,7 @@ public final class yacyClient {
if (yacyCore.log.isInfo()) yacyCore.log.logInfo("remote search: filtered blacklisted url " + metadata.url() + " from peer " + target.getName());
continue; // block with backlist
}
-
+
final String urlRejectReason = Switchboard.getSwitchboard().crawlStacker.urlInAcceptedDomain(metadata.url());
if (urlRejectReason != null) {
if (yacyCore.log.isInfo()) yacyCore.log.logInfo("remote search: rejected url '" + metadata.url() + "' (" + urlRejectReason + ") from peer " + target.getName());
@@ -501,7 +501,7 @@ public final class yacyClient {
}
// save the url entry
- Reference entry = urlEntry.word();
+ final Reference entry = urlEntry.word();
if (entry == null) {
if (yacyCore.log.isWarning()) yacyCore.log.logWarning("remote search: no word attached from peer " + target.getName() + ", version " + target.getVersion());
continue; // no word attached
@@ -529,12 +529,12 @@ public final class yacyClient {
// System.out.println("--- RECEIVED SNIPPET '" + urlEntry.snippet() + "'");
TextSnippet.snippetsCache.put(wordhashes, ASCII.String(urlEntry.hash()), urlEntry.snippet());
}
-
+
// add the url entry to the word indexes
for (int m = 0; m < words; m++) {
try {
container[m].add(entry);
- } catch (RowSpaceExceededException e) {
+ } catch (final RowSpaceExceededException e) {
Log.logException(e);
break;
}
@@ -547,12 +547,12 @@ public final class yacyClient {
containerCache.add(container[0], false, target.getName() + "/" + target.hash, result.joincount, true);
// insert the containers to the index
- for (ReferenceContainer<WordReference> c: container) try {
+ for (final ReferenceContainer<WordReference> c: container) try {
indexSegment.termIndex().add(c);
- } catch (Exception e) {
+ } catch (final Exception e) {
Log.logException(e);
}
- boolean thisIsASecondarySearch = urlhashes.length() > 0;
+ final boolean thisIsASecondarySearch = urlhashes.length() > 0;
assert !thisIsASecondarySearch || secondarySearchSuperviser == null;
yacyCore.log.logInfo("remote search: peer " + target.getName() + " sent " + container[0].size() + "/" + result.joincount + " references for " + (thisIsASecondarySearch ? "a secondary search" : "joined word queries"));
@@ -566,32 +566,32 @@ public final class yacyClient {
containerCache.addTopic(result.references);
}
}
-
+
// read index abstract
if (secondarySearchSuperviser != null) {
String wordhash;
String whacc = "";
ByteBuffer ci;
int ac = 0;
- for (Map.Entry<byte[], String> abstractEntry: result.indexabstract.entrySet()) {
+ for (final Map.Entry<byte[], String> abstractEntry: result.indexabstract.entrySet()) {
try {
ci = new ByteBuffer(abstractEntry.getValue());
wordhash = ASCII.String(abstractEntry.getKey());
- } catch (OutOfMemoryError e) {
+ } catch (final OutOfMemoryError e) {
Log.logException(e);
continue;
}
whacc += wordhash;
secondarySearchSuperviser.addAbstract(wordhash, WordReferenceFactory.decompressIndex(ci, target.hash));
ac++;
-
+
}
if (ac > 0) {
secondarySearchSuperviser.commitAbstract();
yacyCore.log.logInfo("remote search: peer " + target.getName() + " sent " + ac + " index abstracts for words "+ whacc);
}
}
-
+
// generate statistics
if (yacyCore.log.isFine()) yacyCore.log.logFine(
"SEARCH " + result.urlcount +
@@ -601,9 +601,9 @@ public final class yacyClient {
", references=" + result.references);
return result.urlcount;
}
-
+
public static class SearchResult {
-
+
public String version; // version : application version of responder
public String uptime; // uptime : uptime in seconds of responder
public String fwhop; // hops (depth) of forwards that had been performed to construct this result
@@ -616,9 +616,9 @@ public final class yacyClient {
public String[] references; // search hints, the top-words
public List<URIMetadataRow> links; // LURLs of search
public Map<byte[], String> indexabstract; // index abstracts, a collection of url-hashes per word
-
+
public SearchResult(
- Map<String,ContentBody> parts,
+ final Map<String,ContentBody> parts,
final yacySeed mySeed,
final String wordhashes,
final String excludehashes,
@@ -632,10 +632,10 @@ public final class yacyClient {
final int count,
final long time,
final int maxDistance,
- final boolean global,
+ final boolean global,
final int partitions,
- String hostname,
- String hostaddress,
+ final String hostname,
+ final String hostaddress,
final SearchEvent.SecondarySearchSuperviser secondarySearchSuperviser,
final RankingProfile rankingProfile,
final Bitfield constraint) throws IOException {
@@ -653,13 +653,13 @@ public final class yacyClient {
// global : if "true", then result may consist of answers from other peers
// partitions : number of remote peers that are asked (for evaluation of QPM)
// duetime : maximum time that a peer should spent to create a result
-
+
// send request
Map<String, String> resultMap = null;
String key = "";
- ContentBody keyBody = parts.get("key");
+ final ContentBody keyBody = parts.get("key");
if (keyBody != null) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(20);
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream(20);
keyBody.writeTo(baos);
key = baos.toString();
}
@@ -688,7 +688,7 @@ public final class yacyClient {
final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 60000);
resultMap = FileUtils.table(httpClient.POSTbytes(new MultiProtocolURI("http://" + hostaddress + "/yacy/search.html"), hostname, parts, false));
-
+
// evaluate request result
if (resultMap == null || resultMap.isEmpty()) throw new IOException("resultMap is NULL");
try {
@@ -710,36 +710,36 @@ public final class yacyClient {
this.fwsrc = resultMap.get("fwsrc");
this.fwrec = resultMap.get("fwrec");
// scan the result map for entries with special prefix
- indexcount = new TreeMap<byte[], Integer>(Base64Order.enhancedCoder);
- indexabstract = new TreeMap<byte[], String>(Base64Order.enhancedCoder);
- for (Map.Entry<String, String> entry: resultMap.entrySet()) {
+ this.indexcount = new TreeMap<byte[], Integer>(Base64Order.enhancedCoder);
+ this.indexabstract = new TreeMap<byte[], String>(Base64Order.enhancedCoder);
+ for (final Map.Entry<String, String> entry: resultMap.entrySet()) {
if (entry.getKey().startsWith("indexcount.")) {
- indexcount.put(UTF8.getBytes(entry.getKey().substring(11)), Integer.parseInt(entry.getValue()));
+ this.indexcount.put(UTF8.getBytes(entry.getKey().substring(11)), Integer.parseInt(entry.getValue()));
}
if (entry.getKey().startsWith("indexabstract.")) {
- indexabstract.put(UTF8.getBytes(entry.getKey().substring(14)), entry.getValue());
+ this.indexabstract.put(UTF8.getBytes(entry.getKey().substring(14)), entry.getValue());
}
}
- references = resultMap.get("references").split(",");
+ this.references = resultMap.get("references").split(",");
this.links = new ArrayList<URIMetadataRow>(this.urlcount);
for (int n = 0; n < this.urlcount; n++) {
// get one single search result
- String resultLine = resultMap.get("resource" + n);
+ final String resultLine = resultMap.get("resource" + n);
if (resultLine == null) continue;
- URIMetadataRow urlEntry = URIMetadataRow.importEntry(resultLine);
+ final URIMetadataRow urlEntry = URIMetadataRow.importEntry(resultLine);
if (urlEntry == null) continue;
this.links.add(urlEntry);
}
}
}
-
+
public static Map<String, String> permissionMessage(final yacySeedDB seedDB, final String targetHash) {
// ask for allowed message size and attachement size
// if this replies null, the peer does not answer
-
+
// prepare request
final String salt = crypt.randomSalt();
-
+
// send request
try {
final Map<String,ContentBody> parts = yacyNetwork.basicRequestParts(Switchboard.getSwitchboard(), targetHash, salt);
@@ -775,7 +775,7 @@ public final class yacyClient {
return null;
}
}
-
+
public static Map<String, String> crawlReceipt(final yacySeed mySeed, final yacySeed target, final String process, final String result, final String reason, final URIMetadataRow entry, final String wordhashes) {
assert (target != null);
assert (mySeed != null);
@@ -786,28 +786,28 @@ public final class yacyClient {
negative cases, no retry
unavailable - the resource is not avaiable (a broken link); not found or interrupted
robot - a robot-file has denied to crawl that resource
-
+
negative cases, retry possible
rejected - the peer has rejected to load the resource
dequeue - peer too busy - rejected to crawl
-
+
positive cases with crawling
fill - the resource was loaded and processed
update - the resource was already in database but re-loaded and processed
-
+
positive cases without crawling
known - the resource is already in database, believed to be fresh and not reloaded
stale - the resource was reloaded but not processed because source had no changes
-
+
*/
-
+
// prepare request
final String salt = crypt.randomSalt();
-
+
// determining target address
final String address = target.getClusterAddress();
if (address == null) { return null; }
-
+
// send request
try {
// prepare request
@@ -850,7 +850,7 @@ public final class yacyClient {
// check if we got all necessary urls in the urlCache (only for debugging)
Iterator<WordReference> eenum;
Reference entry;
- for (ReferenceContainer<WordReference> ic: indexes) {
+ for (final ReferenceContainer<WordReference> ic: indexes) {
eenum = ic.entries();
while (eenum.hasNext()) {
entry = eenum.next();
@@ -858,37 +858,37 @@ public final class yacyClient {
if (yacyCore.log.isFine()) yacyCore.log.logFine("DEBUG transferIndex: to-send url hash '" + ASCII.String(entry.urlhash()) + "' is not contained in urlCache");
}
}
- }
-
+ }
+
// transfer the RWI without the URLs
Map<String, String> in = transferRWI(targetSeed, indexes, gzipBody, timeout);
-
+
if (in == null) {
return "no connection from transferRWI";
}
-
+
String result = in.get("result");
if (result == null) {
return "no result from transferRWI";
}
-
+
if (!(result.equals("ok"))) {
return result;
}
-
+
// in now contains a list of unknown hashes
String uhss = in.get("unknownURL");
if (uhss == null) {
return "no unknownURL tag in response";
}
yacyChannel.channels(yacyChannel.DHTSEND).addMessage(new RSSMessage("Sent " + indexes.size() + " RWIs to " + targetSeed.getName(), "", targetSeed.hash));
-
+
uhss = uhss.trim();
if (uhss.length() == 0 || uhss.equals(",")) { return null; } // all url's known, we are ready here
-
+
final String[] uhs = uhss.split(",");
if (uhs.length == 0) { return null; } // all url's known
-
+
// extract the urlCache from the result
final URIMetadataRow[] urls = new URIMetadataRow[uhs.length];
for (int i = 0; i < uhs.length; i++) {
@@ -897,23 +897,23 @@ public final class yacyClient {
if (yacyCore.log.isFine()) yacyCore.log.logFine("DEBUG transferIndex: requested url hash '" + uhs[i] + "', unknownURL='" + uhss + "'");
}
}
-
+
in = transferURL(targetSeed, urls, gzipBody, timeout);
-
+
if (in == null) {
return "no connection from transferURL";
}
-
+
result = in.get("result");
if (result == null) {
return "no result from transferURL";
}
-
+
if (!result.equals("ok")) {
return result;
- }
+ }
yacyChannel.channels(yacyChannel.DHTSEND).addMessage(new RSSMessage("Sent " + uhs.length + " URLs to peer " + targetSeed.getName(), "", targetSeed.hash));
-
+
return null;
}
@@ -927,22 +927,22 @@ public final class yacyClient {
// prepare post values
final String salt = crypt.randomSalt();
-
+
// enabling gzip compression for post request body
if (gzipBody && (targetSeed.getVersion() < yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS_CHUNKED)) {
gzipBody = false;
}
-
+
int indexcount = 0;
final StringBuilder entrypost = new StringBuilder(indexes.size() * 73);
Iterator<WordReference> eenum;
Reference entry;
- for (ReferenceContainer<WordReference> ic: indexes) {
+ for (final ReferenceContainer<WordReference> ic: indexes) {
eenum = ic.entries();
while (eenum.hasNext()) {
entry = eenum.next();
- entrypost.append(ASCII.String(ic.getTermHash()))
- .append(entry.toPropertyForm())
+ entrypost.append(ASCII.String(ic.getTermHash()))
+ .append(entry.toPropertyForm())
.append(serverCore.CRLF_STRING);
indexcount++;
}
@@ -965,7 +965,7 @@ public final class yacyClient {
final byte[] content = httpClient.POSTbytes(new MultiProtocolURI("http://" + address + "/yacy/transferRWI.html"), targetSeed.getHexHash() + ".yacyh", parts, gzipBody);
final Iterator<String> v = FileUtils.strings(content);
// this should return a list of urlhashes that are unknown
-
+
final Map<String, String> result = FileUtils.table(v);
// return the transfered index data in bytes (for debugging only)
result.put("indexPayloadSize", Integer.toString(entrypost.length()));
@@ -984,18 +984,18 @@ public final class yacyClient {
// prepare post values
final String salt = crypt.randomSalt();
final Map<String,ContentBody> parts = yacyNetwork.basicRequestParts(Switchboard.getSwitchboard(), targetSeed.hash, salt);
-
+
// enabling gzip compression for post request body
if (gzipBody && (targetSeed.getVersion() < yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS_CHUNKED)) {
gzipBody = false;
}
-
+
String resource;
int urlc = 0;
int urlPayloadSize = 0;
- for (int i = 0; i < urls.length; i++) {
- if (urls[i] != null) {
- resource = urls[i].toString();
+ for (final URIMetadataRow url : urls) {
+ if (url != null) {
+ resource = url.toString();
//System.out.println("*** DEBUG resource = " + resource);
if (resource != null && resource.indexOf(0) == -1) {
parts.put("url" + urlc, UTF8.StringBody(resource));
@@ -1010,10 +1010,10 @@ public final class yacyClient {
final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
final byte[] content = httpClient.POSTbytes(new MultiProtocolURI("http://" + address + "/yacy/transferURL.html"), targetSeed.getHexHash() + ".yacyh", parts, gzipBody);
final Iterator<String> v = FileUtils.strings(content);
-
+
final Map<String, String> result = FileUtils.table(v);
// return the transfered url data in bytes (for debugging only)
- result.put("urlPayloadSize", Integer.toString(urlPayloadSize));
+ result.put("urlPayloadSize", Integer.toString(urlPayloadSize));
return result;
} catch (final Exception e) {
yacyCore.log.logWarning("yacyClient.transferURL to " + address + " error: " + e.getMessage());
@@ -1023,10 +1023,10 @@ public final class yacyClient {
public static Map<String, String> getProfile(final yacySeed targetSeed) {
// ReferenceContainerCache<HostReference> ref = loadIDXHosts(targetSeed);
-
+
// this post a message to the remote message board
final String salt = crypt.randomSalt();
-
+
String address = targetSeed.getClusterAddress();
if (address == null) { address = "localhost:8090"; }
try {
@@ -1040,18 +1040,18 @@ public final class yacyClient {
return null;
}
}
-
+
public static ReferenceContainerCache<HostReference> loadIDXHosts(final yacySeed target) {
- ReferenceContainerCache<HostReference> index = new ReferenceContainerCache<HostReference>(WebStructureGraph.hostReferenceFactory, Base64Order.enhancedCoder, 6);
+ final ReferenceContainerCache<HostReference> index = new ReferenceContainerCache<HostReference>(WebStructureGraph.hostReferenceFactory, Base64Order.enhancedCoder, 6);
// check if the host supports this protocol
if (target.getRevision() < migration.IDX_HOST) {
// if the protocol is not supported then we just return an empty host reference container
return index;
}
-
+
// prepare request
final String salt = crypt.randomSalt();
-
+
// send request
try {
final Map<String,ContentBody> parts = yacyNetwork.basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
@@ -1061,7 +1061,7 @@ public final class yacyClient {
yacyCore.log.logWarning("yacyClient.loadIDXHosts error: empty result");
return null;
}
- JSONObject json = new JSONObject(new JSONTokener(new InputStreamReader(new ByteArrayInputStream(content))));
+ final JSONObject json = new JSONObject(new JSONTokener(new InputStreamReader(new ByteArrayInputStream(content))));
/* the json has the following form:
{
"version":"#[version]#",
@@ -1074,23 +1074,23 @@ public final class yacyClient {
}
}
*/
- JSONObject idx = json.getJSONObject("idx");
+ final JSONObject idx = json.getJSONObject("idx");
// iterate over all references
- Iterator<String> termIterator = idx.keys();
+ final Iterator<String> termIterator = idx.keys();
String term;
while (termIterator.hasNext()) {
term = termIterator.next();
- JSONArray references = idx.getJSONArray(term);
+ final JSONArray references = idx.getJSONArray(term);
// iterate until we get an exception or null
int c = 0;
String reference;
- ReferenceContainer<HostReference> referenceContainer = new ReferenceContainer<HostReference>(WebStructureGraph.hostReferenceFactory, UTF8.getBytes(term));
+ final ReferenceContainer<HostReference> referenceContainer = new ReferenceContainer<HostReference>(WebStructureGraph.hostReferenceFactory, UTF8.getBytes(term));
try {
while ((reference = references.getString(c++)) != null) {
//System.out.println("REFERENCE: " + reference);
referenceContainer.add(new HostReference(reference));
}
- } catch (JSONException e) {} // this finishes the iteration
+ } catch (final JSONException e) {} // this finishes the iteration
index.add(referenceContainer);
}
return index;
@@ -1100,7 +1100,7 @@ public final class yacyClient {
}
}
-
+
public static void main(final String[] args) {
if (args.length > 2) {
@@ -1110,14 +1110,14 @@ public final class yacyClient {
// third arg: search word or file name with list of search words
// i.e. /Data/workspace1/yacy/ localhost:8090 /Data/workspace1/yacy/test/words/searchtest.words
System.out.println("yacyClient Test");
- File searchwordfile = new File(args[2]);
- List<String> searchlines = new ArrayList<String>();
+ final File searchwordfile = new File(args[2]);
+ final List<String> searchlines = new ArrayList<String>();
if (searchwordfile.exists()) {
Iterator<String> i;
try {
i = FileUtils.strings(FileUtils.read(searchwordfile));
while (i.hasNext()) searchlines.add(i.next());
- } catch (IOException e) {
+ } catch (final IOException e) {
e.printStackTrace();
System.exit(-1);
}
@@ -1126,7 +1126,7 @@ public final class yacyClient {
}
for (final String line: searchlines) {
final byte[] wordhashe = ASCII.getBytes(QueryParams.hashSet2hashString(Word.words2hashesHandles(QueryParams.cleanQuery(line)[0])));
- long time = System.currentTimeMillis();
+ final long time = System.currentTimeMillis();
SearchResult result;
try {
result = new SearchResult(
@@ -1144,18 +1144,18 @@ public final class yacyClient {
10, // count,
3000, // time,
1000, // maxDistance,
- true, //global,
+ true, //global,
16, // partitions,
"", args[1],
null, //secondarySearchSuperviser,
new RankingProfile(ContentDomain.TEXT), // rankingProfile,
null // constraint);
);
- for (URIMetadataRow link: result.links) {
+ for (final URIMetadataRow link: result.links) {
System.out.println(link.metadata().url().toNormalform(true, false));
System.out.println(link.snippet());
}
- } catch (IOException e) {
+ } catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -1187,13 +1187,13 @@ public final class yacyClient {
final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
res = httpClient.POSTbytes(url, vhost, newpost, true);
System.out.println(UTF8.String(res));
- } catch (IOException e1) {
+ } catch (final IOException e1) {
Log.logException(e1);
}
}
try {
net.yacy.cora.protocol.http.HTTPClient.closeConnectionManager();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
Log.logException(e);
}
}
diff --git a/source/de/anomic/yacy/yacyRelease.java b/source/de/anomic/yacy/yacyRelease.java
index f91ea80af..a4276acb8 100644
--- a/source/de/anomic/yacy/yacyRelease.java
+++ b/source/de/anomic/yacy/yacyRelease.java
@@ -1,4 +1,4 @@
-// yacyRelease.java
+// yacyRelease.java
// ----------------
// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 27.04.2007 on http://yacy.net
@@ -10,7 +10,7 @@
// $LastChangedBy$
//
// LICENSE
-//
+//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
@@ -51,14 +51,13 @@ import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.protocol.ResponseHeader;
import net.yacy.cora.protocol.http.HTTPClient;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.kelondro.io.CharBuffer;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.util.OS;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.search.Switchboard;
import de.anomic.server.serverCore;
import de.anomic.tools.CryptoLib;
@@ -73,50 +72,50 @@ public final class yacyRelease extends yacyVersion {
private static Map<yacyUpdateLocation, DevAndMainVersions> latestReleases = new ConcurrentHashMap<yacyUpdateLocation, DevAndMainVersions>();
public final static List<yacyUpdateLocation> latestReleaseLocations = new ArrayList<yacyUpdateLocation>(); // will be initialized with value in defaults/yacy.network.freeworld.unit
public static String startParameter = "";
-
+
private MultiProtocolURI url;
private File releaseFile;
-
+
private PublicKey publicKey;
-
+
public yacyRelease(final MultiProtocolURI url) {
super(url.getFileName(), url.getHost());
this.url = url;
}
-
- public yacyRelease(final MultiProtocolURI url, PublicKey publicKey) {
+
+ public yacyRelease(final MultiProtocolURI url, final PublicKey publicKey) {
this(url);
this.publicKey = publicKey;
}
-
+
public yacyRelease(final File releaseFile) {
super(releaseFile.getName(), null);
this.releaseFile = releaseFile;
}
public MultiProtocolURI getUrl() {
- return url;
+ return this.url;
}
-
+
public static final yacyRelease rulebasedUpdateInfo(final boolean manual) {
// according to update properties, decide if we should retrieve update information
// if true, the release that can be obtained is returned.
// if false, null is returned
final Switchboard sb = Switchboard.getSwitchboard();
-
+
// check if release was installed by packagemanager
if (yacyBuildProperties.isPkgManager()) {
yacyCore.log.logInfo("rulebasedUpdateInfo: package manager is used for update");
return null;
}
-
+
// check if update process allows update retrieve
final String process = sb.getConfig("update.process", "manual");
if ((!manual) && (!process.equals("auto"))) {
yacyCore.log.logInfo("rulebasedUpdateInfo: not an automatic update selected");
return null; // no, its a manual or guided process
}
-
+
// check if the last retrieve time is a minimum time ago
final long cycle = Math.max(1, sb.getConfigLong("update.cycle", 168)) * 60 * 60 * 1000; // update.cycle is hours
final long timeLookup = sb.getConfigLong("update.time.lookup", System.currentTimeMillis());
@@ -124,7 +123,7 @@ public final class yacyRelease extends yacyVersion {
yacyCore.log.logInfo("rulebasedUpdateInfo: too early for a lookup for a new release (timeLookup = " + timeLookup + ", cycle = " + cycle + ", now = " + System.currentTimeMillis() + ")");
return null; // no we have recently made a lookup
}
-
+
// check if we know that there is a release that is more recent than that which we are using
final DevAndMainVersions releases = yacyRelease.allReleases(true, sb.getConfig("update.onlySignedFiles", "1").equals("1"));
final yacyRelease latestmain = (releases.main.isEmpty()) ? null : releases.main.last();
@@ -136,7 +135,7 @@ public final class yacyRelease extends yacyVersion {
blacklist = "...[123]";
sb.setConfig("update.blacklist", blacklist);
}
-
+
if ((manual) || (concept.equals("any"))) {
// return a dev-release or a main-release
if ((latestdev != null) &&
@@ -180,30 +179,30 @@ public final class yacyRelease extends yacyVersion {
yacyCore.log.logInfo(
"rulebasedUpdateInfo: latest main " + latestmain.getName() +
" is not more recent than installed release (2) " + thisVersion().getName());
- return null;
+ return null;
}
return latestmain;
}
yacyCore.log.logInfo("rulebasedUpdateInfo: failed to find more recent release");
return null;
}
-
+
public static DevAndMainVersions allReleases(final boolean force, final boolean onlySigned) {
// join the release infos
final TreeSet<yacyRelease> alldev = new TreeSet<yacyRelease>();
final TreeSet<yacyRelease> allmain = new TreeSet<yacyRelease>();
- for (yacyUpdateLocation updateLocation : latestReleaseLocations) {
+ for (final yacyUpdateLocation updateLocation : latestReleaseLocations) {
if(!onlySigned || updateLocation.getPublicKey() != null) {
- DevAndMainVersions versions = getReleases(updateLocation, force);
+ final DevAndMainVersions versions = getReleases(updateLocation, force);
if (versions != null && versions.dev != null) alldev.addAll(versions.dev);
if (versions != null && versions.main != null) allmain.addAll(versions.main);
}
}
return new DevAndMainVersions(alldev, allmain);
}
-
+
/**
- * get all Releases from update location using cache
+ * get all Releases from update location using cache
* @param location Update location
* @param force when true, don't fetch from cache
* @return
@@ -222,31 +221,31 @@ public final class yacyRelease extends yacyVersion {
}
return locLatestRelease;
}
-
+
/**
* get all releases from update location
* @param location
* @return
*/
- private static DevAndMainVersions allReleaseFrom(yacyUpdateLocation location) {
+ private static DevAndMainVersions allReleaseFrom(final yacyUpdateLocation location) {
// retrieves the latest info about releases
// this is done by contacting a release location,
// parsing the content and filtering+parsing links
// returns the version info if successful, null otherwise
ContentScraper scraper;
try {
- scraper = Switchboard.getSwitchboard().loader.parseResource(location.getLocationURL(), CrawlProfile.CacheStrategy.NOCACHE);
+ scraper = Switchboard.getSwitchboard().loader.parseResource(location.getLocationURL(), CacheStrategy.NOCACHE);
} catch (final IOException e) {
return null;
}
-
+
// analyze links in scraper resource, and find link to latest release in it
final Map<MultiProtocolURI, Properties> anchors = scraper.getAnchors(); // a url (String) / name (String) relation
final TreeSet<yacyRelease> mainReleases = new TreeSet<yacyRelease>();
final TreeSet<yacyRelease> devReleases = new TreeSet<yacyRelease>();
- for (MultiProtocolURI url : anchors.keySet()) {
+ for (final MultiProtocolURI url : anchors.keySet()) {
try {
- yacyRelease release = new yacyRelease(url, location.getPublicKey());
+ final yacyRelease release = new yacyRelease(url, location.getPublicKey());
//System.out.println("r " + release.toAnchor());
if (release.isMainRelease()) {
mainReleases.add(release);
@@ -263,7 +262,7 @@ public final class yacyRelease extends yacyVersion {
Switchboard.getSwitchboard().setConfig("update.time.lookup", System.currentTimeMillis());
return new DevAndMainVersions(devReleases, mainReleases);
}
-
+
public static final class DevAndMainVersions {
public TreeSet<yacyRelease> dev, main;
public DevAndMainVersions(final TreeSet<yacyRelease> dev, final TreeSet<yacyRelease> main) {
@@ -272,7 +271,7 @@ public final class yacyRelease extends yacyVersion {
}
}
-
+
/**
* <p>download this release and if public key is know, download signature and check it.
* <p>The signature is named $releaseurl.sig and contains the base64 encoded signature
@@ -285,25 +284,25 @@ public final class yacyRelease extends yacyVersion {
// setup httpClient
final RequestHeader reqHeader = new RequestHeader();
reqHeader.put(HeaderFramework.USER_AGENT, ClientIdentification.getUserAgent());
-
- final String name = this.getUrl().getFileName();
+
+ final String name = getUrl().getFileName();
byte[] signatureBytes = null;
-
+
final HTTPClient client = new HTTPClient();
client.setTimout(6000);
client.setHeader(reqHeader.entrySet());
-
+
// download signature first, if public key is available
try {
if (this.publicKey != null) {
- final byte[] signatureData = client.GETbytes(this.getUrl().toString() + ".sig");
+ final byte[] signatureData = client.GETbytes(getUrl().toString() + ".sig");
if (signatureData == null) {
- Log.logWarning("yacyVersion", "download of signature " + this.getUrl().toString() + " failed. ignoring signature file.");
+ Log.logWarning("yacyVersion", "download of signature " + getUrl().toString() + " failed. ignoring signature file.");
}
else signatureBytes = Base64Order.standardCoder.decode(UTF8.String(signatureData).trim());
}
client.setTimout(120000);
- client.GET(this.getUrl().toString());
+ client.GET(getUrl().toString());
final ResponseHeader header = new ResponseHeader(client.getHttpResponse().getAllHeaders());
final boolean unzipped = header.gzip() && (header.mime().toLowerCase().equals("application/x-tar")); // if true, then the httpc has unzipped the file
@@ -316,30 +315,30 @@ public final class yacyRelease extends yacyVersion {
// copy to file and check signature
SignatureOutputStream verifyOutput = null;
try {
- verifyOutput = new SignatureOutputStream(new FileOutputStream(download), CryptoLib.signAlgorithm, publicKey);
+ verifyOutput = new SignatureOutputStream(new FileOutputStream(download), CryptoLib.signAlgorithm, this.publicKey);
client.writeTo(new BufferedOutputStream(verifyOutput));
if (!verifyOutput.verify(signatureBytes)) throw new IOException("Bad Signature!");
- } catch (NoSuchAlgorithmException e) {
+ } catch (final NoSuchAlgorithmException e) {
throw new IOException("No such algorithm");
- } catch (SignatureException e) {
+ } catch (final SignatureException e) {
throw new IOException("Signature exception");
} finally {
if (verifyOutput != null)
verifyOutput.close();
}
// Save signature
- File signatureFile = new File(download.getAbsoluteFile() + ".sig");
+ final File signatureFile = new File(download.getAbsoluteFile() + ".sig");
FileUtils.copy(UTF8.getBytes(Base64Order.standardCoder.encode(signatureBytes)), signatureFile);
if ((!signatureFile.exists()) || (signatureFile.length() == 0)) throw new IOException("create signature file failed");
} else {
// just copy into file
client.writeTo(new BufferedOutputStream(new FileOutputStream(download)));
}
- if ((!download.exists()) || (download.length() == 0)) throw new IOException("wget of url " + this.getUrl() + " failed");
+ if ((!download.exists()) || (download.length() == 0)) throw new IOException("wget of url " + getUrl() + " failed");
} catch (final IOException e) {
// Saving file failed, abort download
- Log.logSevere("yacyVersion", "download of " + this.getName() + " failed: " + e.getMessage());
+ Log.logSevere("yacyVersion", "download of " + getName() + " failed: " + e.getMessage());
if (download != null && download.exists()) {
FileUtils.deletedelete(download);
if (download.exists()) Log.logWarning("yacyVersion", "could not delete file "+ download);
@@ -348,17 +347,17 @@ public final class yacyRelease extends yacyVersion {
} finally {
try {
client.finish();
- } catch (IOException e) {
- Log.logSevere("yacyVersion", "finish of " + this.getName() + " failed: " + e.getMessage());
+ } catch (final IOException e) {
+ Log.logSevere("yacyVersion", "finish of " + getName() + " failed: " + e.getMessage());
}
}
this.releaseFile = download;
Switchboard.getSwitchboard().setConfig("update.time.download", System.currentTimeMillis());
return this.releaseFile;
}
-
+
public boolean checkSignature() {
- if(releaseFile != null) {
+ if(this.releaseFile != null) {
try {
final CharBuffer signBuffer = new CharBuffer(getSignatureFile());
final byte[] signByteBuffer = Base64Order.standardCoder.decode(signBuffer.toString().trim());
@@ -366,15 +365,15 @@ public final class yacyRelease extends yacyVersion {
for(final yacyUpdateLocation updateLocation : latestReleaseLocations) {
try {
if(cl.verifySignature(updateLocation.getPublicKey(),
- new FileInputStream(releaseFile), signByteBuffer)) {
+ new FileInputStream(this.releaseFile), signByteBuffer)) {
return true;
}
- } catch (InvalidKeyException e) {
- } catch (SignatureException e) {
+ } catch (final InvalidKeyException e) {
+ } catch (final SignatureException e) {
}
}
- } catch (IOException e1) {
- } catch (NoSuchAlgorithmException e) {
+ } catch (final IOException e1) {
+ } catch (final NoSuchAlgorithmException e) {
}
}
@@ -480,8 +479,8 @@ public final class yacyRelease extends yacyVersion {
String scriptFileName = null;
if (OS.isMacArchitecture) {
// overwrite Info.plist for Mac Applications (this holds the class paths and can be seen as the start script)
- File InfoPlistSource = new File(sb.getDataPath(), "DATA/RELEASE/yacy/addon/YaCy.app/Contents/Info.plist");
- File InfoPlistDestination = new File(sb.getAppPath(), "addon/YaCy.app/Contents/Info.plist");
+ final File InfoPlistSource = new File(sb.getDataPath(), "DATA/RELEASE/yacy/addon/YaCy.app/Contents/Info.plist");
+ final File InfoPlistDestination = new File(sb.getAppPath(), "addon/YaCy.app/Contents/Info.plist");
if (InfoPlistSource.exists() && InfoPlistDestination.exists()) {
FileUtils.copy(InfoPlistSource, InfoPlistDestination);
Log.logInfo("UPDATE", "replaced Info.plist");
@@ -492,13 +491,13 @@ public final class yacyRelease extends yacyVersion {
String starterFile = "startYACY_debug.bat";
if (startType.exists()) starterFile = "startYACY.bat"; // startType noconsole
if (startParameter.startsWith("-gui")) starterFile += " " + startParameter;
- script =
+ script =
"@echo off" + serverCore.LF_STRING +
"title YaCy updater" + serverCore.LF_STRING +
"set loading=YACY UPDATER" + serverCore.LF_STRING +
"echo %loading%" + serverCore.LF_STRING +
"cd \"" + sb.getDataPath().toString() + "/DATA/RELEASE/".replace("/", File.separator) + "\"" + serverCore.LF_STRING +
-
+
":WAIT" + serverCore.LF_STRING +
"set loading=%loading%." + serverCore.LF_STRING +
"cls" + serverCore.LF_STRING +
@@ -517,11 +516,11 @@ public final class yacyRelease extends yacyVersion {
// /S delete tree
// /Q don't ask
"goto END" + serverCore.LF_STRING +
-
+
":NODATA" + serverCore.LF_STRING +
"echo YACY UPDATER ERROR: NO UPDATE SOURCE FILES ON FILESYSTEM" + serverCore.LF_STRING +
"pause" + serverCore.LF_STRING +
-
+
":END" + serverCore.LF_STRING +
"cd \"" + sb.getAppPath().toString() + "\"" + serverCore.LF_STRING +
"start /MIN CMD /C " + starterFile + serverCore.LF_STRING;
@@ -542,7 +541,7 @@ public final class yacyRelease extends yacyVersion {
"nohup ./startYACY.sh " + (startParameter.startsWith("-gui") ? startParameter : "") + " > /dev/null" + serverCore.LF_STRING;
scriptFileName = "update.sh";
}
- final File scriptFile = new File(sb.getDataPath(), "DATA/RELEASE/".replace("/", File.separator) + scriptFileName);
+ final File scriptFile = new File(sb.getDataPath(), "DATA/RELEASE/".replace("/", File.separator) + scriptFileName);
OS.deployScript(scriptFile, script);
Log.logInfo("UPDATE", "wrote update-script to " + scriptFile.getAbsolutePath());
OS.execAsynchronous(scriptFile);
@@ -553,7 +552,7 @@ public final class yacyRelease extends yacyVersion {
Log.logSevere("UPDATE", "update failed", e);
}
}
-
+
public static void main(final String[] args) {
System.out.println(thisVersion());
final float base = (float) 0.53;
@@ -567,40 +566,40 @@ public final class yacyRelease extends yacyVersion {
/**
* keep only releases of last month (minimum latest and 1 main (maybe the same))
- *
+ *
* @param filesPath where all downloaded files reside
- * @param deleteAfterDays
+ * @param deleteAfterDays
*/
public static void deleteOldDownloads(final File filesPath, final int deleteAfterDays) {
// list downloaded releases
yacyVersion release;
final String[] downloaded = filesPath.list();
-
+
// parse all filenames and put them in a sorted set
final SortedSet<yacyVersion> downloadedreleases = new TreeSet<yacyVersion>();
- for (int j = 0; j < downloaded.length; j++) {
+ for (final String element : downloaded) {
try {
- release = new yacyVersion(downloaded[j], null);
+ release = new yacyVersion(element, null);
downloadedreleases.add(release);
} catch (final RuntimeException e) {
// not a valid release
}
}
-
+
// if we have some files
if (!downloadedreleases.isEmpty()) {
Log.logFine("STARTUP", "deleting downloaded releases older than "+ deleteAfterDays +" days");
-
+
// keep latest version
final yacyVersion latest = downloadedreleases.last();
downloadedreleases.remove(latest);
// if latest is a developer release, we also keep a main release
final boolean keepMain = !latest.isMainRelease();
-
+
// remove old files
final long now = System.currentTimeMillis();
final long deleteAfterMillis = deleteAfterDays * 24L * 60 * 60000;
-
+
String lastMain = null;
String filename;
for (final yacyVersion aVersion : downloadedreleases) {
@@ -626,17 +625,17 @@ public final class yacyRelease extends yacyVersion {
}
}
}
-
+
public File getReleaseFile() {
- return releaseFile;
+ return this.releaseFile;
}
-
+
public File getSignatureFile() {
- return new File(releaseFile.getAbsoluteFile() + ".sig");
+ return new File(this.releaseFile.getAbsoluteFile() + ".sig");
}
public PublicKey getPublicKey() {
- return publicKey;
+ return this.publicKey;
}
}
diff --git a/source/net/yacy/cora/protocol/Domains.java b/source/net/yacy/cora/protocol/Domains.java
index bfd78fc4c..e0fdf00f8 100644
--- a/source/net/yacy/cora/protocol/Domains.java
+++ b/source/net/yacy/cora/protocol/Domains.java
@@ -11,12 +11,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -46,7 +46,6 @@ import java.util.regex.Pattern;
import net.yacy.cora.storage.ARC;
import net.yacy.cora.storage.ConcurrentARC;
import net.yacy.cora.storage.KeyList;
-import net.yacy.kelondro.util.MemoryControl;
public class Domains {
@@ -55,17 +54,17 @@ public class Domains {
private static final int MAX_NAME_CACHE_HIT_SIZE = 20000;
private static final int MAX_NAME_CACHE_MISS_SIZE = 20000;
private static final int CONCURRENCY_LEVEL = Runtime.getRuntime().availableProcessors() + 1;
-
+
// a dns cache
private static final ARC<String, InetAddress> NAME_CACHE_HIT = new ConcurrentARC<String, InetAddress>(MAX_NAME_CACHE_HIT_SIZE, CONCURRENCY_LEVEL);
private static final ARC<String, String> NAME_CACHE_MISS = new ConcurrentARC<String, String>(MAX_NAME_CACHE_MISS_SIZE, CONCURRENCY_LEVEL);
private static final ConcurrentHashMap<String, Object> LOOKUP_SYNC = new ConcurrentHashMap<String, Object>();
private static List<Pattern> nameCacheNoCachingPatterns = Collections.synchronizedList(new LinkedList<Pattern>());
private static final List<Pattern> LOCALHOST_PATTERNS = makePatterns(LOCAL_PATTERNS);
-
+
/**
* ! ! ! A T T E N T I O N A T T E N T I O N A T T E N T I O N ! ! !
- *
+ *
* Do not move a TLD to another group (if you do not exactly know what you
* are doing)! Because it will change the hash of the url!
*/
@@ -425,20 +424,20 @@ public class Domains {
insertTLDProps(TLD_Generic, TLD_Generic_ID);
// the id=7 is used to flag local addresses
}
-
+
private static KeyList globalHosts = null;
private static boolean noLocalCheck = false;
- public static void init(File globalHostsnameCache) {
+ public static void init(final File globalHostsnameCache) {
if (globalHostsnameCache == null) {
globalHosts = null;
} else try {
globalHosts = new KeyList(globalHostsnameCache);
- } catch (IOException e) {
+ } catch (final IOException e) {
globalHosts = null;
}
}
-
+
/**
* the isLocal check can be switched off to gain a better crawling speed.
* however, if the check is switched off, then ALL urls are considered as local
@@ -447,14 +446,14 @@ public class Domains {
* Bad usage will make peers inoperable.
* @param v
*/
- public static void setNoLocalCheck(boolean v) {
+ public static void setNoLocalCheck(final boolean v) {
noLocalCheck = v;
}
public static void close() {
- if (globalHosts != null) try {globalHosts.close();} catch (IOException e) {}
+ if (globalHosts != null) try {globalHosts.close();} catch (final IOException e) {}
}
-
+
/**
* Does an DNS-Check to resolve a hostname to an IP.
*
@@ -464,23 +463,23 @@ public class Domains {
public static InetAddress dnsResolveFromCache(String host) throws UnknownHostException {
if ((host == null) || host.isEmpty()) return null;
host = host.toLowerCase().trim();
-
+
// try to simply parse the address
InetAddress ip = parseInetAddress(host);
if (ip != null) return ip;
-
+
// trying to resolve host by doing a name cache lookup
ip = NAME_CACHE_HIT.get(host);
if (ip != null) return ip;
-
+
if (NAME_CACHE_MISS.containsKey(host)) return null;
throw new UnknownHostException("host not in cache");
}
-
+
public static void setNoCachingPatterns(final String patternList) {
nameCacheNoCachingPatterns = makePatterns(patternList);
}
-
+
public static List<Pattern> makePatterns(final String patternList) {
final String[] entries = (patternList != null) ? patternList.split(",") : new String[0];
final List<Pattern> patterns = new ArrayList<Pattern>(entries.length);
@@ -512,19 +511,21 @@ public class Domains {
}
*/
}
-
+
public static InetAddress dnsResolve(String host) {
if ((host == null) || (host.length() == 0)) return null;
host = host.toLowerCase().trim();
// try to simply parse the address
InetAddress ip = parseInetAddress(host);
if (ip != null) return ip;
-
+
+ /*
if (MemoryControl.shortStatus()) {
NAME_CACHE_HIT.clear();
NAME_CACHE_MISS.clear();
}
-
+ */
+
// try to resolve host by doing a name cache lookup
ip = NAME_CACHE_HIT.get(host);
if (ip != null) {
@@ -535,7 +536,7 @@ public class Domains {
//System.out.println("DNSLOOKUP-CACHE-MISS(CONC) " + host);
return null;
}
-
+
// call dnsResolveNetBased(host) using concurrency to interrupt execution in case of a time-out
final Object sync_obj_new = new Object();
Object sync_obj = LOOKUP_SYNC.putIfAbsent(host, sync_obj_new);
@@ -553,7 +554,7 @@ public class Domains {
LOOKUP_SYNC.remove(host);
return null;
}
-
+
// do the dns lookup on the dns server
//if (!matchesList(host, nameCacheNoCachingPatterns)) System.out.println("DNSLOOKUP " + host);
try {
@@ -565,29 +566,29 @@ public class Domains {
LOOKUP_SYNC.remove(host);
return null;
}
-
+
if (ip != null && !ip.isLoopbackAddress() && !matchesList(host, nameCacheNoCachingPatterns)) {
// add new ip cache entries
NAME_CACHE_HIT.insertIfAbsent(host, ip);
-
+
// add also the isLocal host name caches
- boolean localp = ip.isAnyLocalAddress() || ip.isLinkLocalAddress() || ip.isSiteLocalAddress();
+ final boolean localp = ip.isAnyLocalAddress() || ip.isLinkLocalAddress() || ip.isSiteLocalAddress();
if (localp) {
localHostNames.add(host);
} else {
- if (globalHosts != null) try {globalHosts.add(host);} catch (IOException e) {}
+ if (globalHosts != null) try {globalHosts.add(host);} catch (final IOException e) {}
}
}
LOOKUP_SYNC.remove(host);
return ip;
}
}
-
+
private final static Pattern dotPattern = Pattern.compile("\\.");
-
+
public static final InetAddress parseInetAddress(String ip) {
if (ip == null || ip.length() < 8) return null;
- if (ip.equals("0:0:0:0:0:0:0:1%0")) ip = "127.0.0.1";
+ if (ip.equals("0:0:0:0:0:0:0:1%0")) ip = "127.0.0.1";
final String[] ips = dotPattern.split(ip);
if (ips.length != 4) return null;
final byte[] ipb = new byte[4];
@@ -605,7 +606,7 @@ public class Domains {
return null;
}
}
-
+
/**
* Returns the number of entries in the nameCacheHit map
*
@@ -619,19 +620,19 @@ public class Domains {
return NAME_CACHE_MISS.size();
}
- private static String localHostName = "127.0.0.1";
+ private static String localHostName = "127.0.0.1";
private static Set<InetAddress> localHostAddresses = new HashSet<InetAddress>();
private static Set<String> localHostNames = new HashSet<String>();
static {
try {
- InetAddress localHostAddress = InetAddress.getLocalHost();
+ final InetAddress localHostAddress = InetAddress.getLocalHost();
if (localHostAddress != null) localHostAddresses.add(localHostAddress);
- } catch (UnknownHostException e) {}
+ } catch (final UnknownHostException e) {}
try {
final InetAddress[] moreAddresses = InetAddress.getAllByName(localHostName);
if (moreAddresses != null) localHostAddresses.addAll(Arrays.asList(moreAddresses));
- } catch (UnknownHostException e) {}
-
+ } catch (final UnknownHostException e) {}
+
// to get the local host name, a dns lookup is necessary.
// if such a lookup blocks, it can cause that the static initiatializer does not finish fast
// therefore we start the host name lookup as concurrent thread
@@ -650,22 +651,22 @@ public class Domains {
if (addr != null) localHostAddresses.add(addr);
}
}
- } catch (SocketException e) {
+ } catch (final SocketException e) {
}
-
+
// now look up the host name
try {
localHostName = getHostName(InetAddress.getLocalHost());
- } catch (UnknownHostException e) {}
+ } catch (final UnknownHostException e) {}
// after the host name was resolved, we try to look up more local addresses
// using the host name:
try {
final InetAddress[] moreAddresses = InetAddress.getAllByName(localHostName);
if (moreAddresses != null) localHostAddresses.addAll(Arrays.asList(moreAddresses));
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
}
-
+
// fill a cache of local host names
for (final InetAddress a: localHostAddresses) {
final String hostname = getHostName(a);
@@ -677,7 +678,7 @@ public class Domains {
}
}.start();
}
-
+
public static InetAddress myPublicLocalIP() {
// list all addresses
// for (int i = 0; i < localHostAddresses.length; i++) System.out.println("IP: " + localHostAddresses[i].getHostAddress()); // DEBUG
@@ -708,7 +709,7 @@ public class Domains {
if (localHostAddress != null &&
(0Xff & localHostAddress.getAddress()[0]) != 127 &&
localHostAddress.getHostAddress().indexOf(":") < 0) return localHostAddress;
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
}
// we filter out the loopback address 127.0.0.1 and all addresses without a name
for (final InetAddress a: localHostAddresses) {
@@ -729,14 +730,14 @@ public class Domains {
// finally, just get any
return localHostAddresses.iterator().next();
}
-
+
/**
* generate a list of intranet InetAddresses without the loopback address 127.0.0.1
* @return list of all intranet addresses
*/
public static Set<InetAddress> myIntranetIPs() {
// list all local addresses
- if (localHostAddresses.size() < 1) try {Thread.sleep(1000);} catch (InterruptedException e) {}
+ if (localHostAddresses.size() < 1) try {Thread.sleep(1000);} catch (final InterruptedException e) {}
final Set<InetAddress> list = new HashSet<InetAddress>();
if (localHostAddresses.isEmpty()) return list; // give up
for (final InetAddress a: localHostAddresses) {
@@ -749,7 +750,7 @@ public class Domains {
public static boolean isThisHostIP(final String hostName) {
if ((hostName == null) || (hostName.length() == 0)) return false;
-
+
boolean isThisHostIP = false;
try {
final InetAddress clientAddress = Domains.dnsResolve(hostName);
@@ -760,28 +761,28 @@ public class Domains {
isThisHostIP = true;
break;
}
- }
- } catch (final Exception e) {}
+ }
+ } catch (final Exception e) {}
return isThisHostIP;
- }
-
+ }
+
public static boolean isThisHostIP(final InetAddress clientAddress) {
if (clientAddress == null) return false;
-
+
boolean isThisHostIP = false;
try {
if (clientAddress.isAnyLocalAddress() || clientAddress.isLoopbackAddress()) return true;
-
+
for (final InetAddress a: localHostAddresses) {
if (a.equals(clientAddress)) {
isThisHostIP = true;
break;
}
- }
- } catch (final Exception e) {}
+ }
+ } catch (final Exception e) {}
return isThisHostIP;
}
-
+
public static int getDomainID(final String host) {
if (host == null || host.isEmpty() || isLocal(host)) return TLD_Local_ID;
final int p = host.lastIndexOf('.');
@@ -789,7 +790,7 @@ public class Domains {
final Integer i = TLDID.get(tld);
return (i == null) ? TLD_Generic_ID : i.intValue();
}
-
+
/**
* check if a given host is the name for a local host address
* this method will return true if noLocalCheck is switched on. This means that
@@ -806,13 +807,13 @@ public class Domains {
host.startsWith("0:0:0:0:0:0:0:1")
);
}
-
+
public static boolean isLocal(final String host) {
return isLocal(host, true);
}
-
- private static boolean isLocal(final String host, boolean recursive) {
-
+
+ private static boolean isLocal(final String host, final boolean recursive) {
+
if (noLocalCheck || // DO NOT REMOVE THIS! it is correct to return true if the check is off
host == null ||
host.length() == 0) return true;
@@ -821,7 +822,7 @@ public class Domains {
// check local ip addresses
if (matchesList(host, LOCALHOST_PATTERNS)) return true;
if (host.startsWith("0:0:0:0:0:0:0:1")) return true;
-
+
// check if there are other local IP addresses that are not in
// the standard IP range
if (localHostNames.contains(host)) return true;
@@ -829,15 +830,15 @@ public class Domains {
//System.out.println("ISLOCAL-GLOBALHOSTS-HIT " + host);
return false;
}
-
+
// check dns lookup: may be a local address even if the domain name looks global
if (!recursive) return false;
final InetAddress a = dnsResolve(host);
return isLocal(a);
}
-
- public static boolean isLocal(InetAddress a) {
- boolean
+
+ public static boolean isLocal(final InetAddress a) {
+ final boolean
localp = noLocalCheck || // DO NOT REMOVE THIS! it is correct to return true if the check is off
a == null ||
a.isAnyLocalAddress() ||
@@ -847,7 +848,7 @@ public class Domains {
isLocal(a.getHostAddress(), false);
return localp;
}
-
+
public static void main(final String[] args) {
/*
try {
@@ -868,8 +869,8 @@ public class Domains {
a = dnsResolve("yacy.net"); System.out.println(a);
a = dnsResolve("kaskelix.de"); System.out.println(a);
a = dnsResolve("yacy.net"); System.out.println(a);
-
- try { Thread.sleep(1000);} catch (InterruptedException e) {} // get time for class init
+
+ try { Thread.sleep(1000);} catch (final InterruptedException e) {} // get time for class init
System.out.println("myPublicLocalIP: " + myPublicLocalIP());
for (final InetAddress b : myIntranetIPs()) {
System.out.println("Intranet IP: " + b);
diff --git a/source/net/yacy/cora/protocol/TimeoutRequest.java b/source/net/yacy/cora/protocol/TimeoutRequest.java
index c80e533ec..fed518a13 100644
--- a/source/net/yacy/cora/protocol/TimeoutRequest.java
+++ b/source/net/yacy/cora/protocol/TimeoutRequest.java
@@ -11,12 +11,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -38,8 +38,6 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import net.yacy.kelondro.logging.Log;
-
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
@@ -52,56 +50,56 @@ import jcifs.smb.SmbFile;
*/
public class TimeoutRequest<E> {
- private Callable<E> call;
-
+ private final Callable<E> call;
+
/**
* initialize the TimeoutRequest with a callable method
*/
- public TimeoutRequest(Callable<E> call) {
+ public TimeoutRequest(final Callable<E> call) {
this.call = call;
}
-
+
/**
* call the method using a time-out
* @param timeout
* @return
* @throws ExecutionException
*/
- public E call(long timeout) throws ExecutionException {
- ExecutorService service = Executors.newSingleThreadExecutor();
+ public E call(final long timeout) throws ExecutionException {
+ final ExecutorService service = Executors.newSingleThreadExecutor();
try {
final Future<E> taskFuture = service.submit(this.call);
- Runnable t = new Runnable() {
+ final Runnable t = new Runnable() {
public void run() { taskFuture.cancel(true); }
};
service.execute(t);
service.shutdown();
try {
return taskFuture.get(timeout, TimeUnit.MILLISECONDS);
- } catch (CancellationException e) {
+ } catch (final CancellationException e) {
// callable was interrupted
throw new ExecutionException(e);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// service was shutdown
throw new ExecutionException(e);
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
// callable failed unexpectedly
throw e;
- } catch (TimeoutException e) {
+ } catch (final TimeoutException e) {
// time-out
throw new ExecutionException(e);
}
- } catch (OutOfMemoryError e) {
- Log.logWarning("TimeoutRequest.call", "OutOfMemoryError / retry follows", e);
+ } catch (final OutOfMemoryError e) {
+ org.apache.log4j.Logger.getLogger(TimeoutRequest.class).warn("OutOfMemoryError / retry follows", e);
// in case that no memory is there to create a new native thread
try {
return this.call.call();
- } catch (Exception e1) {
+ } catch (final Exception e1) {
throw new ExecutionException(e1);
}
}
}
-
+
/**
* ping a remote server using a given uri and a time-out
* @param uri
@@ -114,7 +112,7 @@ public class TimeoutRequest<E> {
public Boolean call() {
//long time = System.currentTimeMillis();
try {
- Socket socket = new Socket();
+ final Socket socket = new Socket();
//System.out.println("PING socket create = " + (System.currentTimeMillis() - time) + " ms (" + host + ":" + port + ")"); time = System.currentTimeMillis();
socket.connect(new InetSocketAddress(host, port), timeout);
//System.out.println("PING socket connect = " + (System.currentTimeMillis() - time) + " ms (" + host + ":" + port + ")"); time = System.currentTimeMillis();
@@ -124,17 +122,17 @@ public class TimeoutRequest<E> {
}
//System.out.println("PING socket close = " + (System.currentTimeMillis() - time) + " ms (" + host + ":" + port + ")"); time = System.currentTimeMillis();
return Boolean.FALSE;
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
//System.out.println("PING socket UnknownHostException = " + (System.currentTimeMillis() - time) + " ms (" + host + ":" + port + ")"); time = System.currentTimeMillis();
return Boolean.FALSE;
- } catch (IOException e) {
+ } catch (final IOException e) {
//System.out.println("PING socket IOException = " + (System.currentTimeMillis() - time) + " ms (" + host + ":" + port + ")"); time = System.currentTimeMillis();
return Boolean.FALSE;
}
}
}).call(timeout).booleanValue();
}
-
+
/**
* do a DNS lookup within a given time
* @param host
@@ -147,13 +145,13 @@ public class TimeoutRequest<E> {
public InetAddress call() {
try {
return InetAddress.getByName(host);
- } catch (UnknownHostException e) {
+ } catch (final UnknownHostException e) {
return null;
}
}
}).call(timeout);
}
-
+
/**
* perform a reverse domain name lookup for a given InetAddress within a given timeout
* @param i
@@ -166,7 +164,7 @@ public class TimeoutRequest<E> {
public String call() { return i.getHostName(); }
}).call(timeout);
}
-
+
/**
* check if a smb file exists
* @param file
@@ -179,15 +177,15 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<Boolean>(new Callable<Boolean>() {
public Boolean call() { try {
return file.exists();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
return Boolean.FALSE;
} }
}).call(timeout).booleanValue();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
+
/**
* check if a smb file can be read
* @param file
@@ -200,15 +198,15 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<Boolean>(new Callable<Boolean>() {
public Boolean call() { try {
return file.canRead();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
return Boolean.FALSE;
} }
}).call(timeout).booleanValue();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
+
/**
* check if a smb file ran be written
* @param file
@@ -221,15 +219,15 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<Boolean>(new Callable<Boolean>() {
public Boolean call() { try {
return file.canWrite();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
return Boolean.FALSE;
} }
}).call(timeout).booleanValue();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
+
/**
* check if a smb file is hidden
* @param file
@@ -242,15 +240,15 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<Boolean>(new Callable<Boolean>() {
public Boolean call() { try {
return file.isHidden();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
return Boolean.FALSE;
} }
}).call(timeout).booleanValue();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
+
/**
* check if a smb file is a directory
* @param file
@@ -263,15 +261,15 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<Boolean>(new Callable<Boolean>() {
public Boolean call() { try {
return file.isDirectory();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
return Boolean.FALSE;
} }
}).call(timeout).booleanValue();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
+
/**
* get the size of a smb file
* @param file
@@ -284,15 +282,15 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<Long>(new Callable<Long>() {
public Long call() { try {
return file.length();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
return Long.valueOf(0);
} }
}).call(timeout).longValue();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
+
/**
* get last-modified time of a smb file
* @param file
@@ -305,15 +303,15 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<Long>(new Callable<Long>() {
public Long call() { try {
return file.lastModified();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
return Long.valueOf(0);
} }
}).call(timeout).longValue();
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
+
/**
* get list of a smb directory
* @param file
@@ -326,20 +324,20 @@ public class TimeoutRequest<E> {
return new TimeoutRequest<String[]>(new Callable<String[]>() {
public String[] call() { try {
return file.list();
- } catch (SmbException e) {
+ } catch (final SmbException e) {
//Log.logWarning("TimeoutRequest:list", file.toString() + " - no list", e);
return null;
} }
}).call(timeout);
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
throw new IOException(e.getMessage());
}
}
-
- public static void main(String[] args) {
+
+ public static void main(final String[] args) {
try {
System.out.println(getByName("yacy.net", 100));
- } catch (ExecutionException e) {
+ } catch (final ExecutionException e) {
e.printStackTrace();
}
}
diff --git a/source/net/yacy/cora/services/federated/SearchHub.java b/source/net/yacy/cora/services/federated/SearchHub.java
index 7ff72e045..5db1ce8a9 100644
--- a/source/net/yacy/cora/services/federated/SearchHub.java
+++ b/source/net/yacy/cora/services/federated/SearchHub.java
@@ -11,12 +11,12 @@
* modify it under the terms of the GNU Lesser General private
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -30,11 +30,10 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-import de.anomic.crawler.CrawlProfile;
-
import net.yacy.cora.document.RSSMessage;
import net.yacy.cora.protocol.http.HTTPClient;
import net.yacy.cora.services.federated.opensearch.SRURSSConnector;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.cora.storage.ConcurrentScoreMap;
import net.yacy.cora.storage.ScoreMap;
@@ -51,12 +50,12 @@ public class SearchHub {
};
public final static SearchHub EMPTY = new SearchHub("", 0);
-
- private String query;
- private int timeout;
- private List<SearchAccumulator> threads;
- private Map<RSSMessage, List<Integer>> result;
-
+
+ private final String query;
+ private final int timeout;
+ private final List<SearchAccumulator> threads;
+ private final Map<RSSMessage, List<Integer>> result;
+
public SearchHub(final String query, final int timeout) {
this.query = query;
this.timeout = timeout;
@@ -77,10 +76,10 @@ public class SearchHub {
* this is mainly used for awaitTermination() and isTerminated()
* @param a
*/
- public void addAccumulator(SearchAccumulator a) {
+ public void addAccumulator(final SearchAccumulator a) {
this.threads.add(a);
}
-
+
/**
* get the original query string
* @return
@@ -88,7 +87,7 @@ public class SearchHub {
public String getQuery() {
return this.query;
}
-
+
/**
* get the given time-out of the search request
* @return
@@ -96,7 +95,7 @@ public class SearchHub {
public int getTimeout() {
return this.timeout;
}
-
+
/**
* get the list of search results as scored map.
* The results are combined using their appearance positions.
@@ -104,11 +103,11 @@ public class SearchHub {
* @return a score map of urls
*/
public ScoreMap<String> getResults() {
- ScoreMap<String> scores = new ConcurrentScoreMap<String>();
- int m = threads.size();
- for (Map.Entry<RSSMessage, List<Integer>> entry: this.result.entrySet()) {
+ final ScoreMap<String> scores = new ConcurrentScoreMap<String>();
+ final int m = this.threads.size();
+ for (final Map.Entry<RSSMessage, List<Integer>> entry: this.result.entrySet()) {
int a = 0;
- for (Integer i : entry.getValue()) a += i.intValue();
+ for (final Integer i : entry.getValue()) a += i.intValue();
scores.inc(entry.getKey().getLink(), a * m / entry.getValue().size());
}
return scores;
@@ -118,27 +117,27 @@ public class SearchHub {
* wait until all accumulation threads have terminated
*/
public void waitTermination() {
- for (SearchAccumulator t: threads) try {t.join();} catch (InterruptedException e) {}
+ for (final SearchAccumulator t: this.threads) try {t.join();} catch (final InterruptedException e) {}
}
-
+
/**
* return true if all accumulation threads have terminated
* @return
*/
public boolean isTerminated() {
- for (SearchAccumulator t: threads) if (t.isAlive()) return false;
+ for (final SearchAccumulator t: this.threads) if (t.isAlive()) return false;
return true;
}
-
+
/**
* return a hash code of the search hub.
* This is computed using only the query string because that identifies the object
*/
@Override
public int hashCode() {
- return query.hashCode();
+ return this.query.hashCode();
}
-
+
/**
* test method to add a list of SRU RSS services.
* such services are provided by YaCy peers
@@ -148,32 +147,32 @@ public class SearchHub {
* @param verify
* @param global
*/
- public static void addSRURSSServices(SearchHub search, String[] rssServices, int count, CrawlProfile.CacheStrategy verify, boolean global, String userAgent) {
- for (String service: rssServices) {
- SRURSSConnector accumulator = new SRURSSConnector(search, service, count, verify, global, userAgent);
+ public static void addSRURSSServices(final SearchHub search, final String[] rssServices, final int count, final CacheStrategy verify, final boolean global, final String userAgent) {
+ for (final String service: rssServices) {
+ final SRURSSConnector accumulator = new SRURSSConnector(search, service, count, verify, global, userAgent);
accumulator.start();
search.addAccumulator(accumulator);
}
}
-
- public static void main(String[] args) {
+
+ public static void main(final String[] args) {
HTTPClient.setDefaultUserAgent("searchhub");
HTTPClient.initConnectionManager();
-
- StringBuilder sb = new StringBuilder();
- for (String s: args) sb.append(s).append(' ');
- String query = sb.toString().trim();
- SearchHub search = new SearchHub(query, 10000);
- addSRURSSServices(search, SRURSSServicesList, 100, CrawlProfile.CacheStrategy.CACHEONLY, false, "searchhub");
- try {Thread.sleep(100);} catch (InterruptedException e1) {}
+
+ final StringBuilder sb = new StringBuilder();
+ for (final String s: args) sb.append(s).append(' ');
+ final String query = sb.toString().trim();
+ final SearchHub search = new SearchHub(query, 10000);
+ addSRURSSServices(search, SRURSSServicesList, 100, CacheStrategy.CACHEONLY, false, "searchhub");
+ try {Thread.sleep(100);} catch (final InterruptedException e1) {}
search.waitTermination();
- ScoreMap<String> result = search.getResults();
- Iterator<String> i = result.keys(true);
+ final ScoreMap<String> result = search.getResults();
+ final Iterator<String> i = result.keys(true);
String u;
while (i.hasNext()) {
u = i.next();
System.out.println("[" + result.get(u) + "] " + u);
}
- try {HTTPClient.closeConnectionManager();} catch (InterruptedException e) { e.printStackTrace(); }
+ try {HTTPClient.closeConnectionManager();} catch (final InterruptedException e) { e.printStackTrace(); }
}
}
diff --git a/source/net/yacy/cora/services/federated/SearchResult.java b/source/net/yacy/cora/services/federated/SearchResult.java
index 2abbd84c5..c9e3a84b2 100644
--- a/source/net/yacy/cora/services/federated/SearchResult.java
+++ b/source/net/yacy/cora/services/federated/SearchResult.java
@@ -13,12 +13,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -26,46 +26,45 @@
package net.yacy.cora.services.federated;
-import de.anomic.search.ResultEntry;
import net.yacy.cora.storage.WeakPriorityBlockingQueue;
-public class SearchResult extends WeakPriorityBlockingQueue<ResultEntry> {
+public class SearchResult extends WeakPriorityBlockingQueue<Object> {
- public SearchResult(int maxsize) {
+ public SearchResult(final int maxsize) {
super(maxsize);
}
private static final long serialVersionUID = -4865225874936938082L;
-
+
private long numFound = 0;
private long start = 0;
private Float maxScore = null;
- protected void setNumFound(long numFound) {
+ protected void setNumFound(final long numFound) {
this.numFound = numFound;
}
public long getNumFound() {
- return numFound;
+ return this.numFound;
}
- protected void setStart(long start) {
+ protected void setStart(final long start) {
this.start = start;
}
public long getStart() {
- return start;
+ return this.start;
}
- protected void setMaxScore(Float maxScore) {
+ protected void setMaxScore(final Float maxScore) {
this.maxScore = maxScore;
}
public Float getMaxScore() {
- return maxScore;
+ return this.maxScore;
}
public String toString() {
- return "{count=" + numFound + ", offset=" + start + (maxScore != null ? ", maxScore=" + maxScore : "") + ", docs=" + super.toString() + "}";
+ return "{count=" + this.numFound + ", offset=" + this.start + (this.maxScore != null ? ", maxScore=" + this.maxScore : "") + ", docs=" + super.toString() + "}";
}
}
\ No newline at end of file
diff --git a/source/net/yacy/cora/services/federated/opensearch/SRURSSConnector.java b/source/net/yacy/cora/services/federated/opensearch/SRURSSConnector.java
index c58f7350a..3a22dd147 100644
--- a/source/net/yacy/cora/services/federated/opensearch/SRURSSConnector.java
+++ b/source/net/yacy/cora/services/federated/opensearch/SRURSSConnector.java
@@ -11,12 +11,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -34,10 +34,6 @@ import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-import org.apache.http.entity.mime.content.ContentBody;
-
-import de.anomic.crawler.CrawlProfile;
-
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
@@ -47,29 +43,32 @@ import net.yacy.cora.protocol.ClientIdentification;
import net.yacy.cora.protocol.http.HTTPClient;
import net.yacy.cora.services.federated.SearchAccumulator;
import net.yacy.cora.services.federated.SearchHub;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
+
+import org.apache.http.entity.mime.content.ContentBody;
public class SRURSSConnector extends Thread implements SearchAccumulator {
private final static int recordsPerSession = 100;
-
+
final String urlBase;
final String query;
final long timeoutInit;
final int maximumRecordsInit;
- final CrawlProfile.CacheStrategy verify;
+ final CacheStrategy verify;
final boolean global;
final Map<RSSMessage, List<Integer>> result;
final String userAgent;
private final BlockingQueue<RSSMessage> results;
-
+
public SRURSSConnector(
final Map<RSSMessage, List<Integer>> result,
final String query,
final long timeoutInit,
final String urlBase,
final int maximumRecordsInit,
- final CrawlProfile.CacheStrategy verify,
+ final CacheStrategy verify,
final boolean global,
final String userAgent) {
this.results = new LinkedBlockingQueue<RSSMessage>();
@@ -82,12 +81,12 @@ public class SRURSSConnector extends Thread implements SearchAccumulator {
this.global = global;
this.userAgent = userAgent;
}
-
+
public SRURSSConnector(
final SearchHub search,
final String urlBase,
final int maximumRecordsInit,
- final CrawlProfile.CacheStrategy verify,
+ final CacheStrategy verify,
final boolean global,
final String userAgent) {
this.results = new LinkedBlockingQueue<RSSMessage>();
@@ -100,35 +99,35 @@ public class SRURSSConnector extends Thread implements SearchAccumulator {
this.global = global;
this.userAgent = userAgent;
}
-
+
@Override
public void run() {
- searchSRURSS(results, urlBase, query, timeoutInit, maximumRecordsInit, verify, global, userAgent);
+ searchSRURSS(this.results, this.urlBase, this.query, this.timeoutInit, this.maximumRecordsInit, this.verify, this.global, this.userAgent);
int p = 1;
RSSMessage message;
try {
- while ((message = results.poll(timeoutInit, TimeUnit.MILLISECONDS)) != RSSMessage.POISON) {
+ while ((message = this.results.poll(this.timeoutInit, TimeUnit.MILLISECONDS)) != RSSMessage.POISON) {
if (message == null) break;
- List<Integer> m = result.get(message.getLink());
+ List<Integer> m = this.result.get(message.getLink());
if (m == null) m = new ArrayList<Integer>();
m.add(new Integer(p++));
- result.put(message, m);
+ this.result.put(message, m);
}
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
e.printStackTrace();
}
}
-
+
public static Thread searchSRURSS(
final BlockingQueue<RSSMessage> queue,
final String urlBase,
final String query,
final long timeoutInit,
final int maximumRecordsInit,
- final CrawlProfile.CacheStrategy verify,
+ final CacheStrategy verify,
final boolean global,
final String userAgent) {
- Thread job = new Thread() {
+ final Thread job = new Thread() {
@Override
public void run() {
int startRecord = 0;
@@ -136,12 +135,12 @@ public class SRURSSConnector extends Thread implements SearchAccumulator {
int maximumRecords = maximumRecordsInit;
long timeout = timeoutInit;
mainloop: while (timeout > 0 && maximumRecords > 0) {
- long st = System.currentTimeMillis();
+ final long st = System.currentTimeMillis();
RSSFeed feed;
try {
feed = loadSRURSS(urlBase, query, timeout, startRecord, recordsPerSession, verify, global, userAgent);
- } catch (IOException e1) {
- e1.printStackTrace();
+ } catch (final IOException e1) {
+ //e1.printStackTrace();
break mainloop;
}
if (feed == null || feed.isEmpty()) break mainloop;
@@ -151,21 +150,21 @@ public class SRURSSConnector extends Thread implements SearchAccumulator {
if (message == null) break innerloop;
try {
queue.put(message);
- } catch (InterruptedException e) {
- e.printStackTrace();
+ } catch (final InterruptedException e) {
+ e.printStackTrace();
break innerloop;
}
}
startRecord += recordsPerSession;
timeout -= System.currentTimeMillis() - st;
}
- try { queue.put(RSSMessage.POISON); } catch (InterruptedException e) { e.printStackTrace(); }
+ try { queue.put(RSSMessage.POISON); } catch (final InterruptedException e) { e.printStackTrace(); }
}
};
job.start();
return job;
}
-
+
/**
* send a query to a yacy public search interface
* @param rssSearchServiceURL the target url base (everything before the ? that follows the SRU request syntax properties). can null, then the local peer is used
@@ -178,21 +177,21 @@ public class SRURSSConnector extends Thread implements SearchAccumulator {
* @return
*/
public static RSSFeed loadSRURSS(
- String rssSearchServiceURL,
- String query,
- long timeout,
- int startRecord,
- int maximumRecords,
- CrawlProfile.CacheStrategy cacheStrategy,
- boolean global,
- String userAgent) throws IOException {
+ final String rssSearchServiceURL,
+ final String query,
+ final long timeout,
+ final int startRecord,
+ final int maximumRecords,
+ final CacheStrategy cacheStrategy,
+ final boolean global,
+ final String userAgent) throws IOException {
MultiProtocolURI uri = null;
try {
uri = new MultiProtocolURI(rssSearchServiceURL);
- } catch (MalformedURLException e) {
+ } catch (final MalformedURLException e) {
throw new IOException("cora.Search failed asking peer '" + rssSearchServiceURL + "': bad url, " + e.getMessage());
}
-
+
// send request
byte[] result = new byte[0];
try {
@@ -206,7 +205,7 @@ public class SRURSSConnector extends Thread implements SearchAccumulator {
// result = HTTPConnector.getConnector(userAgent == null ? MultiProtocolURI.yacybotUserAgent : userAgent).post(new MultiProtocolURI(rssSearchServiceURL), (int) timeout, uri.getHost(), parts);
final HTTPClient httpClient = new HTTPClient(userAgent == null ? ClientIdentification.getUserAgent() : userAgent, (int) timeout);
result = httpClient.POSTbytes(new MultiProtocolURI(rssSearchServiceURL), uri.getHost(), parts, false);
-
+
final RSSReader reader = RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, result);
if (reader == null) {
throw new IOException("cora.Search failed asking peer '" + uri.getHost() + "': probably bad response from remote peer (1), reader == null");
@@ -218,7 +217,6 @@ public class SRURSSConnector extends Thread implements SearchAccumulator {
}
return feed;
} catch (final IOException e) {
- String debug = UTF8.String(result); System.out.println("*** DEBUG: " + debug);
throw new IOException("cora.Search error asking peer '" + uri.getHost() + "':" + e.toString());
}
}
diff --git a/source/net/yacy/cora/services/federated/solr/SolrChardingConnector.java b/source/net/yacy/cora/services/federated/solr/SolrChardingConnector.java
index 12f79bebb..34be34b52 100644
--- a/source/net/yacy/cora/services/federated/solr/SolrChardingConnector.java
+++ b/source/net/yacy/cora/services/federated/solr/SolrChardingConnector.java
@@ -11,12 +11,12 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -44,55 +44,55 @@ public class SolrChardingConnector {
private final SolrScheme scheme;
private final SolrChardingSelection charding;
private final String[] urls;
-
- public SolrChardingConnector(final String urlList, SolrScheme scheme, SolrChardingSelection.Method method) throws IOException {
+
+ public SolrChardingConnector(final String urlList, final SolrScheme scheme, final SolrChardingSelection.Method method) throws IOException {
this.urls = urlList.split(",");
this.connectors = new ArrayList<SolrSingleConnector>();
- for (String u: urls) {
+ for (final String u: this.urls) {
this.connectors.add(new SolrSingleConnector(u.trim(), scheme));
}
- this.charding = new SolrChardingSelection(method, urls.length);
+ this.charding = new SolrChardingSelection(method, this.urls.length);
this.scheme = scheme;
}
public void close() {
- for (SolrSingleConnector connector: this.connectors) connector.close();
+ for (final SolrSingleConnector connector: this.connectors) connector.close();
}
-
+
/**
* delete everything in the solr index
* @throws IOException
*/
public void clear() throws IOException {
- for (SolrSingleConnector connector: this.connectors) connector.clear();
+ for (final SolrSingleConnector connector: this.connectors) connector.clear();
}
-
+
/**
* delete an entry from solr
* @param id the url hash of the entry
* @throws IOException
*/
- public void delete(String id) throws IOException {
- for (SolrSingleConnector connector: this.connectors) connector.delete(id);
+ public void delete(final String id) throws IOException {
+ for (final SolrSingleConnector connector: this.connectors) connector.delete(id);
}
-
+
/**
* delete a set of entries from solr; entries are identified by their url hash
* @param ids a list of url hashes
* @throws IOException
*/
- public void delete(List<String> ids) throws IOException {
- for (SolrSingleConnector connector: this.connectors) connector.delete(ids);
+ public void delete(final List<String> ids) throws IOException {
+ for (final SolrSingleConnector connector: this.connectors) connector.delete(ids);
}
-
+
/**
* add a YaCy document. This calls the scheme processor to add the document as solr document
* @param id the url hash of the entry
* @param header the http response header
- * @param doc the YaCy document
+ * @param doc the YaCy document
* @throws IOException
*/
- public void add(String id, ResponseHeader header, Document doc) throws IOException {
+ public void add(final String id, final ResponseHeader header, final Document doc) throws IOException {
add(this.scheme.yacy2solr(id, header, doc));
}
@@ -101,19 +101,19 @@ public class SolrChardingConnector {
* @param solrdoc
* @throws IOException
*/
- private void add(SolrInputDocument solrdoc) throws IOException {
+ private void add(final SolrInputDocument solrdoc) throws IOException {
this.connectors.get(this.charding.select(solrdoc)).add(solrdoc);
}
-
+
/**
* add a collection of Solr documents
* @param docs
* @throws IOException
*/
- protected void addSolr(Collection<SolrInputDocument> docs) throws IOException {
- for (SolrInputDocument doc: docs) add(doc);
+ protected void addSolr(final Collection<SolrInputDocument> docs) throws IOException {
+ for (final SolrInputDocument doc: docs) add(doc);
}
-
+
/**
* register an entry as error document
* @param digestURI
@@ -121,58 +121,58 @@ public class SolrChardingConnector {
* @param httpstatus
* @throws IOException
*/
- public void err(DigestURI digestURI, String failReason, int httpstatus) throws IOException {
+ public void err(final DigestURI digestURI, final String failReason, final int httpstatus) throws IOException {
this.connectors.get(this.charding.selectURL(digestURI.toNormalform(true, false))).err(digestURI, failReason, httpstatus);
}
-
-
+
+
/**
* get a query result from solr
* to get all results set the query String to "*:*"
* @param querystring
* @throws IOException
*/
- public SolrDocumentList get(String querystring, int offset, int count) throws IOException {
- SolrDocumentList list = new SolrDocumentList();
- for (SolrSingleConnector connector: this.connectors) {
- SolrDocumentList l = connector.get(querystring, offset, count);
- for (SolrDocument d: l) {
+ public SolrDocumentList get(final String querystring, final int offset, final int count) throws IOException {
+ final SolrDocumentList list = new SolrDocumentList();
+ for (final SolrSingleConnector connector: this.connectors) {
+ final SolrDocumentList l = connector.get(querystring, offset, count);
+ for (final SolrDocument d: l) {
list.add(d);
}
}
return list;
}
-
- public SolrDocumentList[] getList(String querystring, int offset, int count) throws IOException {
- SolrDocumentList[] list = new SolrDocumentList[this.connectors.size()];
+
+ public SolrDocumentList[] getList(final String querystring, final int offset, final int count) throws IOException {
+ final SolrDocumentList[] list = new SolrDocumentList[this.connectors.size()];
int i = 0;
- for (SolrSingleConnector connector: this.connectors) {
+ for (final SolrSingleConnector connector: this.connectors) {
list[i++] = connector.get(querystring, offset, count);
}
return list;
}
-
+
public long[] getSizeList() throws IOException {
- long[] size = new long[this.connectors.size()];
+ final long[] size = new long[this.connectors.size()];
int i = 0;
- for (SolrSingleConnector connector: this.connectors) {
- SolrDocumentList list = connector.get("*:*", 0, 1);
+ for (final SolrSingleConnector connector: this.connectors) {
+ final SolrDocumentList list = connector.get("*:*", 0, 1);
size[i++] = list.getNumFound();
}
return size;
}
-
+
public long getSize() throws IOException {
- long[] size = getSizeList();
+ final long[] size = getSizeList();
long s = 0;
- for (long l: size) s += l;
+ for (final long l: size) s += l;
return s;
}
-
+
public String[] getAdminInterfaceList() {
- String[] urlAdmin = new String[this.connectors.size()];
+ final String[] urlAdmin = new String[this.connectors.size()];
int i = 0;
- for (String u: this.urls) {
+ for (final String u: this.urls) {
urlAdmin[i++] = u + "/admin/";
}
return urlAdmin;
diff --git a/source/net/yacy/cora/services/federated/yacy/CacheStrategy.java b/source/net/yacy/cora/services/federated/yacy/CacheStrategy.java
new file mode 100644
index 000000000..14067465d
--- /dev/null
+++ b/source/net/yacy/cora/services/federated/yacy/CacheStrategy.java
@@ -0,0 +1,48 @@
+package net.yacy.cora.services.federated.yacy;
+
+public enum CacheStrategy {
+
+ NOCACHE(0), // never use the cache, all content from fresh internet source
+ IFFRESH(1), // use the cache if the cache exists and is fresh using the proxy-fresh rules
+ IFEXIST(2), // use the cache if the cache exist. Do no check freshness. Otherwise use online source.
+ CACHEONLY(3); // never go online, use all content from cache. If no cache entry exist, consider content nevertheless as available
+ // the fifth case may be that the CacheStrategy object is assigned NULL. That means that no snippet creation is wanted.
+
+ public int code;
+
+ private CacheStrategy(final int code) {
+ this.code = code;
+ }
+
+ public String toString() {
+ return Integer.toString(this.code);
+ }
+
+ public static CacheStrategy decode(final int code) {
+ for (final CacheStrategy strategy: CacheStrategy.values()) if (strategy.code == code) return strategy;
+ return NOCACHE;
+ }
+
+ public static CacheStrategy parse(final String name) {
+ if (name == null) return null;
+ if (name.equals("nocache")) return NOCACHE;
+ if (name.equals("iffresh")) return IFFRESH;
+ if (name.equals("ifexist")) return IFEXIST;
+ if (name.equals("cacheonly")) return CACHEONLY;
+ if (name.equals("true")) return IFEXIST;
+ if (name.equals("false")) return null; // if this cache strategy is assigned as query attribute, null means "do not create a snippet"
+ return null;
+ }
+
+ public String toName() {
+ return name().toLowerCase();
+ }
+
+ public boolean isAllowedToFetchOnline() {
+ return this.code < 3;
+ }
+
+ public boolean mustBeOffline() {
+ return this.code == 3;
+ }
+}
diff --git a/source/net/yacy/document/importer/OAIListFriendsLoader.java b/source/net/yacy/document/importer/OAIListFriendsLoader.java
index 0c2beab35..ca663f07e 100644
--- a/source/net/yacy/document/importer/OAIListFriendsLoader.java
+++ b/source/net/yacy/document/importer/OAIListFriendsLoader.java
@@ -2,19 +2,19 @@
* OAIListFriendsLoader
* Copyright 2010 by Michael Peter Christen
* First released 29.04.2010 at http://yacy.net
- *
+ *
* This is a part of YaCy, a peer-to-peer based web search engine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -29,15 +29,16 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
-import java.util.Map.Entry;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import net.yacy.cora.document.UTF8;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.util.FileUtils;
@@ -47,57 +48,56 @@ import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
public class OAIListFriendsLoader {
private static final long serialVersionUID = -8705115274655024604L;
-
+
private static final HashMap<String, File> listFriends = new HashMap<String, File>();
-
- public static void init(LoaderDispatcher loader, Map<String, File> moreFriends) {
+
+ public static void init(final LoaderDispatcher loader, final Map<String, File> moreFriends) {
listFriends.putAll(moreFriends);
- if (loader != null) for (Map.Entry<String, File> oaiFriend: listFriends.entrySet()) {
+ if (loader != null) for (final Map.Entry<String, File> oaiFriend: listFriends.entrySet()) {
loader.loadIfNotExistBackground(oaiFriend.getKey(), oaiFriend.getValue(), Long.MAX_VALUE);
}
}
-
- public static Map<String, File> loadListFriendsSources(File initFile, File dataPath) {
- Properties p = new Properties();
- Map<String, File> m = new HashMap<String, File>();
+
+ public static Map<String, File> loadListFriendsSources(final File initFile, final File dataPath) {
+ final Properties p = new Properties();
+ final Map<String, File> m = new HashMap<String, File>();
try {
p.loadFromXML(new FileInputStream(initFile));
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
return m;
}
- for (Entry<Object, Object> e: p.entrySet()) m.put((String) e.getKey(), new File(dataPath, (String) e.getValue()));
+ for (final Entry<Object, Object> e: p.entrySet()) m.put((String) e.getKey(), new File(dataPath, (String) e.getValue()));
return m;
}
-
-
- public static Map<String, String> getListFriends(LoaderDispatcher loader) {
- Map<String, String> map = new TreeMap<String, String>();
+
+
+ public static Map<String, String> getListFriends(final LoaderDispatcher loader) {
+ final Map<String, String> map = new TreeMap<String, String>();
Map<String, String> m;
- for (Map.Entry<String, File> oaiFriend: listFriends.entrySet()) try {
+ for (final Map.Entry<String, File> oaiFriend: listFriends.entrySet()) try {
if (!oaiFriend.getValue().exists()) {
- Response response = loader == null ? null : loader.load(loader.request(new DigestURI(oaiFriend.getKey()), false, true), CrawlProfile.CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
+ final Response response = loader == null ? null : loader.load(loader.request(new DigestURI(oaiFriend.getKey()), false, true), CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
if (response != null) FileUtils.copy(response.getContent(), oaiFriend.getValue());
}
-
+
if (oaiFriend.getValue().exists()) {
- byte[] b = FileUtils.read(oaiFriend.getValue());
+ final byte[] b = FileUtils.read(oaiFriend.getValue());
if (b != null) {
m = new Parser(b).map;
if (m != null) map.putAll(m);
}
}
-
- } catch (IOException e) {}
+
+ } catch (final IOException e) {}
return map;
}
-
+
// get a resumption token using a SAX xml parser from am input stream
private static class Parser extends DefaultHandler {
@@ -105,10 +105,10 @@ public class OAIListFriendsLoader {
private final StringBuilder buffer;
private boolean parsingValue;
private SAXParser saxParser;
- private InputStream stream;
+ private final InputStream stream;
private Attributes atts;
private int recordCounter;
- private TreeMap<String, String> map;
+ private final TreeMap<String, String> map;
public Parser(final byte[] b) throws IOException {
this.map = new TreeMap<String, String>();
@@ -121,25 +121,25 @@ public class OAIListFriendsLoader {
try {
this.saxParser = factory.newSAXParser();
this.saxParser.parse(this.stream, this);
- } catch (SAXException e) {
+ } catch (final SAXException e) {
Log.logException(e);
Log.logWarning("OAIListFriendsLoader.Parser", "OAIListFriends was not parsed:\n" + UTF8.String(b));
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
Log.logWarning("OAIListFriendsLoader.Parser", "OAIListFriends was not parsed:\n" + UTF8.String(b));
- } catch (ParserConfigurationException e) {
+ } catch (final ParserConfigurationException e) {
Log.logException(e);
Log.logWarning("OAIListFriendsLoader.Parser", "OAIListFriends was not parsed:\n" + UTF8.String(b));
throw new IOException(e.getMessage());
} finally {
try {
this.stream.close();
- } catch (IOException e) {
+ } catch (final IOException e) {
Log.logException(e);
}
}
}
-
+
/*
<?xml version="1.0" encoding="UTF-8"?>
<BaseURLs>
@@ -148,10 +148,10 @@ public class OAIListFriendsLoader {
<baseURL id="http://roar.eprints.org/id/eprint/1064">http://oai.repec.openlib.org/</baseURL>
</BaseURLs>
*/
-
+
public void startElement(final String uri, final String name, final String tag, final Attributes atts) throws SAXException {
if ("baseURL".equals(tag)) {
- recordCounter++;
+ this.recordCounter++;
this.parsingValue = true;
this.atts = atts;
}
@@ -160,15 +160,15 @@ public class OAIListFriendsLoader {
public void endElement(final String uri, final String name, final String tag) {
if (tag == null) return;
if ("baseURL".equals(tag)) {
- this.map.put(buffer.toString(), this.atts.getValue("id"));
+ this.map.put(this.buffer.toString(), this.atts.getValue("id"));
this.buffer.setLength(0);
this.parsingValue = false;
}
}
public void characters(final char ch[], final int start, final int length) {
- if (parsingValue) {
- buffer.append(ch, start, length);
+ if (this.parsingValue) {
+ this.buffer.append(ch, start, length);
}
}
diff --git a/source/net/yacy/document/importer/OAIPMHLoader.java b/source/net/yacy/document/importer/OAIPMHLoader.java
index d453da3d4..889423568 100644
--- a/source/net/yacy/document/importer/OAIPMHLoader.java
+++ b/source/net/yacy/document/importer/OAIPMHLoader.java
@@ -2,19 +2,19 @@
* OAIPMHLoader
* Copyright 2009 by Michael Peter Christen
* First released 30.09.2009 at http://yacy.net
- *
+ *
* This is a part of YaCy, a peer-to-peer based web search engine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
@@ -25,11 +25,10 @@ package net.yacy.document.importer;
import java.io.File;
import java.io.IOException;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.repository.LoaderDispatcher;
-
-import de.anomic.crawler.CrawlProfile;
import de.anomic.crawler.retrieval.Response;
@@ -43,22 +42,22 @@ public class OAIPMHLoader {
private final DigestURI source;
private final ResumptionToken resumptionToken;
-
- public OAIPMHLoader(LoaderDispatcher loader, DigestURI source, File targetDir, String filePrefix) throws IOException {
+
+ public OAIPMHLoader(final LoaderDispatcher loader, final DigestURI source, final File targetDir, final String filePrefix) throws IOException {
this.source = source;
-
+
// load the file from the net
- Response response = loader.load(loader.request(source, false, true), CrawlProfile.CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
- byte[] b = response.getContent();
+ final Response response = loader.load(loader.request(source, false, true), CacheStrategy.NOCACHE, Long.MAX_VALUE, true);
+ final byte[] b = response.getContent();
this.resumptionToken = new ResumptionToken(source, b);
//System.out.println("*** ResumptionToken = " + this.resumptionToken.toString());
- File f1 = new File(targetDir, OAIPMHImporter.filename4Source(source));
- File f0 = new File(targetDir, f1.getName() + ".tmp");
-
+ final File f1 = new File(targetDir, OAIPMHImporter.filename4Source(source));
+ final File f0 = new File(targetDir, f1.getName() + ".tmp");
+
// transaction-safe writing
FileUtils.copy(b, f0);
f0.renameTo(f1);
-
+
/*
SurrogateReader sr = new SurrogateReader(new ByteArrayInputStream(b), 100);
Thread srt = new Thread(sr);
@@ -72,15 +71,15 @@ public class OAIPMHLoader {
} catch (InterruptedException e) {}
*/
}
-
+
public ResumptionToken getResumptionToken() {
return this.resumptionToken;
}
public String source() {
- return source.toNormalform(true, false);
+ return this.source.toNormalform(true, false);
}
-
+
public static StringBuilder escape(final String s) {
final int len = s.length();
final StringBuilder sbuf = new StringBuilder(len + 10);
@@ -117,9 +116,9 @@ public class OAIPMHLoader {
case '%':
if (i + 2 < l) {
ch = s.charAt(++i);
- int hb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
+ final int hb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
ch = s.charAt(++i);
- int lb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase ((char) ch) - 'a') & 0xF;
+ final int lb = (Character.isDigit ((char) ch) ? ch - '0' : 10 + Character.toLowerCase ((char) ch) - 'a') & 0xF;
b = (hb << 4) | lb;
} else {
b = ch;
diff --git a/source/net/yacy/repository/LoaderDispatcher.java b/source/net/yacy/repository/LoaderDispatcher.java
index 199b00a58..d8e37eed6 100644
--- a/source/net/yacy/repository/LoaderDispatcher.java
+++ b/source/net/yacy/repository/LoaderDispatcher.java
@@ -47,6 +47,7 @@ import net.yacy.cora.protocol.ClientIdentification;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.protocol.ResponseHeader;
+import net.yacy.cora.services.federated.yacy.CacheStrategy;
import net.yacy.document.Document;
import net.yacy.document.Parser;
import net.yacy.document.TextParser;
@@ -135,7 +136,7 @@ public final class LoaderDispatcher {
0);
}
- public void load(final DigestURI url, final CrawlProfile.CacheStrategy cacheStratgy, final long maxFileSize, final File targetFile) throws IOException {
+ public void load(final DigestURI url, final CacheStrategy cacheStratgy, final long maxFileSize, final File targetFile) throws IOException {
final byte[] b = load(request(url, false, true), cacheStratgy, maxFileSize, false).getContent();
if (b == null) throw new IOException("load == null");
@@ -148,7 +149,7 @@ public final class LoaderDispatcher {
tmp.renameTo(targetFile);
}
- public Response load(final Request request, final CrawlProfile.CacheStrategy cacheStrategy, final long maxFileSize, final boolean checkBlacklist) throws IOException {
+ public Response load(final Request request, final CacheStrategy cacheStrategy, final long maxFileSize, final boolean checkBlacklist) throws IOException {
final String url = request.url().toNormalform(true, false);
Semaphore check = this.loaderSteering.get(url);
if (check != null) {
@@ -180,16 +181,16 @@ public final class LoaderDispatcher {
* @return the loaded entity in a Response object
* @throws IOException
*/
- private Response loadInternal(final Request request, CrawlProfile.CacheStrategy cacheStrategy, final long maxFileSize, final boolean checkBlacklist) throws IOException {
+ private Response loadInternal(final Request request, CacheStrategy cacheStrategy, final long maxFileSize, final boolean checkBlacklist) throws IOException {
// get the protocol of the next URL
final DigestURI url = request.url();
- if (url.isFile() || url.isSMB()) cacheStrategy = CrawlProfile.CacheStrategy.NOCACHE; // load just from the file system
+ if (url.isFile() || url.isSMB()) cacheStrategy = CacheStrategy.NOCACHE; // load just from the file system
final String protocol = url.getProtocol();
final String host = url.getHost();
// check if we have the page in the cache
final CrawlProfile crawlProfile = this.sb.crawler.getActive(UTF8.getBytes(request.profileHandle()));
- if (crawlProfile != null && cacheStrategy != CrawlProfile.CacheStrategy.NOCACHE) {
+ if (crawlProfile != null && cacheStrategy != CacheStrategy.NOCACHE) {
// we have passed a first test if caching is allowed
// now see if there is a cache entry
@@ -214,14 +215,14 @@ public final class LoaderDispatcher {
content);
// check which caching strategy shall be used
- if (cacheStrategy == CrawlProfile.CacheStrategy.IFEXIST || cacheStrategy == CrawlProfile.CacheStrategy.CACHEONLY) {
+ if (cacheStrategy == CacheStrategy.IFEXIST || cacheStrategy == CacheStrategy.CACHEONLY) {
// well, just take the cache and don't care about freshness of the content
this.log.logInfo("cache hit/useall for: " + url.toNormalform(true, false));
return response;
}
// now the cacheStrategy must be CACHE_STRATEGY_IFFRESH, that means we should do a proxy freshness test
- assert cacheStrategy == CrawlProfile.CacheStrategy.IFFRESH : "cacheStrategy = " + cacheStrategy;
+ assert cacheStrategy == CacheStrategy.IFFRESH : "cacheStrategy = " + cacheStrategy;
if (response.isFreshForProxy()) {
this.log.logInfo("cache hit/fresh for: " + url.toNormalform(true, false));
return response;
@@ -236,7 +237,7 @@ public final class LoaderDispatcher {
}
// check case where we want results from the cache exclusively, and never from the internet (offline mode)
- if (cacheStrategy == CrawlProfile.CacheStrategy.CACHEONLY) {
+ if (cacheStrategy == CacheStrategy.CACHEONLY) {
// we had a chance to get the content from the cache .. its over. We don't have it.
throw new IOException("cache only strategy");
}
@@ -299,7 +300,7 @@ public final class LoaderDispatcher {
* @return the content as {@link byte[]}
* @throws IOException
*/
- public byte[] loadContent(final Request request, final CrawlProfile.CacheStrategy cacheStrategy) throws IOException {
+ public byte[] loadContent(final Request request, final CacheStrategy cacheStrategy) throws IOException {
// try to download the resource using the loader
final long maxFileSize = this.sb.getConfigLong("crawler.http.maxFileSize", HTTPLoader.DEFAULT_MAXFILESIZE);
final Response entry = load(request, cacheStrategy, maxFileSize, false);
@@ -309,7 +310,7 @@ public final class LoaderDispatcher {
return entry.getContent();
}
- public Document[] loadDocuments(final Request request, final CrawlProfile.CacheStrategy cacheStrategy, final int timeout, final long maxFileSize) throws IOException, Parser.Failure {
+ public Document[] loadDocuments(final Request request, final CacheStrategy cacheStrategy, final int timeout, final long maxFileSize) throws IOException, Parser.Failure {
// load resource
final Response response = load(request, cacheStrategy, maxFileSize, false);
@@ -323,7 +324,7 @@ public final class LoaderDispatcher {
return response.parse();
}
- public ContentScraper parseResource(final DigestURI location, final CrawlProfile.CacheStrategy cachePolicy) throws IOException {
+ public ContentScraper parseResource(final DigestURI location, final CacheStrategy cachePolicy) throws IOException {
// load page
final long maxFileSize = this.sb.getConfigLong("crawler.http.maxFileSize", HTTPLoader.DEFAULT_MAXFILESIZE);
final Response r = this.load(request(location, true, false), cachePolicy, maxFileSize, false);
@@ -344,7 +345,7 @@ public final class LoaderDispatcher {
* @return a map from URLs to the anchor texts of the urls
* @throws IOException
*/
- public final Map<MultiProtocolURI, String> loadLinks(final DigestURI url, final CrawlProfile.CacheStrategy cacheStrategy) throws IOException {
+ public final Map<MultiProtocolURI, String> loadLinks(final DigestURI url, final CacheStrategy cacheStrategy) throws IOException {
final Response response = load(request(url, true, false), cacheStrategy, Long.MAX_VALUE, false);
if (response == null) throw new IOException("response == null");
final ResponseHeader responseHeader = response.getResponseHeader();
@@ -378,11 +379,11 @@ public final class LoaderDispatcher {
}
public void loadIfNotExistBackground(final String url, final File cache, final long maxFileSize) {
- new Loader(url, cache, maxFileSize, CrawlProfile.CacheStrategy.IFEXIST).start();
+ new Loader(url, cache, maxFileSize, CacheStrategy.IFEXIST).start();
}
public void loadIfNotExistBackground(final String url, final long maxFileSize) {
- new Loader(url, null, maxFileSize, CrawlProfile.CacheStrategy.IFEXIST).start();
+ new Loader(url, null, maxFileSize, CacheStrategy.IFEXIST).start();
}
private class Loader extends Thread {
@@ -390,9 +391,9 @@ public final class LoaderDispatcher {
private final String url;
private final File cache;
private final long maxFileSize;
- private final CrawlProfile.CacheStrategy cacheStrategy;
+ private final CacheStrategy cacheStrategy;
- public Loader(final String url, final File cache, final long maxFileSize, final CrawlProfile.CacheStrategy cacheStrategy) {
+ public Loader(final String url, final File cache, final long maxFileSize, final CacheStrategy cacheStrategy) {
this.url = url;
this.cache = cache;
this.maxFileSize = maxFileSize;