Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
tried to clean up the search process mess
Michael Peter Christen6629e376855c
diff --git a/htroot/IndexControlRWIs_p.java b/htroot/IndexControlRWIs_p.javaindex 45bdb1f78..295e6353d 100644--- a/htroot/IndexControlRWIs_p.java+++ b/htroot/IndexControlRWIs_p.java@@ -35,7 +35,6 @@ import java.util.List;import net.yacy.cora.date.GenericFormatter;import net.yacy.cora.document.ASCII;-import net.yacy.cora.document.UTF8;import net.yacy.cora.federate.yacy.CacheStrategy;import net.yacy.cora.protocol.RequestHeader;import net.yacy.cora.storage.HandleSet;@@ -61,12 +60,13 @@ import net.yacy.peers.Protocol;import net.yacy.peers.Seed;import net.yacy.repository.Blacklist.BlacklistType;import net.yacy.search.Switchboard;+import net.yacy.search.SwitchboardConstants;import net.yacy.search.index.Segment;import net.yacy.search.query.QueryParams;-import net.yacy.search.query.RWIProcess;+import net.yacy.search.query.RankingProcess;+import net.yacy.search.query.SearchEvent;import net.yacy.search.query.SearchEventCache;import net.yacy.search.ranking.BlockRank;-import net.yacy.search.ranking.ReferenceOrder;import net.yacy.server.serverObjects;import net.yacy.server.serverSwitch;@@ -125,8 +125,8 @@ public class IndexControlRWIs_p {if ( post.containsKey("keystringsearch") ) {prop.put("keyhash", keyhash);- final RWIProcess ranking = genSearchresult(prop, sb, segment, keyhash, null);- if ( ranking.rwiAvailableCount() == 0 ) {+ final SearchEvent theSearch = genSearchresult(prop, sb, segment, keyhash, null);+ if ( theSearch.rankingProcess.rwiAvailableCount() == 0 ) {prop.put("searchresult", 1);prop.putHTML("searchresult_word", keystring);}@@ -136,8 +136,8 @@ public class IndexControlRWIs_p {if ( keystring.isEmpty() || !ByteBuffer.equals(Word.word2hash(keystring), keyhash) ) {prop.put("keystring", "<" + errmsg + ">");}- final RWIProcess ranking = genSearchresult(prop, sb, segment, keyhash, null);- if ( ranking.rwiAvailableCount() == 0 ) {+ final SearchEvent theSearch = genSearchresult(prop, sb, segment, keyhash, null);+ if ( theSearch.rankingProcess.rwiAvailableCount() == 0 ) {prop.put("searchresult", 2);prop.putHTML("searchresult_wordhash", ASCII.String(keyhash));}@@ -232,8 +232,8 @@ public class IndexControlRWIs_p {}final Bitfield flags = compileFlags(post);final int count = (post.get("lines", "all").equals("all")) ? -1 : post.getInt("lines", -1);- final RWIProcess ranking = genSearchresult(prop, sb, segment, keyhash, flags);- genURLList(prop, keyhash, keystring, ranking, flags, count);+ final SearchEvent theSearch = genSearchresult(prop, sb, segment, keyhash, flags);+ genURLList(prop, keyhash, keystring, theSearch, flags, count);}// transfer to other peer@@ -459,14 +459,14 @@ public class IndexControlRWIs_p {final serverObjects prop,final byte[] keyhash,final String keystring,- final RWIProcess ranked,+ final SearchEvent theSearch,final Bitfield flags,final int maxlines) {// search for a word hash and generate a list of url linksfinal String keyhashs = ASCII.String(keyhash);prop.put("genUrlList_keyHash", keyhashs);- if ( ranked.rwiAvailableCount() == 0 ) {+ if ( theSearch.rankingProcess.rwiAvailableCount() == 0 ) {prop.put("genUrlList", 1);prop.put("genUrlList_count", 0);prop.put("searchresult", 2);@@ -480,7 +480,7 @@ public class IndexControlRWIs_p {URIMetadataNode entry;String us;long rn = -1;- while ( !ranked.rwiIsEmpty() && (entry = ranked.takeURL(false, 1000)) != null ) {+ while ( !theSearch.rankingProcess.rwiIsEmpty() && (entry = theSearch.takeURL(false, 1000)) != null ) {url = entry.url();if ( url == null ) {continue;@@ -507,9 +507,9 @@ public class IndexControlRWIs_p {prop.putNum("genUrlList_urlList_" + i + "_urlExists_tf", 1000.0 * entry.word().termFrequency());- prop.putNum("genUrlList_urlList_" + i + "_urlExists_authority", (ranked.getOrder() == null)+ prop.putNum("genUrlList_urlList_" + i + "_urlExists_authority", (theSearch.rankingProcess.getOrder() == null)? -1- : ranked.getOrder().authority(ASCII.String(entry.hash(), 6, 6)));+ : theSearch.rankingProcess.getOrder().authority(ASCII.String(entry.hash(), 6, 6)));prop.put("genUrlList_urlList_" + i + "_urlExists_date",GenericFormatter.SHORT_DAY_FORMATTER.format(new Date(entry.word().lastModified())));@@ -575,7 +575,7 @@ public class IndexControlRWIs_p {break;}}- final Iterator<byte[]> iter = ranked.miss(); // iterates url hash strings+ final Iterator<byte[]> iter = theSearch.rankingProcess.miss(); // iterates url hash stringsbyte[] b;while ( iter.hasNext() ) {b = iter.next();@@ -666,18 +666,17 @@ public class IndexControlRWIs_p {prop.put("searchresult_hosts", hc);}- public static RWIProcess genSearchresult(+ public static SearchEvent 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 RWIProcess ranked = new RWIProcess(query, order, false);- ranked.run();-++ final QueryParams query = new QueryParams(ASCII.String(keyhash), -1, filter, segment, sb.getRanking(), "IndexControlRWIs_p");+ final SearchEvent theSearch = SearchEventCache.getEvent(query, sb.peers, sb.tables, null, false, sb.loader, Integer.MAX_VALUE, Long.MAX_VALUE, (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_ROBINSON, 0), (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_MULTIWORD, 0));+ //theSearch.rankingProcess.run();+ RankingProcess ranked = theSearch.rankingProcess;if ( ranked.rwiAvailableCount() == 0 ) {prop.put("searchresult", 2);prop.put("searchresult_wordhash", keyhash);@@ -697,6 +696,6 @@ public class IndexControlRWIs_p {prop.put("searchresult_app", ranked.flagCount()[Condenser.flag_cat_hasapp]);prop.put("searchresult_indexof", ranked.flagCount()[Condenser.flag_cat_indexof]);}- return ranked;+ return theSearch;}}diff --git a/htroot/yacy/search.java b/htroot/yacy/search.javaindex d71216513..d559e7d8b 100644--- a/htroot/yacy/search.java+++ b/htroot/yacy/search.java@@ -71,6 +71,7 @@ import net.yacy.search.query.AccessTracker;import net.yacy.search.query.QueryParams;import net.yacy.search.query.SearchEvent;import net.yacy.search.query.SearchEventCache;+import net.yacy.search.query.SearchEventType;import net.yacy.search.ranking.RankingProfile;import net.yacy.search.snippet.ResultEntry;import net.yacy.server.serverCore;@@ -257,7 +258,7 @@ public final class search {//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.query_include_hashes, QueryParams.hashes2Handles(urls));- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEvent.Type.COLLECTION, "", incc.size(), System.currentTimeMillis() - timer), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEventType.COLLECTION, "", incc.size(), System.currentTimeMillis() - timer), false);if (incc != null) {final Iterator<Map.Entry<byte[], ReferenceContainer<WordReference>>> ci = incc.entrySet().iterator();Map.Entry<byte[], ReferenceContainer<WordReference>> entry;@@ -323,7 +324,7 @@ public final class search {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().rwiAvailableCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount();+ joincount = theSearch.rankingProcess.rwiAvailableCount() - theSearch.rankingProcess.getMissCount() - theSearch.getSortOutCount();prop.put("joincount", Integer.toString(joincount));if (joincount != 0) {accu = theSearch.result().completeResults(maxtime);@@ -385,7 +386,7 @@ public final class search {i++;}prop.put("references", (refstr.length() > 0) ? refstr.substring(1) : refstr.toString());- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEvent.Type.REFERENCECOLLECTION, "", i, System.currentTimeMillis() - timer), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEventType.REFERENCECOLLECTION, "", i, System.currentTimeMillis() - timer), false);}prop.put("indexabstract", indexabstract.toString());@@ -413,7 +414,7 @@ public final class search {theQuery.transmitcount = accu.size() + 1;prop.put("links", links.toString());prop.put("linkcount", accu.size());- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEvent.Type.RESULTLIST, "", accu.size(), System.currentTimeMillis() - timer), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEventType.RESULTLIST, "", accu.size(), System.currentTimeMillis() - timer), false);}// prepare search statisticsdiff --git a/htroot/yacysearch.java b/htroot/yacysearch.javaindex b468cea7e..e6aff9cb0 100644--- a/htroot/yacysearch.java+++ b/htroot/yacysearch.java@@ -80,6 +80,7 @@ import net.yacy.search.query.AccessTracker;import net.yacy.search.query.QueryParams;import net.yacy.search.query.SearchEvent;import net.yacy.search.query.SearchEventCache;+import net.yacy.search.query.SearchEventType;import net.yacy.search.query.SnippetProcess;import net.yacy.search.ranking.RankingProfile;import net.yacy.search.snippet.TextSnippet;@@ -766,7 +767,7 @@ public class yacysearch {EventTracker.delete(EventTracker.EClass.SEARCH);EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true),- SearchEvent.Type.INITIALIZATION,+ SearchEventType.INITIALIZATION,"",0,0), false);@@ -832,26 +833,26 @@ public class yacysearch {+ theQuery.queryString+ " - "+ "local-unfiltered("- + theSearch.getRankingResult().rwiAvailableCount()+ + theSearch.rankingProcess.rwiAvailableCount()+ "), "+ "local_miss("- + theSearch.getRankingResult().getMissCount()+ + theSearch.rankingProcess.getMissCount()+ "), "+ "local_sortout("- + theSearch.getRankingResult().getSortOutCount()+ + theSearch.getSortOutCount()+ "), "+ "remote("- + theSearch.getRankingResult().getRemoteResourceSize()+ + theSearch.rankingProcess.getRemoteResourceSize()+ ") links found, "+ (System.currentTimeMillis() - timestamp)+ " ms");// prepare search statisticstheQuery.resultcount =- theSearch.getRankingResult().rwiAvailableCount()- - theSearch.getRankingResult().getMissCount()- - theSearch.getRankingResult().getSortOutCount()- + theSearch.getRankingResult().getRemoteIndexCount();+ theSearch.rankingProcess.rwiAvailableCount()+ - theSearch.getSortOutCount()+ - theSearch.rankingProcess.getMissCount()+ + theSearch.rankingProcess.getRemoteIndexCount();theQuery.searchtime = System.currentTimeMillis() - timestamp;theQuery.urlretrievaltime = theSearch.result().getURLRetrievalTime();theQuery.snippetcomputationtime = theSearch.result().getSnippetComputationTime();@@ -933,10 +934,10 @@ public class yacysearch {}final int indexcount =- theSearch.getRankingResult().rwiAvailableCount()- - theSearch.getRankingResult().getMissCount()- - theSearch.getRankingResult().getSortOutCount()- + theSearch.getRankingResult().getRemoteIndexCount();+ theSearch.rankingProcess.rwiAvailableCount()+ - theSearch.getSortOutCount()+ - theSearch.rankingProcess.getMissCount()+ + theSearch.rankingProcess.getRemoteIndexCount();prop.put("num-results_offset", startRecord == 0 ? 0 : startRecord + 1);prop.put("num-results_itemscount", Formatter.number(startRecord + theSearch.getQuery().itemsPerPage > indexcount ? startRecord@@ -950,19 +951,19 @@ public class yacysearch {: "0");prop.put("num-results_globalresults_localResourceSize",- Formatter.number(theSearch.getRankingResult().rwiAvailableCount(), true));+ Formatter.number(theSearch.rankingProcess.rwiAvailableCount(), true));prop.put("num-results_globalresults_localMissCount",- Formatter.number(theSearch.getRankingResult().getMissCount(), true));+ Formatter.number(theSearch.rankingProcess.getMissCount(), true));prop.put("num-results_globalresults_remoteResourceSize",- Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));+ Formatter.number(theSearch.rankingProcess.getRemoteResourceSize(), true));prop.put("num-results_globalresults_remoteIndexCount",- Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));+ Formatter.number(theSearch.rankingProcess.getRemoteIndexCount(), true));prop.put("num-results_globalresults_remotePeerCount",- Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));+ Formatter.number(theSearch.rankingProcess.getRemotePeerCount(), true));// compose page navigationfinal StringBuilder resnav = new StringBuilder(200);diff --git a/htroot/yacysearchitem.java b/htroot/yacysearchitem.javaindex f40c6a932..8df838dc5 100644--- a/htroot/yacysearchitem.java+++ b/htroot/yacysearchitem.java@@ -44,9 +44,11 @@ import net.yacy.peers.graphics.ProfilingGraph;import net.yacy.search.EventTracker;import net.yacy.search.Switchboard;import net.yacy.search.SwitchboardConstants;+import net.yacy.search.query.HeuristicResult;import net.yacy.search.query.QueryParams;import net.yacy.search.query.SearchEvent;import net.yacy.search.query.SearchEventCache;+import net.yacy.search.query.SearchEventType;import net.yacy.search.snippet.ResultEntry;import net.yacy.search.snippet.TextSnippet;import net.yacy.server.serverObjects;@@ -90,17 +92,17 @@ public class yacysearchitem {final QueryParams theQuery = theSearch.getQuery();// dynamically update count values- final int totalcount = theSearch.getRankingResult().rwiAvailableCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount();+ final int totalcount = theSearch.rankingProcess.rwiAvailableCount() - theSearch.rankingProcess.getMissCount() - theSearch.getSortOutCount() + theSearch.rankingProcess.getRemoteIndexCount();final int offset = theQuery.neededResults() - theQuery.itemsPerPage() + 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().rwiAvailableCount(), 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));+ prop.put("localResourceSize", Formatter.number(theSearch.rankingProcess.rwiAvailableCount(), true));+ prop.put("localMissCount", Formatter.number(theSearch.rankingProcess.getMissCount(), true));+ prop.put("remoteResourceSize", Formatter.number(theSearch.rankingProcess.getRemoteResourceSize(), true));+ prop.put("remoteIndexCount", Formatter.number(theSearch.rankingProcess.getRemoteIndexCount(), true));+ prop.put("remotePeerCount", Formatter.number(theSearch.rankingProcess.getRemotePeerCount(), true));prop.put("navurlBase", QueryParams.navurlBase("html", theQuery, null, theQuery.urlMask.toString(), theQuery.navigators).toString());final String target_special_pattern = sb.getConfig(SwitchboardConstants.SEARCH_TARGET_SPECIAL_PATTERN, "");@@ -222,7 +224,7 @@ public class yacysearchitem {prop.put("content_description", desc);prop.putXML("content_description-xml", desc);prop.putJSON("content_description-json", desc);- final SearchEvent.HeuristicResult heuristic = theSearch.getHeuristic(result.hash());+ final HeuristicResult heuristic = theSearch.getHeuristic(result.hash());if (heuristic == null) {prop.put("content_heuristic", 0);} else {@@ -233,7 +235,7 @@ public class yacysearchitem {}prop.put("content_heuristic_name", heuristic.heuristicName);}- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEvent.Type.FINALIZATION, "" + item, 0, 0), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEventType.FINALIZATION, "" + item, 0, 0), false);final String ext = resultURL.getFileExtension().toLowerCase();if (ext.equals("png") || ext.equals("jpg") || ext.equals("gif")) {final String license = sb.licensedURLs.aquireLicense(resultURL);diff --git a/htroot/yacysearchlatestinfo.java b/htroot/yacysearchlatestinfo.javaindex ae92ec0c9..92d6a3a4d 100644--- a/htroot/yacysearchlatestinfo.java+++ b/htroot/yacysearchlatestinfo.java@@ -33,17 +33,17 @@ public class yacysearchlatestinfo {final QueryParams theQuery = theSearch.getQuery();// dynamically update count values- final int totalcount = theSearch.getRankingResult().rwiAvailableCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount();+ final int totalcount = theSearch.rankingProcess.rwiAvailableCount() - theSearch.rankingProcess.getMissCount() - theSearch.getSortOutCount() + theSearch.rankingProcess.getRemoteIndexCount();final int offset = theQuery.neededResults() - theQuery.itemsPerPage() + 1;prop.put("offset", offset);prop.put("itemscount",Formatter.number(offset + theSearch.getQuery().itemsPerPage >= totalcount ? offset + totalcount % theSearch.getQuery().itemsPerPage - 1 : offset + theSearch.getQuery().itemsPerPage - 1));prop.put("itemsperpage", theSearch.getQuery().itemsPerPage);prop.put("totalcount", Formatter.number(totalcount, true));- prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().rwiAvailableCount(), 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));+ prop.put("localResourceSize", Formatter.number(theSearch.rankingProcess.rwiAvailableCount(), true));+ prop.put("localMissCount", Formatter.number(theSearch.rankingProcess.getMissCount(), true));+ prop.put("remoteResourceSize", Formatter.number(theSearch.rankingProcess.getRemoteResourceSize(), true));+ prop.put("remoteIndexCount", Formatter.number(theSearch.rankingProcess.getRemoteIndexCount(), true));+ prop.put("remotePeerCount", Formatter.number(theSearch.rankingProcess.getRemotePeerCount(), true));prop.putJSON("navurlBase", QueryParams.navurlBase("html", theQuery, null, theQuery.urlMask.toString(), theQuery.navigators).toString());return prop;diff --git a/htroot/yacysearchtrailer.java b/htroot/yacysearchtrailer.javaindex 4cf8e9672..25bfc5e7a 100644--- a/htroot/yacysearchtrailer.java+++ b/htroot/yacysearchtrailer.java@@ -37,6 +37,7 @@ import net.yacy.search.EventTracker;import net.yacy.search.query.QueryParams;import net.yacy.search.query.SearchEvent;import net.yacy.search.query.SearchEventCache;+import net.yacy.search.query.SearchEventType;import net.yacy.server.serverObjects;import net.yacy.server.serverSwitch;@@ -338,7 +339,7 @@ public class yacysearchtrailer {final String aboutBody = env.getConfig("about.body", "");final String aboutHeadline = env.getConfig("about.headline", "");if ((aboutBody.isEmpty() && aboutHeadline.isEmpty()) ||- theSearch.getRankingResult().rwiAvailableCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount() == 0) {+ theSearch.rankingProcess.rwiAvailableCount() - theSearch.rankingProcess.getMissCount() - theSearch.getSortOutCount() + theSearch.rankingProcess.getRemoteIndexCount() == 0) {prop.put("nav-about", 0);} else {prop.put("nav-about", 1);@@ -349,7 +350,7 @@ public class yacysearchtrailer {// category: location search// show only if there is a location database present and if there had been any search resultsif (LibraryProvider.geoLoc.isEmpty() ||- theSearch.getRankingResult().rwiAvailableCount() == 0) {+ theSearch.rankingProcess.rwiAvailableCount() == 0) {prop.put("cat-location", 0);} else {prop.put("cat-location", 1);@@ -357,10 +358,10 @@ public class yacysearchtrailer {prop.put(fileType, "cat-location_queryenc", theQuery.queryString(true).replace(' ', '+'));}- final int indexcount = theSearch.getRankingResult().rwiAvailableCount() - theSearch.getRankingResult().getMissCount() - theSearch.getRankingResult().getSortOutCount() + theSearch.getRankingResult().getRemoteIndexCount();+ final int indexcount = theSearch.rankingProcess.rwiAvailableCount() - theSearch.rankingProcess.getMissCount() - theSearch.getSortOutCount() + theSearch.rankingProcess.getRemoteIndexCount();prop.put("num-results_totalcount", indexcount);- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEvent.Type.FINALIZATION, "bottomline", 0, 0), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theQuery.id(true), SearchEventType.FINALIZATION, "bottomline", 0, 0), false);return prop;}diff --git a/source/net/yacy/peers/Protocol.java b/source/net/yacy/peers/Protocol.javaindex 8c5705d74..36fe29735 100644--- a/source/net/yacy/peers/Protocol.java+++ b/source/net/yacy/peers/Protocol.java@@ -103,6 +103,7 @@ import net.yacy.search.Switchboard;import net.yacy.search.SwitchboardConstants;import net.yacy.search.index.Segment;import net.yacy.search.query.SearchEvent;+import net.yacy.search.query.SecondarySearchSuperviser;import net.yacy.search.snippet.TextSnippet;import net.yacy.server.serverCore;import net.yacy.server.serverObjects;@@ -603,7 +604,7 @@ public final class Protocolfinal int maxDistance,final int partitions,final Seed target,- final SearchEvent.SecondarySearchSuperviser secondarySearchSuperviser,+ final SecondarySearchSuperviser secondarySearchSuperviser,final Blacklist blacklist) {// send a search request to peer with remote Hash@@ -621,7 +622,7 @@ public final class Protocol// duetime : maximum time that a peer should spent to create a resultfinal long timestamp = System.currentTimeMillis();- event.rankingProcess.addExpectedRemoteReferences(count);+ event.addExpectedRemoteReferences(count);SearchResult result;try {result =@@ -701,7 +702,7 @@ public final class Protocolfinal Blacklist blacklist) {final long timestamp = System.currentTimeMillis();- event.rankingProcess.addExpectedRemoteReferences(count);+ event.addExpectedRemoteReferences(count);SearchResult result;try {result =@@ -847,7 +848,7 @@ public final class Protocol// one is enough, only the references are used, not the wordevent.rankingProcess.add(container.get(0), false, target.getName() + "/" + target.hash, result.joincount, time);event.rankingProcess.addFinalize();- event.rankingProcess.addExpectedRemoteReferences(-count);+ event.addExpectedRemoteReferences(-count);// insert the containers to the indexfor ( final ReferenceContainer<WordReference> c : container ) {@@ -901,7 +902,7 @@ public final class Protocolfinal int partitions,final String hostname,final String hostaddress,- final SearchEvent.SecondarySearchSuperviser secondarySearchSuperviser+ final SecondarySearchSuperviser secondarySearchSuperviser) throws IOException {// send a search request to peer with remote Hash@@ -1027,7 +1028,7 @@ public final class Protocolif (event.getQuery().queryString == null || event.getQuery().queryString.length() == 0) {return -1; // we cannot query solr only with word hashes, there is no clear text string}- event.rankingProcess.addExpectedRemoteReferences(count);+ event.addExpectedRemoteReferences(count);SolrDocumentList docList = null;final SolrQuery solrQuery = event.getQuery().solrQuery();solrQuery.setStart(offset);@@ -1120,14 +1121,14 @@ public final class Protocol}if (localsearch) {- event.rankingProcess.add(container, true, "localpeer", docList.size());+ event.add(container, true, "localpeer", docList.size());event.rankingProcess.addFinalize();- event.rankingProcess.addExpectedRemoteReferences(-count);+ event.addExpectedRemoteReferences(-count);Network.log.logInfo("local search (solr): localpeer sent " + container.get(0).size() + "/" + docList.size() + " references");} else {- event.rankingProcess.add(container, false, target.getName() + "/" + target.hash, docList.size());+ event.add(container, false, target.getName() + "/" + target.hash, docList.size());event.rankingProcess.addFinalize();- event.rankingProcess.addExpectedRemoteReferences(-count);+ event.addExpectedRemoteReferences(-count);Network.log.logInfo("remote search (solr): peer " + target.getName() + " sent " + container.get(0).size() + "/" + docList.size() + " references");}}diff --git a/source/net/yacy/peers/RemoteSearch.java b/source/net/yacy/peers/RemoteSearch.javaindex 1ef635b7c..e9a94e0bc 100644--- a/source/net/yacy/peers/RemoteSearch.java+++ b/source/net/yacy/peers/RemoteSearch.java@@ -35,6 +35,7 @@ import net.yacy.kelondro.logging.Log;import net.yacy.repository.Blacklist;import net.yacy.search.query.QueryParams;import net.yacy.search.query.SearchEvent;+import net.yacy.search.query.SecondarySearchSuperviser;public class RemoteSearch extends Thread {@@ -44,7 +45,7 @@ public class RemoteSearch extends Thread {final private SearchEvent event;final private String wordhashes, excludehashes, sitehash, authorhash, contentdom;final private int partitions;- final private SearchEvent.SecondarySearchSuperviser secondarySearchSuperviser;+ final private SecondarySearchSuperviser secondarySearchSuperviser;final private Blacklist blacklist;final private Seed targetPeer;private int urls;@@ -67,7 +68,7 @@ public class RemoteSearch extends Thread {final int maxDistance,final int partitions,final Seed targetPeer,- final SearchEvent.SecondarySearchSuperviser secondarySearchSuperviser,+ final SecondarySearchSuperviser secondarySearchSuperviser,final Blacklist blacklist) {super(ysThreadGroup, "yacySearch_" + targetPeer.getName());this.event = event;@@ -129,14 +130,6 @@ public class RemoteSearch extends Thread {return wh.toString();}- public int links() {- return this.urls;- }-- public int count() {- return this.count;- }-public Seed target() {return this.targetPeer;}diff --git a/source/net/yacy/peers/graphics/ProfilingGraph.java b/source/net/yacy/peers/graphics/ProfilingGraph.javaindex e8fd8c12d..7a7dfa116 100644--- a/source/net/yacy/peers/graphics/ProfilingGraph.java+++ b/source/net/yacy/peers/graphics/ProfilingGraph.java@@ -31,7 +31,7 @@ import java.util.Iterator;import net.yacy.search.EventTracker;import net.yacy.search.EventTracker.Event;-import net.yacy.search.query.SearchEvent;+import net.yacy.search.query.SearchEventType;import net.yacy.visualization.ChartPlotter;import net.yacy.visualization.RasterPlotter;@@ -199,13 +199,13 @@ public class ProfilingGraph {}public static class EventSearch {- public SearchEvent.Type processName;+ public SearchEventType processName;public String comment;public String queryID;public long duration;public int resultCount;- public EventSearch(final String queryID, final SearchEvent.Type processName, final String comment, final int resultCount, final long duration) {+ public EventSearch(final String queryID, final SearchEventType processName, final String comment, final int resultCount, final long duration) {this.queryID = queryID;this.processName = processName;this.comment = comment;diff --git a/source/net/yacy/search/Switchboard.java b/source/net/yacy/search/Switchboard.javaindex ae7713fbc..6f5dbc489 100644--- a/source/net/yacy/search/Switchboard.java+++ b/source/net/yacy/search/Switchboard.java@@ -3244,7 +3244,7 @@ public final class Switchboard extends serverSwitch {}final Map<MultiProtocolURI, String> links;- searchEvent.getRankingResult().oneFeederStarted();+ searchEvent.rankingProcess.oneFeederStarted();try {links = Switchboard.this.loader.loadLinks(url, CacheStrategy.NOCACHE, BlacklistType.SEARCH, TextSnippet.snippetMinLoadDelay);if ( links != null ) {@@ -3261,7 +3261,7 @@ public final class Switchboard extends serverSwitch {} catch ( final Throwable e ) {Log.logException(e);} finally {- searchEvent.getRankingResult().oneFeederTerminated();+ searchEvent.rankingProcess.oneFeederTerminated();}}}.start();@@ -3346,7 +3346,7 @@ public final class Switchboard extends serverSwitch {// if we have an url then try to load the rssRSSReader rss = null;- searchEvent.getRankingResult().oneFeederStarted();+ searchEvent.rankingProcess.oneFeederStarted();try {final Response response =Switchboard.this.loader.load(Switchboard.this.loader.request(url, true, false), CacheStrategy.NOCACHE, BlacklistType.SEARCH, TextSnippet.snippetMinLoadDelay);@@ -3375,7 +3375,7 @@ public final class Switchboard extends serverSwitch {} catch ( final Throwable e ) {//Log.logException(e);} finally {- searchEvent.getRankingResult().oneFeederTerminated();+ searchEvent.rankingProcess.oneFeederTerminated();}}}.start();diff --git a/source/net/yacy/search/index/DocumentIndex.java b/source/net/yacy/search/index/DocumentIndex.javaindex 8f9601486..518bf21a7 100644--- a/source/net/yacy/search/index/DocumentIndex.java+++ b/source/net/yacy/search/index/DocumentIndex.java@@ -29,25 +29,17 @@ package net.yacy.search.index;import java.io.File;import java.io.IOException;import java.net.MalformedURLException;-import java.util.ArrayList;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import org.apache.solr.common.SolrInputDocument;-import net.yacy.cora.document.Classification;-import net.yacy.cora.document.UTF8;import net.yacy.document.Condenser;import net.yacy.document.Document;import net.yacy.document.LibraryProvider;import net.yacy.document.TextParser;import net.yacy.kelondro.data.meta.DigestURI;-import net.yacy.kelondro.data.meta.URIMetadataNode;import net.yacy.kelondro.logging.Log;-import net.yacy.search.query.QueryParams;-import net.yacy.search.query.RWIProcess;-import net.yacy.search.ranking.RankingProfile;-import net.yacy.search.ranking.ReferenceOrder;/*** convenience class to access the yacycore library from outside of yacy to put files into the index@@ -56,9 +48,6 @@ import net.yacy.search.ranking.ReferenceOrder;*/public class DocumentIndex extends Segment {- private static final RankingProfile textRankingDefault = new RankingProfile(Classification.ContentDomain.TEXT);- //private Bitfield zeroConstraint = new Bitfield(4);-private static DigestURI poison;static {try {@@ -218,34 +207,6 @@ public class DocumentIndex extends Segment {}}- /**- * do a full-text search of a given string and return a specific number of results- *- * @param querystring- * @param count- * @return a list of files that contain the given string- */- public ArrayList<DigestURI> find(final String querystring, int count) {- // make a query and start a search- final QueryParams query =- new QueryParams(querystring, count, null, this, textRankingDefault, "DocumentIndex");- final ReferenceOrder order = new ReferenceOrder(query.ranking, UTF8.getBytes(query.targetlang));- final RWIProcess rankedCache = new RWIProcess(query, order, false);- rankedCache.start();-- // search is running; retrieve results- URIMetadataNode row;- final ArrayList<DigestURI> files = new ArrayList<DigestURI>();- while ( (row = rankedCache.takeURL(false, 1000)) != null ) {- files.add(row.url());- count--;- if ( count == 0 ) {- break;- }- }- return files;- }-/*** close the index. This terminates all worker threads and then closes the segment.*/@@ -277,56 +238,4 @@ public class DocumentIndex extends Segment {public void fail(DigestURI f, String failReason);}- public static void main(final String[] args) {- // first argument: path to segment- // second argument: either 'add' or 'search'- // third and more arguments exists only in case that second argument is 'search': these are then the search words- //- // example:- // DocumentIndex yacyindex add test/parsertest- // DocumentIndex yacyindex search steht- System.setProperty("java.awt.headless", "true");- if ( args.length < 3 ) {- return;- }- final File segmentPath = new File(args[0]);- System.out.println("using index files at " + segmentPath.getAbsolutePath());- final CallbackListener callback = new CallbackListener() {- @Override- public void commit(final DigestURI f, final SolrInputDocument resultRow) {- System.out.println("indexed: " + f.toString());- }-- @Override- public void fail(final DigestURI f, final String failReason) {- System.out.println("not indexed " + f.toString() + ": " + failReason);- }- };- try {- if ( args[1].equals("add") ) {- final DigestURI f = new DigestURI(args[2]);- final DocumentIndex di = new DocumentIndex(segmentPath, null, callback, 100000);- di.addConcurrent(f);- di.close();- } else {- String query = "";- for ( int i = 2; i < args.length; i++ ) {- query += args[i];- }- query.trim();- final DocumentIndex di = new DocumentIndex(segmentPath, null, callback, 100000);- final ArrayList<DigestURI> results = di.find(query, 100);- for ( final DigestURI f : results ) {- if ( f != null ) {- System.out.println(f.toString());- }- }- di.close();- }- } catch ( final IOException e ) {- Log.logException(e);- }- //System.exit(0);- }-}diff --git a/source/net/yacy/search/index/Segment.java b/source/net/yacy/search/index/Segment.javaindex 094e5985d..7835df1fd 100644--- a/source/net/yacy/search/index/Segment.java+++ b/source/net/yacy/search/index/Segment.java@@ -71,7 +71,7 @@ import net.yacy.kelondro.util.Bitfield;import net.yacy.kelondro.util.ISO639;import net.yacy.repository.LoaderDispatcher;import net.yacy.search.Switchboard;-import net.yacy.search.query.RWIProcess;+import net.yacy.search.query.RankingProcess;import net.yacy.search.query.SearchEvent;public class Segment {@@ -375,7 +375,7 @@ public class Segment {// STORE PAGE INDEX INTO WORD INDEX DBint outlinksSame = document.inboundLinks().size();int outlinksOther = document.outboundLinks().size();- final RWIProcess rankingProcess = (searchEvent == null) ? null : searchEvent.getRankingResult();+ final RankingProcess rankingProcess = (searchEvent == null) ? null : searchEvent.getRankingResult();final int urlLength = urlNormalform.length();final int urlComps = MultiProtocolURI.urlComps(url.toString()).length;@@ -425,7 +425,7 @@ public class Segment {}}}- if (rankingProcess != null) rankingProcess.addFinalize();+ if (searchEvent != null) searchEvent.rankingProcess.addFinalize();// assign the catchall wordientry.setWord(wprop == null ? catchallWord : wprop); // we use one of the word properties as template to get the document characteristicsdiff --git a/source/net/yacy/search/query/HeuristicResult.java b/source/net/yacy/search/query/HeuristicResult.javanew file mode 100644index 000000000..34b2f4106--- /dev/null+++ b/source/net/yacy/search/query/HeuristicResult.java@@ -0,0 +1,50 @@+/**+ * HeuristicResult+ * Copyright 2012 by Michael Peter Christen, [email protected], Frankfurt a. M., Germany+ * First released 01.11.2012 at http://yacy.net+ *+ * 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/>.+ */++package net.yacy.search.query;++import net.yacy.cora.order.Base64Order;++public class HeuristicResult implements Comparable<HeuristicResult> {+ private final byte[] urlhash;+ public final String heuristicName;+ public final boolean redundant;++ public HeuristicResult(final byte[] urlhash, final String heuristicName, final boolean redundant) {+ this.urlhash = urlhash;+ this.heuristicName = heuristicName;+ this.redundant = redundant;+ }++ @Override+ public int compareTo(HeuristicResult o) {+ return Base64Order.enhancedCoder.compare(this.urlhash, o.urlhash);+ }++ @Override+ public int hashCode() {+ return (int) Base64Order.enhancedCoder.cardinal(this.urlhash);+ }++ @Override+ public boolean equals(Object o) {+ return Base64Order.enhancedCoder.equal(this.urlhash, ((HeuristicResult) o).urlhash);+ }+}diff --git a/source/net/yacy/search/query/QueryParams.java b/source/net/yacy/search/query/QueryParams.javaindex 131e4dc15..36602262e 100644--- a/source/net/yacy/search/query/QueryParams.java+++ b/source/net/yacy/search/query/QueryParams.java@@ -136,7 +136,7 @@ public final class QueryParams {public long searchtime, urlretrievaltime, snippetcomputationtime; // time to perform the search, to get all the urls, and to compute the snippetsprivate boolean specialRights; // is true if the user has a special authorization and my use more database-extensive optionspublic final String userAgent;- protected boolean filterfailurls;+ public boolean filterfailurls;protected double lat, lon, radius;diff --git a/source/net/yacy/search/query/RWIProcess.java b/source/net/yacy/search/query/RWIProcess.javadeleted file mode 100644index f1c04b45b..000000000--- a/source/net/yacy/search/query/RWIProcess.java+++ /dev/null@@ -1,1093 +0,0 @@-// RankingProcess.java-// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 07.11.2007 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate$-// $LastChangedRevision$-// $LastChangedBy$-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package net.yacy.search.query;--import java.util.Comparator;-import java.util.ConcurrentModificationException;-import java.util.HashMap;-import java.util.Iterator;-import java.util.List;-import java.util.Map;-import java.util.SortedMap;-import java.util.concurrent.BlockingQueue;-import java.util.concurrent.ConcurrentHashMap;-import java.util.concurrent.TimeUnit;-import java.util.concurrent.atomic.AtomicInteger;-import java.util.regex.Pattern;--import net.yacy.cora.document.ASCII;-import net.yacy.cora.document.Classification;-import net.yacy.cora.document.Classification.ContentDomain;-import net.yacy.cora.document.MultiProtocolURI;-import net.yacy.cora.federate.yacy.CacheStrategy;-import net.yacy.cora.lod.JenaTripleStore;-import net.yacy.cora.lod.vocabulary.Tagging;-import net.yacy.cora.lod.vocabulary.YaCyMetadata;-import net.yacy.cora.protocol.Scanner;-import net.yacy.cora.sorting.ClusteredScoreMap;-import net.yacy.cora.sorting.ConcurrentScoreMap;-import net.yacy.cora.sorting.ScoreMap;-import net.yacy.cora.sorting.WeakPriorityBlockingQueue;-import net.yacy.cora.sorting.WeakPriorityBlockingQueue.ReverseElement;-import net.yacy.cora.storage.HandleSet;-import net.yacy.cora.util.SpaceExceededException;-import net.yacy.document.Condenser;-import net.yacy.document.LibraryProvider;-import net.yacy.interaction.contentcontrol.ContentControlFilterUpdateThread;-import net.yacy.kelondro.data.meta.DigestURI;-import net.yacy.kelondro.data.meta.URIMetadataNode;-import net.yacy.kelondro.data.meta.URIMetadataRow;-import net.yacy.kelondro.data.word.Word;-import net.yacy.kelondro.data.word.WordReference;-import net.yacy.kelondro.data.word.WordReferenceVars;-import net.yacy.kelondro.index.RowHandleSet;-import net.yacy.kelondro.logging.Log;-import net.yacy.kelondro.rwi.ReferenceContainer;-import net.yacy.kelondro.rwi.TermSearch;-import net.yacy.kelondro.util.Bitfield;-import net.yacy.peers.graphics.ProfilingGraph;-import net.yacy.repository.Blacklist.BlacklistType;-import net.yacy.repository.FilterEngine;-import net.yacy.search.EventTracker;-import net.yacy.search.Switchboard;-import net.yacy.search.index.Segment;-import net.yacy.search.ranking.ReferenceOrder;-import net.yacy.search.snippet.ResultEntry;--import com.hp.hpl.jena.rdf.model.RDFNode;-import com.hp.hpl.jena.rdf.model.Resource;--public final class RWIProcess extends Thread-{-- private static final long maxWaitPerResult = 30;- private static final int max_results_preparation = 3000, max_results_preparation_special = -1; // -1 means 'no limit'-- private final QueryParams query;- private final HandleSet urlhashes; // map for double-check; String/Long relation, addresses ranking number (backreference for deletion)- private final int[] flagcount; // flag counter- private final HandleSet misses; // contains url-hashes that could not been found in the LURL-DB- private int sortout; // counter for referenced that had been sorted out for other reasons- //private final int[] domZones;- private SortedMap<byte[], ReferenceContainer<WordReference>> localSearchInclusion;-- private int remote_resourceSize;- private int remote_indexCount;- private int remote_peerCount;- private int local_indexCount;- private final AtomicInteger maxExpectedRemoteReferences, expectedRemoteReferences, receivedRemoteReferences;- private final WeakPriorityBlockingQueue<WordReferenceVars> rwiStack;- protected final WeakPriorityBlockingQueue<URIMetadataNode> nodeStack;- private final AtomicInteger feedersAlive, feedersTerminated;- private final ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>> doubleDomCache; // key = domhash (6 bytes); value = like stack- //private final HandleSet handover; // key = urlhash; used for double-check of urls that had been handed over to search process-- private final ScoreMap<String> ref; // reference score computation for the commonSense heuristic- private final Map<String, byte[]> hostResolver; // a mapping from a host hash (6 bytes) to the full url hash of one of these urls that have the host hash- private final ReferenceOrder order;- private boolean addRunning;- private final boolean remote;- private final long maxtime;-- // navigation scores- private final ScoreMap<String> hostNavigator; // a counter for the appearance of the host hash- private final ScoreMap<String> authorNavigator; // a counter for the appearances of authors- private final ScoreMap<String> namespaceNavigator; // a counter for name spaces- private final ScoreMap<String> protocolNavigator; // a counter for protocol types- private final ScoreMap<String> filetypeNavigator; // a counter for file types- private final Map<String, ScoreMap<String>> vocabularyNavigator; // counters for Vocabularies; key is metatag.getVocabularyName()- private final Map<String, String> taggingPredicates; // a map from tagging vocabulary names to tagging predicate uris-- public RWIProcess(final QueryParams query, final ReferenceOrder order, final boolean remote) {- // we collect the urlhashes and construct a list with urlEntry objects- // attention: if minEntries is too high, this method will not terminate within the maxTime- // sortorder: 0 = hash, 1 = url, 2 = ranking- this.addRunning = true;- this.localSearchInclusion = null;- int stackMaxsize = query.snippetCacheStrategy == null || query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? max_results_preparation_special : max_results_preparation;- this.rwiStack = new WeakPriorityBlockingQueue<WordReferenceVars>(stackMaxsize, false);- this.nodeStack = new WeakPriorityBlockingQueue<URIMetadataNode>(stackMaxsize, false);- this.doubleDomCache = new ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>>();- this.query = query;- this.order = order;- this.remote = remote;- this.remote_peerCount = 0;- this.remote_resourceSize = 0;- this.remote_indexCount = 0;- this.local_indexCount = 0;- this.urlhashes = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100);- this.misses = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100);- this.sortout = 0;- this.flagcount = new int[32];- for ( int i = 0; i < 32; i++ ) {- this.flagcount[i] = 0;- }- this.hostNavigator = new ConcurrentScoreMap<String>();- this.hostResolver = new ConcurrentHashMap<String, byte[]>();- this.authorNavigator = new ConcurrentScoreMap<String>();- this.namespaceNavigator = new ConcurrentScoreMap<String>();- this.protocolNavigator = new ConcurrentScoreMap<String>();- this.filetypeNavigator = new ConcurrentScoreMap<String>();- this.vocabularyNavigator = new ConcurrentHashMap<String, ScoreMap<String>>();- this.ref = new ConcurrentScoreMap<String>();- this.feedersAlive = new AtomicInteger(0);- this.feedersTerminated = new AtomicInteger(0);- this.maxExpectedRemoteReferences = new AtomicInteger(0);- this.expectedRemoteReferences = new AtomicInteger(0);- this.receivedRemoteReferences = new AtomicInteger(0);- this.maxtime = query.maxtime;-- // pre-calculate some values for navigation-- this.taggingPredicates = new HashMap<String, String>();- for (Tagging t: LibraryProvider.autotagging.getVocabularies()) {- this.taggingPredicates.put(t.getName(), t.getPredicate());- }- }-- public void addExpectedRemoteReferences(int x) {- if ( x > 0 ) {- this.maxExpectedRemoteReferences.addAndGet(x);- }- this.expectedRemoteReferences.addAndGet(x);- }-- protected boolean expectMoreRemoteReferences() {- return this.expectedRemoteReferences.get() > 0;- }-- protected long waitTimeRecommendation() {- return- this.maxExpectedRemoteReferences.get() == 0 ? 0 :- Math.min(maxWaitPerResult,- Math.min(- maxWaitPerResult * this.expectedRemoteReferences.get() / this.maxExpectedRemoteReferences.get(),- maxWaitPerResult * (100 - Math.min(100, this.receivedRemoteReferences.get())) / 100));- }-- public QueryParams getQuery() {- return this.query;- }-- public ReferenceOrder getOrder() {- return this.order;- }-- @Override- public void run() {-- // do a search- oneFeederStarted();-- // sort the local containers and truncate it to a limited count,- // so following sortings together with the global results will be fast- try {- final long timer = System.currentTimeMillis();- final TermSearch<WordReference> search =- this.query- .getSegment()- .termIndex()- .query(- this.query.query_include_hashes,- this.query.query_exclude_hashes,- null,- Segment.wordReferenceFactory,- this.query.maxDistance);- this.localSearchInclusion = search.inclusion();- final ReferenceContainer<WordReference> index = search.joined();- EventTracker.update(- EventTracker.EClass.SEARCH,- new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEvent.Type.JOIN,- this.query.queryString,- index.size(),- System.currentTimeMillis() - timer),- false);- if ( !index.isEmpty() ) {- add(index, true, "local index: " + this.query.getSegment().getLocation(), -1, this.maxtime);- addFinalize();- }- } catch ( final Exception e ) {- Log.logException(e);- } finally {- oneFeederTerminated();- }- }-- public void addFinalize() {- this.addRunning = false;- }-- public void add(- final List<URIMetadataNode> index,- final boolean local,- final String resourceName,- final int fullResource) {-- this.addRunning = true;- assert (index != null);- if (index.isEmpty()) return;-- if (!local) {- assert fullResource >= 0 : "fullResource = " + fullResource;- this.remote_resourceSize += fullResource;- this.remote_peerCount++;- }-- long timer = System.currentTimeMillis();-- // normalize entries- int is = index.size();- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEvent.Type.NORMALIZING,- resourceName,- is,- System.currentTimeMillis() - timer), false);- if (!local) {- this.receivedRemoteReferences.addAndGet(is);- }-- // iterate over normalized entries and select some that are better than currently stored- timer = System.currentTimeMillis();- final boolean nav_hosts = this.query.navigators.equals("all") || this.query.navigators.indexOf("hosts", 0) >= 0;-- // apply all constraints- try {- final String pattern = this.query.urlMask.pattern();- final boolean httpPattern = pattern.equals("http://.*");- final boolean noHttpButProtocolPattern = pattern.equals("https://.*") || pattern.equals("ftp://.*") || pattern.equals("smb://.*") || pattern.equals("file://.*");- pollloop: for (URIMetadataNode iEntry: index) {-- // doublecheck for urls- if (this.urlhashes.has(iEntry.hash())) {- continue pollloop;- }-- // increase flag counts- for ( int j = 0; j < 32; j++ ) {- if (iEntry.flags().get(j)) this.flagcount[j]++;- }-- // check constraints- Bitfield flags = iEntry.flags();- if (!testFlags(flags)) continue pollloop;-- // check document domain- if (this.query.contentdom.getCode() > 0 &&- ((this.query.contentdom == ContentDomain.AUDIO && !(flags.get(Condenser.flag_cat_hasaudio))) ||- (this.query.contentdom == ContentDomain.VIDEO && !(flags.get(Condenser.flag_cat_hasvideo))) ||- (this.query.contentdom == ContentDomain.IMAGE && !(flags.get(Condenser.flag_cat_hasimage))) ||- (this.query.contentdom == ContentDomain.APP && !(flags.get(Condenser.flag_cat_hasapp))))) {- continue pollloop;- }-- // check site constraints- final String hosthash = iEntry.hosthash();- if ( this.query.sitehash == null ) {- if (this.query.siteexcludes != null && this.query.siteexcludes.contains(hosthash)) {- continue pollloop;- }- } else {- // filter out all domains that do not match with the site constraint- if (!hosthash.equals(this.query.sitehash)) continue pollloop;- }-- // collect host navigation information (even if we have only one; this is to provide a switch-off button)- if (this.query.navigators.isEmpty() && (nav_hosts || this.query.urlMask_isCatchall)) {- this.hostNavigator.inc(hosthash);- this.hostResolver.put(hosthash, iEntry.hash());- }-- // check protocol- if ( !this.query.urlMask_isCatchall ) {- final boolean httpFlagSet = DigestURI.flag4HTTPset(iEntry.hash());- if ( httpPattern && !httpFlagSet ) {- continue pollloop;- }- if ( noHttpButProtocolPattern && httpFlagSet ) {- continue pollloop;- }- }-- // check vocabulary constraint- String subject = YaCyMetadata.hashURI(iEntry.hash());- Resource resource = JenaTripleStore.getResource(subject);- if (this.query.metatags != null && !this.query.metatags.isEmpty()) {- // all metatags must appear in the tags list- for (Tagging.Metatag metatag: this.query.metatags) {- Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, metatag.getPredicate());- if (!ni.hasNext()) continue pollloop;- String tags = ni.next().toString();- if (tags.indexOf(metatag.getObject()) < 0) continue pollloop;- }- }-- // add navigators using the triplestore- for (Map.Entry<String, String> v: this.taggingPredicates.entrySet()) {- Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, v.getValue());- while (ni.hasNext()) {- String[] tags = ni.next().toString().split(",");- for (String tag: tags) {- ScoreMap<String> voc = this.vocabularyNavigator.get(v.getKey());- if (voc == null) {- voc = new ConcurrentScoreMap<String>();- this.vocabularyNavigator.put(v.getKey(), voc);- }- voc.inc(tag);- }- }- }-- // finally extend the double-check and insert result to stack- this.urlhashes.putUnique(iEntry.hash());- rankingtryloop: while (true) {- try {- this.nodeStack.put(new ReverseElement<URIMetadataNode>(iEntry, this.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)- break rankingtryloop;- } catch ( final ArithmeticException e ) {- // this may happen if the concurrent normalizer changes values during cardinal computation- continue rankingtryloop;- }- }- // increase counter for statistics- if (local) this.local_indexCount++; else this.remote_indexCount++;- }- } catch ( final SpaceExceededException e ) {- }-- //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true);- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEvent.Type.PRESORT,- resourceName,- index.size(),- System.currentTimeMillis() - timer), false);- }-- public void add(- final ReferenceContainer<WordReference> index,- final boolean local,- final String resourceName,- final int fullResource,- final long maxtime) {- // we collect the urlhashes and construct a list with urlEntry objects- // attention: if minEntries is too high, this method will not terminate within the maxTime- //Log.logInfo("RWIProcess", "added a container, size = " + index.size());-- this.addRunning = true;- assert (index != null);- if (index.isEmpty()) return;- if (!local) {- assert fullResource >= 0 : "fullResource = " + fullResource;- this.remote_resourceSize += fullResource;- this.remote_peerCount++;- }- long timer = System.currentTimeMillis();-- // normalize entries- final BlockingQueue<WordReferenceVars> decodedEntries = this.order.normalizeWith(index, maxtime);- int is = index.size();- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEvent.Type.NORMALIZING,- resourceName,- is,- System.currentTimeMillis() - timer), false);- if (!local) this.receivedRemoteReferences.addAndGet(is);-- // iterate over normalized entries and select some that are better than currently stored- timer = System.currentTimeMillis();- final boolean nav_hosts = this.query.navigators.equals("all") || this.query.navigators.indexOf("hosts", 0) >= 0;-- // apply all constraints- long timeout = System.currentTimeMillis() + maxtime;- try {- WordReferenceVars iEntry;- final String pattern = this.query.urlMask.pattern();- final boolean httpPattern = pattern.equals("http://.*");- final boolean noHttpButProtocolPattern = pattern.equals("https://.*") || pattern.equals("ftp://.*") || pattern.equals("smb://.*") || pattern.equals("file://.*");- long remaining;- pollloop: while ( true ) {- remaining = timeout - System.currentTimeMillis();- if (remaining <= 0) {- Log.logWarning("RWIProcess", "terminated 'add' loop before poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());- break;- }- iEntry = decodedEntries.poll(remaining, TimeUnit.MILLISECONDS);- if (iEntry == null) {- Log.logWarning("RWIProcess", "terminated 'add' loop after poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());- break pollloop;- }- if (iEntry == WordReferenceVars.poison) {- break pollloop;- }- assert (iEntry.urlhash().length == index.row().primaryKeyLength);-- // doublecheck for urls- if (this.urlhashes.has(iEntry.urlhash())) continue pollloop;-- // increase flag counts- Bitfield flags = iEntry.flags();- for (int j = 0; j < 32; j++) {- if (flags.get(j)) this.flagcount[j]++;- }-- // check constraints- if (!testFlags(flags)) continue pollloop;-- // check document domain- if (this.query.contentdom.getCode() > 0 &&- ((this.query.contentdom == ContentDomain.AUDIO && !(flags.get(Condenser.flag_cat_hasaudio))) ||- (this.query.contentdom == ContentDomain.VIDEO && !(flags.get(Condenser.flag_cat_hasvideo))) ||- (this.query.contentdom == ContentDomain.IMAGE && !(flags.get(Condenser.flag_cat_hasimage))) ||- (this.query.contentdom == ContentDomain.APP && !(flags.get(Condenser.flag_cat_hasapp))))) {- continue pollloop;- }-- // count domZones- //this.domZones[DigestURI.domDomain(iEntry.metadataHash())]++;-- // check site constraints- final String hosthash = iEntry.hosthash();- if ( this.query.sitehash == null ) {- if (this.query.siteexcludes != null && this.query.siteexcludes.contains(hosthash)) continue pollloop;- } else {- // filter out all domains that do not match with the site constraint- if (!hosthash.equals(this.query.sitehash)) continue pollloop;- }-- // collect host navigation information (even if we have only one; this is to provide a switch-off button)- if (this.query.navigators.isEmpty() && (nav_hosts || this.query.urlMask_isCatchall)) {- this.hostNavigator.inc(hosthash);- this.hostResolver.put(hosthash, iEntry.urlhash());- }-- // check protocol- if (!this.query.urlMask_isCatchall) {- final boolean httpFlagSet = DigestURI.flag4HTTPset(iEntry.urlHash);- if (httpPattern && !httpFlagSet) continue pollloop;- if (noHttpButProtocolPattern && httpFlagSet) continue pollloop;- }-- // check vocabulary constraint- String subject = YaCyMetadata.hashURI(iEntry.urlhash());- Resource resource = JenaTripleStore.getResource(subject);- if (this.query.metatags != null && !this.query.metatags.isEmpty()) {- // all metatags must appear in the tags list- for (Tagging.Metatag metatag: this.query.metatags) {- Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, metatag.getPredicate());- if (!ni.hasNext()) continue pollloop;- String tags = ni.next().toString();- if (tags.indexOf(metatag.getObject()) < 0) continue pollloop;- }- }-- // add navigators using the triplestore- for (Map.Entry<String, String> v: this.taggingPredicates.entrySet()) {- Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, v.getValue());- while (ni.hasNext()) {- String[] tags = ni.next().toString().split(",");- for (String tag: tags) {- ScoreMap<String> voc = this.vocabularyNavigator.get(v.getKey());- if (voc == null) {- voc = new ConcurrentScoreMap<String>();- this.vocabularyNavigator.put(v.getKey(), voc);- }- voc.inc(tag);- }- }- }-- // finally extend the double-check and insert result to stack- this.urlhashes.putUnique(iEntry.urlhash());- rankingtryloop: while (true) {- try {- this.rwiStack.put(new ReverseElement<WordReferenceVars>(iEntry, this.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)- break rankingtryloop;- } catch ( final ArithmeticException e ) {- // this may happen if the concurrent normalizer changes values during cardinal computation- continue rankingtryloop;- }- }- // increase counter for statistics- if (local) this.local_indexCount++; else this.remote_indexCount++;- }- if (System.currentTimeMillis() >= timeout) Log.logWarning("RWIProcess", "rwi normalization ended with timeout = " + maxtime);-- } catch ( final InterruptedException e ) {- } catch ( final SpaceExceededException e ) {- }-- //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true);- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEvent.Type.PRESORT,- resourceName,- index.size(),- System.currentTimeMillis() - timer), false);- }-- /**- * method to signal the incoming stack that one feeder has terminated- */- public void oneFeederTerminated() {- this.feedersTerminated.incrementAndGet();- final int c = this.feedersAlive.decrementAndGet();- assert c >= 0 : "feeders = " + c;- }-- public void oneFeederStarted() {- this.feedersAlive.addAndGet(1);- }-- protected boolean feedingIsFinished() {- return- this.feedersTerminated.intValue() > (this.remote ? 1 : 0) &&- this.feedersAlive.get() == 0;// &&- //(!this.remote || this.remote_indexCount > 0);- }-- private boolean testFlags(final Bitfield flags) {- if (this.query.constraint == null) return true;- // test if ientry matches with filter- // if all = true: let only entries pass that has all matching bits- // if all = false: let all entries pass that has at least one matching bit- if (this.query.allofconstraint) {- for ( int i = 0; i < 32; i++ ) {- if ((this.query.constraint.get(i)) && (!flags.get(i))) return false;- }- return true;- }- for (int i = 0; i < 32; i++) {- if ((this.query.constraint.get(i)) && (flags.get(i))) return true;- }- return false;- }-- protected Map<byte[], ReferenceContainer<WordReference>> searchContainerMap() {- // direct access to the result maps is needed for abstract generation- // this is only available if execQuery() was called before- return this.localSearchInclusion;- }-- private URIMetadataNode takeRWI(final boolean skipDoubleDom, final long waitingtime) {-- // returns from the current RWI list the best entry and removes this entry from the list- WeakPriorityBlockingQueue<WordReferenceVars> m;- WeakPriorityBlockingQueue.Element<WordReferenceVars> rwi = null;- WeakPriorityBlockingQueue.Element<URIMetadataNode> page;-- // take one entry from the stack if there are entries on that stack or the feeding is not yet finished- try {- int loops = 0; // a loop counter to terminate the reading if all the results are from the same domain- // wait some time if we did not get so much remote results so far to get a better ranking over remote results- // we wait at most 30 milliseconds to get a maximum total waiting time of 300 milliseconds for 10 results- long wait = waitTimeRecommendation();- if ( wait > 0 ) {- //System.out.println("*** RWIProcess extra wait: " + wait + "ms; expectedRemoteReferences = " + this.expectedRemoteReferences.get() + ", receivedRemoteReferences = " + this.receivedRemoteReferences.get() + ", initialExpectedRemoteReferences = " + this.maxExpectedRemoteReferences.get());- Thread.sleep(wait);- }- // loop as long as we can expect that we should get more results- final long timeout = System.currentTimeMillis() + waitingtime;- while (((!feedingIsFinished() && this.addRunning) || this.nodeStack.sizeQueue() > 0 || this.rwiStack.sizeQueue() > 0) &&- (this.query.itemsPerPage < 1 || loops++ < this.query.itemsPerPage || (loops > 1000 && !this.doubleDomCache.isEmpty()))) {- page = null;- rwi = null;- if ( waitingtime <= 0 ) {- page = this.addRunning ? this.nodeStack.poll(waitingtime) : this.nodeStack.poll();- if (page == null) rwi = this.addRunning ? this.rwiStack.poll(waitingtime) : this.rwiStack.poll();- } else {- timeoutloop: while ( System.currentTimeMillis() < timeout ) {- //System.out.println("### RWIProcess feedingIsFinished() = " + feedingIsFinished() + ", this.nodeStack.sizeQueue() = " + this.nodeStack.sizeQueue());- if (feedingIsFinished() && this.rwiStack.sizeQueue() == 0 && this.nodeStack.sizeQueue() == 0) break timeoutloop;- page = this.nodeStack.poll(50);- if (page != null) break timeoutloop;- rwi = this.rwiStack.poll(50);- if (rwi != null) break timeoutloop;- }- }- if (page != null) return page.getElement();- if (rwi == null) break;- if (!skipDoubleDom) {- return this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());- }-- // check doubledom- final String hosthash = rwi.getElement().hosthash();- m = this.doubleDomCache.get(hosthash);- if (m == null) {- synchronized ( this.doubleDomCache ) {- m = this.doubleDomCache.get(hosthash);- if ( m == null ) {- // first appearance of dom. we create an entry to signal that one of that domain was already returned- m = new WeakPriorityBlockingQueue<WordReferenceVars>(this.query.snippetCacheStrategy == null || this.query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? max_results_preparation_special : max_results_preparation, false);- this.doubleDomCache.put(hosthash, m);- return this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());- }- // second appearances of dom- m.put(rwi);- }- } else {- m.put(rwi);- }- }- } catch ( final InterruptedException e1 ) {- }- //Log.logWarning("RWIProcess", "feedingIsFinished() = " + feedingIsFinished());- //Log.logWarning("RWIProcess", "this.addRunning = " + this.addRunning);- //Log.logWarning("RWIProcess", "this.nodeStack.sizeQueue() = " + this.nodeStack.sizeQueue());- //Log.logWarning("RWIProcess", "this.stack.sizeQueue() = " + this.rwiStack.sizeQueue());- //Log.logWarning("RWIProcess", "this.doubleDomCachee.size() = " + this.doubleDomCache.size());- if (this.doubleDomCache.isEmpty()) {- Log.logWarning("RWIProcess", "doubleDomCache.isEmpty");- return null;- }-- // no more entries in sorted RWI entries. Now take Elements from the doubleDomCache- // find best entry from all caches- WeakPriorityBlockingQueue.Element<WordReferenceVars> bestEntry = null;- WeakPriorityBlockingQueue.Element<WordReferenceVars> o;- final Iterator<WeakPriorityBlockingQueue<WordReferenceVars>> i = this.doubleDomCache.values().iterator();- while ( i.hasNext() ) {- try {- m = i.next();- } catch ( final ConcurrentModificationException e ) {- Log.logException(e);- continue; // not the best solution...- }- if (m == null) continue;- if (m.isEmpty()) continue;- if (bestEntry == null) {- bestEntry = m.peek();- continue;- }- o = m.peek();- if (o == null) continue;- if (o.getWeight() < bestEntry.getWeight()) bestEntry = o;- }- if (bestEntry == null) {- Log.logWarning("RWIProcess", "bestEntry == null (1)");- return null;- }-- // finally remove the best entry from the doubledom cache- m = this.doubleDomCache.get(bestEntry.getElement().hosthash());- if (m != null) {- bestEntry = m.poll();- if (bestEntry != null && m.sizeAvailable() == 0) {- synchronized ( this.doubleDomCache ) {- if (m.sizeAvailable() == 0) {- this.doubleDomCache.remove(bestEntry.getElement().hosthash());- }- }- }- }- if (bestEntry == null) {- Log.logWarning("RWIProcess", "bestEntry == null (2)");- return null;- }- return this.query.getSegment().fulltext().getMetadata(bestEntry.getElement(), bestEntry.getWeight());- }-- /**- * get one metadata entry from the ranked results. This will be the 'best' entry so far according to the- * applied ranking. If there are no more entries left or the timeout limit is reached then null is- * returned. The caller may distinguish the timeout case from the case where there will be no more also in- * the future by calling this.feedingIsFinished()- *- * @param skipDoubleDom should be true if it is wanted that double domain entries are skipped- * @param waitingtime the time this method may take for a result computation- * @return a metadata entry for a url- */- public URIMetadataNode takeURL(final boolean skipDoubleDom, final long waitingtime) {- // returns from the current RWI list the best URL entry and removes this entry from the list- final long timeout = System.currentTimeMillis() + Math.max(10, waitingtime);- int p = -1;- long timeleft;- while ( (timeleft = timeout - System.currentTimeMillis()) > 0 ) {- //System.out.println("timeleft = " + timeleft);- final URIMetadataNode page = takeRWI(skipDoubleDom, timeleft);- if (page == null) {- Log.logWarning("RWIProcess", "takeRWI returned null");- return null; // all time was already wasted in takeRWI to get another element- }-- if ( !this.query.urlMask_isCatchall ) {- // check url mask- if ( !page.matches(this.query.urlMask) ) {- this.sortout++;- continue;- }- }-- // check for more errors- if ( page.url() == null ) {- this.sortout++;- continue; // rare case where the url is corrupted- }-- // check content domain- if ((this.query.contentdom.getCode() > 0 && page.url().getContentDomain() != this.query.contentdom) ||- (this.query.contentdom == Classification.ContentDomain.TEXT && page.url().getContentDomain().getCode() > 0)) {- this.sortout++;- continue;- }-- // Check for blacklist- if (Switchboard.urlBlacklist.isListed(BlacklistType.SEARCH, page)) {- this.sortout++;- continue;- }-- // content control-- if (Switchboard.getSwitchboard().getConfigBool("contentcontrol.enabled", false) == true) {-- // check global network filter from bookmark list- if (!Switchboard.getSwitchboard()- .getConfig("contentcontrol.mandatoryfilterlist", "")- .equals("")) {-- FilterEngine f = ContentControlFilterUpdateThread.getNetworkFilter();- if (f != null) {- if (!f.isListed(page.url(), null)) {- this.sortout++;- continue;- }- }- }- }-- final String pageurl = page.url().toNormalform(true);- final String pageauthor = page.dc_creator();- final String pagetitle = page.dc_title().toLowerCase();-- // check exclusion- if ( this.query.query_exclude_hashes != null && !this.query.query_exclude_hashes.isEmpty() &&- ((QueryParams.anymatch(pagetitle, this.query.query_exclude_hashes))- || (QueryParams.anymatch(pageurl.toLowerCase(), this.query.query_exclude_hashes))- || (QueryParams.anymatch(pageauthor.toLowerCase(), this.query.query_exclude_hashes)))) {- this.sortout++;- continue;- }-- // check index-of constraint- if ( (this.query.constraint != null)- && (this.query.constraint.get(Condenser.flag_cat_indexof))- && (!(pagetitle.startsWith("index of"))) ) {- final Iterator<byte[]> wi = this.query.query_include_hashes.iterator();- while ( wi.hasNext() ) {- this.query.getSegment().termIndex().removeDelayed(wi.next(), page.hash());- }- this.sortout++;- continue;- }-- // check location constraint- if ( (this.query.constraint != null)- && (this.query.constraint.get(Condenser.flag_cat_haslocation))- && (page.lat() == 0.0f || page.lon() == 0.0f) ) {- this.sortout++;- continue;- }-- // check geo coordinates- double lat, lon;- if (this.query.radius > 0.0d && this.query.lat != 0.0d && this.query.lon != 0.0d && (lat = page.lat()) != 0.0d && (lon = page.lon()) != 0.0d) {- double latDelta = this.query.lat - lat;- double lonDelta = this.query.lon - lon;- double distance = Math.sqrt(latDelta * latDelta + lonDelta * lonDelta); // pythagoras- if (distance > this.query.radius) {- this.sortout++;- continue;- }- }-- // evaluate information of metadata for navigation- // author navigation:- if ( pageauthor != null && pageauthor.length() > 0 ) {- // add author to the author navigator- final String authorhash = ASCII.String(Word.word2hash(pageauthor));-- // check if we already are filtering for authors- if ( this.query.authorhash != null && !this.query.authorhash.equals(authorhash) ) {- this.sortout++;- continue;- }-- // add author to the author navigator- this.authorNavigator.inc(pageauthor);- } else if ( this.query.authorhash != null ) {- this.sortout++;- continue;- }-- // check Scanner- if ( !Scanner.acceptURL(page.url()) ) {- this.sortout++;- continue;- }-- // from here: collect navigation information-- // collect host navigation information (even if we have only one; this is to provide a switch-off button)- if (!this.query.navigators.isEmpty() && (this.query.urlMask_isCatchall || this.query.navigators.equals("all") || this.query.navigators.indexOf("hosts", 0) >= 0)) {- final String hosthash = page.hosthash();- this.hostNavigator.inc(hosthash);- this.hostResolver.put(hosthash, page.hash());- }-- // namespace navigation- String pagepath = page.url().getPath();- if ( (p = pagepath.indexOf(':')) >= 0 ) {- pagepath = pagepath.substring(0, p);- p = pagepath.lastIndexOf('/');- if ( p >= 0 ) {- pagepath = pagepath.substring(p + 1);- this.namespaceNavigator.inc(pagepath);- }- }-- // protocol navigation- final String protocol = page.url().getProtocol();- this.protocolNavigator.inc(protocol);-- // file type navigation- final String fileext = page.url().getFileExtension();- if ( fileext.length() > 0 ) {- this.filetypeNavigator.inc(fileext);- }-- // accept url- return page;- }- Log.logWarning("RWIProcess", "loop terminated");- return null;- }-- public int[] flagCount() {- return this.flagcount;- }-- public boolean rwiIsEmpty() {- if ( !this.rwiStack.isEmpty() ) {- return false;- }- for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {- if ( !s.isEmpty() ) {- return false;- }- }- return true;- }-- protected int rwiQueueSize() {- int c = this.rwiStack.sizeQueue();- for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {- c += s.sizeQueue();- }- return c;- }-- public int rwiAvailableCount() {- // the number of results in the local peer after filtering- return this.rwiStack.sizeAvailable();- }-- public int getRemoteIndexCount() {- // the number of result contributions from all the remote peers- return this.remote_indexCount;- }-- public int getRemoteResourceSize() {- // the number of all hits in all the remote peers- return Math.max(this.remote_resourceSize, this.remote_indexCount);- }-- public int getRemotePeerCount() {- // the number of remote peers that have contributed- return this.remote_peerCount;- }-- public Iterator<byte[]> miss() {- return this.misses.iterator();- }-- public int getMissCount() {- return this.misses.size();- }-- public int getSortOutCount() {- return this.sortout;- }-- public ScoreMap<String> getNamespaceNavigator() {- if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("namespace", 0) < 0 ) {- return new ClusteredScoreMap<String>();- }- return this.namespaceNavigator;- }-- public ScoreMap<String> getHostNavigator() {- final ScoreMap<String> result = new ConcurrentScoreMap<String>();- if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("hosts", 0) < 0 ) {- return result;- }-- final Iterator<String> domhashs = this.hostNavigator.keys(false);- URIMetadataNode row;- byte[] urlhash;- String hosthash, hostname;- if ( this.hostResolver != null ) {- while ( domhashs.hasNext() && result.sizeSmaller(30) ) {- hosthash = domhashs.next();- if ( hosthash == null ) {- continue;- }- urlhash = this.hostResolver.get(hosthash);- row = urlhash == null ? null : this.query.getSegment().fulltext().getMetadata(urlhash);- hostname = row == null ? null : row.url().getHost();- if ( hostname != null ) {- result.set(hostname, this.hostNavigator.get(hosthash));- }- }- }- return result;- }-- public ScoreMap<String> getProtocolNavigator() {- if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("protocol", 0) < 0 ) {- return new ClusteredScoreMap<String>();- }- return this.protocolNavigator;- }-- public ScoreMap<String> getFiletypeNavigator() {- if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("filetype", 0) < 0 ) {- return new ClusteredScoreMap<String>();- }- return this.filetypeNavigator;- }-- public Map<String,ScoreMap<String>> getVocabularyNavigators() {- return this.vocabularyNavigator;- }-- public static final Comparator<Map.Entry<String, Integer>> mecomp =- new Comparator<Map.Entry<String, Integer>>() {- @Override- public int compare(final Map.Entry<String, Integer> o1, final Map.Entry<String, Integer> o2) {- if ( o1.getValue().intValue() < o2.getValue().intValue() ) {- return 1;- }- if ( o2.getValue().intValue() < o1.getValue().intValue() ) {- return -1;- }- return 0;- }- };-- public ScoreMap<String> getTopicNavigator(final int count) {- // create a list of words that had been computed by statistics over all- // words that appeared in the url or the description of all urls- final ScoreMap<String> result = new ConcurrentScoreMap<String>();- if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("topics", 0) < 0 ) {- return result;- }- if ( this.ref.sizeSmaller(2) ) {- this.ref.clear(); // navigators with one entry are not useful- }- final Map<String, Float> counts = new HashMap<String, Float>();- final Iterator<String> i = this.ref.keys(false);- String word;- int c;- float q, min = Float.MAX_VALUE, max = Float.MIN_VALUE;- int ic = count;- while ( ic-- > 0 && i.hasNext() ) {- word = i.next();- if ( word == null ) {- continue;- }- c = this.query.getSegment().getQueryCount(word);- if ( c > 0 ) {- q = ((float) this.ref.get(word)) / ((float) c);- min = Math.min(min, q);- max = Math.max(max, q);- counts.put(word, q);- }- }- if ( max > min ) {- for ( final Map.Entry<String, Float> ce : counts.entrySet() ) {- result.set(ce.getKey(), (int) (((double) count) * (ce.getValue() - min) / (max - min)));- }- }- return this.ref;- }-- private final static Pattern lettermatch = Pattern.compile("[a-z]+");-- public void addTopic(final String[] words) {- String word;- for ( final String w : words ) {- word = w.toLowerCase();- if ( word.length() > 2- && "http_html_php_ftp_www_com_org_net_gov_edu_index_home_page_for_usage_the_and_zum_der_die_das_und_the_zur_bzw_mit_blog_wiki_aus_bei_off"- .indexOf(word) < 0- && !this.query.query_include_hashes.has(Word.word2hash(word))- && lettermatch.matcher(word).matches()- && !Switchboard.badwords.contains(word)- && !Switchboard.stopwords.contains(word) ) {- this.ref.inc(word);- }- }- }-- public void addTopics(final ResultEntry resultEntry) {- // take out relevant information for reference computation- if ( (resultEntry.url() == null) || (resultEntry.title() == null) ) {- return;- }- //final String[] urlcomps = htmlFilterContentScraper.urlComps(resultEntry.url().toNormalform(true, true)); // word components of the url- final String[] descrcomps = MultiProtocolURI.splitpattern.split(resultEntry.title().toLowerCase()); // words in the description-- // add references- //addTopic(urlcomps);- addTopic(descrcomps);- }-- public ScoreMap<String> getAuthorNavigator() {- // create a list of words that had been computed by statistics over all- // words that appeared in the url or the description of all urls- if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("authors", 0) < 0 ) {- return new ConcurrentScoreMap<String>();- }- return this.authorNavigator;- }--}diff --git a/source/net/yacy/search/query/RankingProcess.java b/source/net/yacy/search/query/RankingProcess.javanew file mode 100644index 000000000..c46f74c63--- /dev/null+++ b/source/net/yacy/search/query/RankingProcess.java@@ -0,0 +1,560 @@+// RankingProcess.java+// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 07.11.2007 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $LastChangedBy$+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package net.yacy.search.query;++import java.util.HashMap;+import java.util.Iterator;+import java.util.Map;+import java.util.SortedMap;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.regex.Pattern;++import net.yacy.cora.document.Classification.ContentDomain;+import net.yacy.cora.document.MultiProtocolURI;+import net.yacy.cora.document.UTF8;+import net.yacy.cora.federate.yacy.CacheStrategy;+import net.yacy.cora.lod.JenaTripleStore;+import net.yacy.cora.lod.vocabulary.Tagging;+import net.yacy.cora.lod.vocabulary.YaCyMetadata;+import net.yacy.cora.sorting.ConcurrentScoreMap;+import net.yacy.cora.sorting.ScoreMap;+import net.yacy.cora.sorting.WeakPriorityBlockingQueue;+import net.yacy.cora.sorting.WeakPriorityBlockingQueue.ReverseElement;+import net.yacy.cora.storage.HandleSet;+import net.yacy.cora.util.SpaceExceededException;+import net.yacy.document.Condenser;+import net.yacy.document.LibraryProvider;+import net.yacy.kelondro.data.meta.DigestURI;+import net.yacy.kelondro.data.meta.URIMetadataNode;+import net.yacy.kelondro.data.meta.URIMetadataRow;+import net.yacy.kelondro.data.word.Word;+import net.yacy.kelondro.data.word.WordReference;+import net.yacy.kelondro.data.word.WordReferenceVars;+import net.yacy.kelondro.index.RowHandleSet;+import net.yacy.kelondro.logging.Log;+import net.yacy.kelondro.rwi.ReferenceContainer;+import net.yacy.kelondro.rwi.TermSearch;+import net.yacy.kelondro.util.Bitfield;+import net.yacy.peers.graphics.ProfilingGraph;+import net.yacy.search.EventTracker;+import net.yacy.search.Switchboard;+import net.yacy.search.index.Segment;+import net.yacy.search.ranking.ReferenceOrder;+import net.yacy.search.snippet.ResultEntry;++import com.hp.hpl.jena.rdf.model.RDFNode;+import com.hp.hpl.jena.rdf.model.Resource;++public final class RankingProcess extends Thread {++ protected static final int max_results_preparation = 3000, max_results_preparation_special = -1; // -1 means 'no limit'++ //private final SearchEvent searchEvent;+ private final QueryParams query;+ private SortedMap<byte[], ReferenceContainer<WordReference>> localSearchInclusion;+ private final ScoreMap<String> ref; // reference score computation for the commonSense heuristic+ private final long maxtime;+ protected final WeakPriorityBlockingQueue<WordReferenceVars> rwiStack;+ protected final ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>> doubleDomCache; // key = domhash (6 bytes); value = like stack+ private final int[] flagcount; // flag counter+ private final HandleSet misses; // contains url-hashes that could not been found in the LURL-DB+ private final AtomicInteger feedersAlive, feedersTerminated;+ private boolean addRunning;+ protected final AtomicInteger receivedRemoteReferences;+ protected final ReferenceOrder order;+ int local_indexCount;+ int remote_indexCount;+ int remote_resourceSize;+ int remote_peerCount;+ final HandleSet urlhashes; // map for double-check; String/Long relation, addresses ranking number (backreference for deletion)+ final ScoreMap<String> hostNavigator; // a counter for the appearance of the host hash+ final Map<String, byte[]> hostResolver; // a mapping from a host hash (6 bytes) to the full url hash of one of these urls that have the host hash+ final Map<String, String> taggingPredicates; // a map from tagging vocabulary names to tagging predicate uris+ final Map<String, ScoreMap<String>> vocabularyNavigator; // counters for Vocabularies; key is metatag.getVocabularyName()+ private boolean remote;++ public RankingProcess(final QueryParams query, boolean remote) {+ // we collect the urlhashes and construct a list with urlEntry objects+ // attention: if minEntries is too high, this method will not terminate within the maxTime+ // sortorder: 0 = hash, 1 = url, 2 = ranking+ this.query = query;+ this.remote = remote;+ this.localSearchInclusion = null;+ this.ref = new ConcurrentScoreMap<String>();+ this.maxtime = query.maxtime;+ int stackMaxsize = query.snippetCacheStrategy == null || query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? max_results_preparation_special : max_results_preparation;+ this.rwiStack = new WeakPriorityBlockingQueue<WordReferenceVars>(stackMaxsize, false);+ this.doubleDomCache = new ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>>();+ this.misses = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100);+ this.flagcount = new int[32];+ for ( int i = 0; i < 32; i++ ) {+ this.flagcount[i] = 0;+ }+ this.feedersAlive = new AtomicInteger(0);+ this.feedersTerminated = new AtomicInteger(0);+ this.addRunning = true;+ this.receivedRemoteReferences = new AtomicInteger(0);+ this.order = new ReferenceOrder(this.query.ranking, UTF8.getBytes(this.query.targetlang));+ this.remote_resourceSize = 0;+ this.remote_indexCount = 0;+ this.remote_peerCount = 0;+ this.local_indexCount = 0;+ this.urlhashes = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100);+ this.hostNavigator = new ConcurrentScoreMap<String>();+ this.hostResolver = new ConcurrentHashMap<String, byte[]>();+ this.vocabularyNavigator = new ConcurrentHashMap<String, ScoreMap<String>>();+ this.taggingPredicates = new HashMap<String, String>();+ for (Tagging t: LibraryProvider.autotagging.getVocabularies()) {+ this.taggingPredicates.put(t.getName(), t.getPredicate());+ }+ }++ public ReferenceOrder getOrder() {+ return this.order;+ }++ protected boolean feedingIsFinished() {+ return+ this.feedersTerminated.intValue() > (this.remote ? 1 : 0) &&+ this.feedersAlive.get() == 0;// &&+ //(!this.remote || this.remote_indexCount > 0);+ }++ /**+ * method to signal the incoming stack that one feeder has terminated+ */+ public void oneFeederTerminated() {+ this.feedersTerminated.incrementAndGet();+ final int c = this.feedersAlive.decrementAndGet();+ assert c >= 0 : "feeders = " + c;+ }++ public void oneFeederStarted() {+ this.feedersAlive.addAndGet(1);+ }++ public int rwiAvailableCount() {+ // the number of results in the local peer after filtering+ return this.rwiStack.sizeAvailable();+ }++ public QueryParams getQuery() {+ return this.query;+ }++ public int[] flagCount() {+ return this.flagcount;+ }++ public Iterator<byte[]> miss() {+ return this.misses.iterator();+ }++ public int getMissCount() {+ return this.misses.size();+ }++ protected void addBegin() {+ this.addRunning = true;+ }++ public void addFinalize() {+ this.addRunning = false;+ }++ protected boolean addRunning() {+ return this.addRunning;+ }++ public boolean rwiIsEmpty() {+ if ( !this.rwiStack.isEmpty() ) {+ return false;+ }+ for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {+ if ( !s.isEmpty() ) {+ return false;+ }+ }+ return true;+ }++ protected int rwiQueueSize() {+ int c = this.rwiStack.sizeQueue();+ for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {+ c += s.sizeQueue();+ }+ return c;+ }++ protected boolean testFlags(final Bitfield flags) {+ if (this.query.constraint == null) return true;+ // test if ientry matches with filter+ // if all = true: let only entries pass that has all matching bits+ // if all = false: let all entries pass that has at least one matching bit+ if (this.query.allofconstraint) {+ for ( int i = 0; i < 32; i++ ) {+ if ((this.query.constraint.get(i)) && (!flags.get(i))) return false;+ }+ return true;+ }+ for (int i = 0; i < 32; i++) {+ if ((this.query.constraint.get(i)) && (flags.get(i))) return true;+ }+ return false;+ }++ public int getRemoteIndexCount() {+ // the number of result contributions from all the remote peers+ return this.remote_indexCount;+ }++ public int getRemoteResourceSize() {+ // the number of all hits in all the remote peers+ return Math.max(this.remote_resourceSize, this.remote_indexCount);+ }++ public int getRemotePeerCount() {+ // the number of remote peers that have contributed+ return this.remote_peerCount;+ }++ @Override+ public void run() {++ // do a search+ oneFeederStarted();++ // sort the local containers and truncate it to a limited count,+ // so following sortings together with the global results will be fast+ try {+ final long timer = System.currentTimeMillis();+ final TermSearch<WordReference> search =+ this.query+ .getSegment()+ .termIndex()+ .query(+ this.query.query_include_hashes,+ this.query.query_exclude_hashes,+ null,+ Segment.wordReferenceFactory,+ this.query.maxDistance);+ this.localSearchInclusion = search.inclusion();+ final ReferenceContainer<WordReference> index = search.joined();+ EventTracker.update(+ EventTracker.EClass.SEARCH,+ new ProfilingGraph.EventSearch(+ this.query.id(true),+ SearchEventType.JOIN,+ this.query.queryString,+ index.size(),+ System.currentTimeMillis() - timer),+ false);+ if ( !index.isEmpty() ) {+ add(index, true, "local index: " + this.query.getSegment().getLocation(), -1, this.maxtime);+ this.addFinalize();+ }+ } catch ( final Exception e ) {+ Log.logException(e);+ } finally {+ oneFeederTerminated();+ }+ }++ public void add(+ final ReferenceContainer<WordReference> index,+ final boolean local,+ final String resourceName,+ final int fullResource,+ final long maxtime) {+ // we collect the urlhashes and construct a list with urlEntry objects+ // attention: if minEntries is too high, this method will not terminate within the maxTime+ //Log.logInfo("RWIProcess", "added a container, size = " + index.size());++ this.addRunning = true;+ assert (index != null);+ if (index.isEmpty()) return;+ if (!local) {+ assert fullResource >= 0 : "fullResource = " + fullResource;+ this.remote_resourceSize += fullResource;+ this.remote_peerCount++;+ }+ long timer = System.currentTimeMillis();++ // normalize entries+ final BlockingQueue<WordReferenceVars> decodedEntries = this.order.normalizeWith(index, maxtime);+ int is = index.size();+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(+ this.query.id(true),+ SearchEventType.NORMALIZING,+ resourceName,+ is,+ System.currentTimeMillis() - timer), false);+ if (!local) this.receivedRemoteReferences.addAndGet(is);++ // iterate over normalized entries and select some that are better than currently stored+ timer = System.currentTimeMillis();+ final boolean nav_hosts = this.query.navigators.equals("all") || this.query.navigators.indexOf("hosts", 0) >= 0;++ // apply all constraints+ long timeout = System.currentTimeMillis() + maxtime;+ try {+ WordReferenceVars iEntry;+ final String pattern = this.query.urlMask.pattern();+ final boolean httpPattern = pattern.equals("http://.*");+ final boolean noHttpButProtocolPattern = pattern.equals("https://.*") || pattern.equals("ftp://.*") || pattern.equals("smb://.*") || pattern.equals("file://.*");+ long remaining;+ pollloop: while ( true ) {+ remaining = timeout - System.currentTimeMillis();+ if (remaining <= 0) {+ Log.logWarning("RWIProcess", "terminated 'add' loop before poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());+ break;+ }+ iEntry = decodedEntries.poll(remaining, TimeUnit.MILLISECONDS);+ if (iEntry == null) {+ Log.logWarning("RWIProcess", "terminated 'add' loop after poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());+ break pollloop;+ }+ if (iEntry == WordReferenceVars.poison) {+ break pollloop;+ }+ assert (iEntry.urlhash().length == index.row().primaryKeyLength);++ // doublecheck for urls+ if (this.urlhashes.has(iEntry.urlhash())) continue pollloop;++ // increase flag counts+ Bitfield flags = iEntry.flags();+ for (int j = 0; j < 32; j++) {+ if (flags.get(j)) this.flagcount[j]++;+ }++ // check constraints+ if (!this.testFlags(flags)) continue pollloop;++ // check document domain+ if (this.query.contentdom.getCode() > 0 &&+ ((this.query.contentdom == ContentDomain.AUDIO && !(flags.get(Condenser.flag_cat_hasaudio))) ||+ (this.query.contentdom == ContentDomain.VIDEO && !(flags.get(Condenser.flag_cat_hasvideo))) ||+ (this.query.contentdom == ContentDomain.IMAGE && !(flags.get(Condenser.flag_cat_hasimage))) ||+ (this.query.contentdom == ContentDomain.APP && !(flags.get(Condenser.flag_cat_hasapp))))) {+ continue pollloop;+ }++ // count domZones+ //this.domZones[DigestURI.domDomain(iEntry.metadataHash())]++;++ // check site constraints+ final String hosthash = iEntry.hosthash();+ if ( this.query.sitehash == null ) {+ if (this.query.siteexcludes != null && this.query.siteexcludes.contains(hosthash)) continue pollloop;+ } else {+ // filter out all domains that do not match with the site constraint+ if (!hosthash.equals(this.query.sitehash)) continue pollloop;+ }++ // collect host navigation information (even if we have only one; this is to provide a switch-off button)+ if (this.query.navigators.isEmpty() && (nav_hosts || this.query.urlMask_isCatchall)) {+ this.hostNavigator.inc(hosthash);+ this.hostResolver.put(hosthash, iEntry.urlhash());+ }++ // check protocol+ if (!this.query.urlMask_isCatchall) {+ final boolean httpFlagSet = DigestURI.flag4HTTPset(iEntry.urlHash);+ if (httpPattern && !httpFlagSet) continue pollloop;+ if (noHttpButProtocolPattern && httpFlagSet) continue pollloop;+ }++ // check vocabulary constraint+ String subject = YaCyMetadata.hashURI(iEntry.urlhash());+ Resource resource = JenaTripleStore.getResource(subject);+ if (this.query.metatags != null && !this.query.metatags.isEmpty()) {+ // all metatags must appear in the tags list+ for (Tagging.Metatag metatag: this.query.metatags) {+ Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, metatag.getPredicate());+ if (!ni.hasNext()) continue pollloop;+ String tags = ni.next().toString();+ if (tags.indexOf(metatag.getObject()) < 0) continue pollloop;+ }+ }++ // add navigators using the triplestore+ for (Map.Entry<String, String> v: this.taggingPredicates.entrySet()) {+ Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, v.getValue());+ while (ni.hasNext()) {+ String[] tags = ni.next().toString().split(",");+ for (String tag: tags) {+ ScoreMap<String> voc = this.vocabularyNavigator.get(v.getKey());+ if (voc == null) {+ voc = new ConcurrentScoreMap<String>();+ this.vocabularyNavigator.put(v.getKey(), voc);+ }+ voc.inc(tag);+ }+ }+ }++ // finally extend the double-check and insert result to stack+ this.urlhashes.putUnique(iEntry.urlhash());+ rankingtryloop: while (true) {+ try {+ this.rwiStack.put(new ReverseElement<WordReferenceVars>(iEntry, this.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)+ break rankingtryloop;+ } catch ( final ArithmeticException e ) {+ // this may happen if the concurrent normalizer changes values during cardinal computation+ continue rankingtryloop;+ }+ }+ // increase counter for statistics+ if (local) this.local_indexCount++; else this.remote_indexCount++;+ }+ if (System.currentTimeMillis() >= timeout) Log.logWarning("RWIProcess", "rwi normalization ended with timeout = " + maxtime);++ } catch ( final InterruptedException e ) {+ } catch ( final SpaceExceededException e ) {+ }++ //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(+ this.query.id(true),+ SearchEventType.PRESORT,+ resourceName,+ index.size(),+ System.currentTimeMillis() - timer), false);+ }++ protected Map<byte[], ReferenceContainer<WordReference>> searchContainerMap() {+ // direct access to the result maps is needed for abstract generation+ // this is only available if execQuery() was called before+ return this.localSearchInclusion;+ }+++ public ScoreMap<String> getHostNavigator() {+ final ScoreMap<String> result = new ConcurrentScoreMap<String>();+ if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("hosts", 0) < 0 ) {+ return result;+ }++ final Iterator<String> domhashs = this.hostNavigator.keys(false);+ URIMetadataNode row;+ byte[] urlhash;+ String hosthash, hostname;+ if ( this.hostResolver != null ) {+ while ( domhashs.hasNext() && result.sizeSmaller(30) ) {+ hosthash = domhashs.next();+ if ( hosthash == null ) {+ continue;+ }+ urlhash = this.hostResolver.get(hosthash);+ row = urlhash == null ? null : this.query.getSegment().fulltext().getMetadata(urlhash);+ hostname = row == null ? null : row.url().getHost();+ if ( hostname != null ) {+ result.set(hostname, this.hostNavigator.get(hosthash));+ }+ }+ }+ return result;+ }++ public Map<String,ScoreMap<String>> getVocabularyNavigators() {+ return this.vocabularyNavigator;+ }++ protected ScoreMap<String> getTopicNavigator(final int count) {+ // create a list of words that had been computed by statistics over all+ // words that appeared in the url or the description of all urls+ final ScoreMap<String> result = new ConcurrentScoreMap<String>();+ if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("topics", 0) < 0 ) {+ return result;+ }+ if ( this.ref.sizeSmaller(2) ) {+ this.ref.clear(); // navigators with one entry are not useful+ }+ final Map<String, Float> counts = new HashMap<String, Float>();+ final Iterator<String> i = this.ref.keys(false);+ String word;+ int c;+ float q, min = Float.MAX_VALUE, max = Float.MIN_VALUE;+ int ic = count;+ while ( ic-- > 0 && i.hasNext() ) {+ word = i.next();+ if ( word == null ) {+ continue;+ }+ c = this.query.getSegment().getQueryCount(word);+ if ( c > 0 ) {+ q = ((float) this.ref.get(word)) / ((float) c);+ min = Math.min(min, q);+ max = Math.max(max, q);+ counts.put(word, q);+ }+ }+ if ( max > min ) {+ for ( final Map.Entry<String, Float> ce : counts.entrySet() ) {+ result.set(ce.getKey(), (int) (((double) count) * (ce.getValue() - min) / (max - min)));+ }+ }+ return this.ref;+ }++ private final static Pattern lettermatch = Pattern.compile("[a-z]+");++ public void addTopic(final String[] words) {+ String word;+ for ( final String w : words ) {+ word = w.toLowerCase();+ if ( word.length() > 2+ && "http_html_php_ftp_www_com_org_net_gov_edu_index_home_page_for_usage_the_and_zum_der_die_das_und_the_zur_bzw_mit_blog_wiki_aus_bei_off"+ .indexOf(word) < 0+ && !this.query.query_include_hashes.has(Word.word2hash(word))+ && lettermatch.matcher(word).matches()+ && !Switchboard.badwords.contains(word)+ && !Switchboard.stopwords.contains(word) ) {+ this.ref.inc(word);+ }+ }+ }++ protected void addTopics(final ResultEntry resultEntry) {+ // take out relevant information for reference computation+ if ( (resultEntry.url() == null) || (resultEntry.title() == null) ) {+ return;+ }+ //final String[] urlcomps = htmlFilterContentScraper.urlComps(resultEntry.url().toNormalform(true, true)); // word components of the url+ final String[] descrcomps = MultiProtocolURI.splitpattern.split(resultEntry.title().toLowerCase()); // words in the description++ // add references+ //addTopic(urlcomps);+ addTopic(descrcomps);+ }+++}diff --git a/source/net/yacy/search/query/SearchEvent.java b/source/net/yacy/search/query/SearchEvent.javaindex 4ae4618f1..9ab27efb9 100644--- a/source/net/yacy/search/query/SearchEvent.java+++ b/source/net/yacy/search/query/SearchEvent.java@@ -27,84 +27,86 @@package net.yacy.search.query;import java.util.ArrayList;-import java.util.Collections;-import java.util.HashSet;+import java.util.ConcurrentModificationException;import java.util.Iterator;import java.util.List;import java.util.Map;-import java.util.Set;import java.util.SortedMap;-import java.util.SortedSet;import java.util.TreeMap;-import java.util.TreeSet;-import java.util.concurrent.Semaphore;-import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;++import com.hp.hpl.jena.rdf.model.RDFNode;+import com.hp.hpl.jena.rdf.model.Resource;import net.yacy.cora.document.ASCII;-import net.yacy.cora.document.UTF8;+import net.yacy.cora.document.Classification;+import net.yacy.cora.document.Classification.ContentDomain;+import net.yacy.cora.federate.yacy.CacheStrategy;import net.yacy.cora.federate.yacy.Distribution;+import net.yacy.cora.lod.JenaTripleStore;+import net.yacy.cora.lod.vocabulary.Tagging;+import net.yacy.cora.lod.vocabulary.YaCyMetadata;import net.yacy.cora.order.Base64Order;+import net.yacy.cora.protocol.Scanner;+import net.yacy.cora.sorting.ClusteredScoreMap;+import net.yacy.cora.sorting.ConcurrentScoreMap;import net.yacy.cora.sorting.ScoreMap;+import net.yacy.cora.sorting.WeakPriorityBlockingQueue;+import net.yacy.cora.sorting.WeakPriorityBlockingQueue.ReverseElement;+import net.yacy.cora.util.SpaceExceededException;import net.yacy.data.WorkTables;+import net.yacy.document.Condenser;import net.yacy.document.LargeNumberCache;+import net.yacy.interaction.contentcontrol.ContentControlFilterUpdateThread;+import net.yacy.kelondro.data.meta.DigestURI;+import net.yacy.kelondro.data.meta.URIMetadataNode;+import net.yacy.kelondro.data.word.Word;import net.yacy.kelondro.data.word.WordReference;import net.yacy.kelondro.data.word.WordReferenceFactory;+import net.yacy.kelondro.data.word.WordReferenceVars;import net.yacy.kelondro.logging.Log;import net.yacy.kelondro.rwi.ReferenceContainer;+import net.yacy.kelondro.util.Bitfield;import net.yacy.kelondro.util.MemoryControl;-import net.yacy.kelondro.util.SetTools;import net.yacy.peers.RemoteSearch;import net.yacy.peers.SeedDB;import net.yacy.peers.graphics.ProfilingGraph;+import net.yacy.repository.FilterEngine;import net.yacy.repository.LoaderDispatcher;+import net.yacy.repository.Blacklist.BlacklistType;import net.yacy.search.EventTracker;import net.yacy.search.Switchboard;-import net.yacy.search.query.SnippetProcess.Worker;-import net.yacy.search.ranking.ReferenceOrder;import net.yacy.search.snippet.ResultEntry;public final class SearchEvent {- public enum Type {- INITIALIZATION,- COLLECTION,- JOIN,- PRESORT,- URLFETCH,- NORMALIZING,- FINALIZATION,- REMOTESEARCH_START,- REMOTESEARCH_TERMINATE,- ABSTRACTS,- CLEANUP,- SNIPPETFETCH_START,- ONERESULT,- REFERENCECOLLECTION,- RESULTLIST;- }-- // class variables that may be implemented with an abstract class+ private static final long maxWaitPerResult = 30;+private long eventTime;- private QueryParams query;+ protected QueryParams query;public final SeedDB peers;private final WorkTables workTables;- public final RWIProcess rankingProcess; // ordered search results, grows dynamically as all the query threads enrich this container+ public final RankingProcess rankingProcess; // ordered search results, grows dynamically as all the query threads enrich this containerprivate final SnippetProcess resultFetcher;-public final SecondarySearchSuperviser secondarySearchSuperviser;-- // class variables for remote searchespublic final List<RemoteSearch> primarySearchThreadsL;- private Thread[] secondarySearchThreads;+ protected Thread[] secondarySearchThreads;public final SortedMap<byte[], String> preselectedPeerHashes;private final Thread localSearchThread;private final SortedMap<byte[], Integer> IACount;private final SortedMap<byte[], String> IAResults;private final SortedMap<byte[], HeuristicResult> heuristics;private byte[] IAmaxcounthash, IAneardhthash;- private final ReferenceOrder order;private final Thread localsearch;-+ private final AtomicInteger expectedRemoteReferences, maxExpectedRemoteReferences;+ private int sortout; // counter for referenced that had been sorted out for other reasons+ private final ScoreMap<String> authorNavigator; // a counter for the appearances of authors+ private final ScoreMap<String> namespaceNavigator; // a counter for name spaces+ private final ScoreMap<String> protocolNavigator; // a counter for protocol types+ private final ScoreMap<String> filetypeNavigator; // a counter for file types++ protected final WeakPriorityBlockingQueue<URIMetadataNode> nodeStack;+protected SearchEvent(final QueryParams query,final SeedDB peers,@@ -124,8 +126,18 @@ public final class SearchEvent {this.peers = peers;this.workTables = workTables;this.query = query;+ this.nodeStack = new WeakPriorityBlockingQueue<URIMetadataNode>(300, false);++ this.maxExpectedRemoteReferences = new AtomicInteger(0);+ this.expectedRemoteReferences = new AtomicInteger(0);+ this.sortout = 0;+ this.authorNavigator = new ConcurrentScoreMap<String>();+ this.namespaceNavigator = new ConcurrentScoreMap<String>();+ this.protocolNavigator = new ConcurrentScoreMap<String>();+ this.filetypeNavigator = new ConcurrentScoreMap<String>();+this.secondarySearchSuperviser =- (this.query.query_include_hashes.size() > 1) ? new SecondarySearchSuperviser() : null; // generate abstracts only for combined searches+ (this.query.query_include_hashes.size() > 1) ? new SecondarySearchSuperviser(this) : null; // generate abstracts only for combined searchesif ( this.secondarySearchSuperviser != null ) {this.secondarySearchSuperviser.start();}@@ -137,8 +149,7 @@ public final class SearchEvent {this.IAmaxcounthash = null;this.IAneardhthash = null;this.localSearchThread = null;- this.order = new ReferenceOrder(this.query.ranking, UTF8.getBytes(this.query.targetlang));- final boolean remote =+ boolean remote =(peers != null && peers.sizeConnected() > 0)&& (this.query.domType == QueryParams.Searchdom.CLUSTER || (this.query.domType == QueryParams.Searchdom.GLOBAL && peers.mySeed()@@ -148,7 +159,7 @@ public final class SearchEvent {// prepare a local RWI search// initialize a ranking process that is the target for data// that is generated concurrently from local and global search threads- this.rankingProcess = new RWIProcess(this.query, this.order, remote);+ this.rankingProcess = new RankingProcess(this.query, remote);// start a local solr searchthis.localsearch = RemoteSearch.solrRemoteSearch(this, 100, null /*this peer*/, Switchboard.urlBlacklist);@@ -191,7 +202,7 @@ public final class SearchEvent {EventTracker.EClass.SEARCH,new ProfilingGraph.EventSearch(this.query.id(true),- Type.REMOTESEARCH_START,+ SearchEventType.REMOTESEARCH_START,"",this.primarySearchThreadsL.size(),System.currentTimeMillis() - timer),@@ -248,7 +259,7 @@ public final class SearchEvent {EventTracker.EClass.SEARCH,new ProfilingGraph.EventSearch(this.query.id(true),- Type.ABSTRACTS,+ SearchEventType.ABSTRACTS,"",this.rankingProcess.searchContainerMap().size(),System.currentTimeMillis() - timer),@@ -268,8 +279,8 @@ public final class SearchEvent {// start worker threads to fetch urls and snippetsthis.resultFetcher =new SnippetProcess(+ this,loader,- this.rankingProcess,this.query,this.peers,this.workTables,@@ -280,7 +291,7 @@ public final class SearchEvent {SearchEventCache.cleanupEvents(false);EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true),- Type.CLEANUP,+ SearchEventType.CLEANUP,"",0,0), false);@@ -292,15 +303,11 @@ public final class SearchEvent {SearchEventCache.put(this.query.id(false), this);}- public ReferenceOrder getOrder() {- return this.order;- }-public long getEventTime() {return this.eventTime;}- public void resetEventTime() {+ protected void resetEventTime() {this.eventTime = System.currentTimeMillis();}@@ -313,7 +320,7 @@ public final class SearchEvent {this.resultFetcher.query = query;}- public void cleanup() {+ protected void cleanup() {this.resultFetcher.setCleanupState();// stop all threads@@ -341,7 +348,7 @@ public final class SearchEvent {}// call the worker threads and ask them to stop- for ( final Worker w : this.resultFetcher.workerThreads ) {+ for ( final SnippetWorker w : this.resultFetcher.workerThreads ) {if ( w != null && w.isAlive() ) {w.pleaseStop();w.interrupt();@@ -374,10 +381,6 @@ public final class SearchEvent {}}- public Iterator<Map.Entry<byte[], String>> abstractsString() {- return this.IAResults.entrySet().iterator();- }-public String abstractsString(final byte[] hash) {return this.IAResults.get(hash);}@@ -402,26 +405,6 @@ public final class SearchEvent {return this.IAneardhthash;}- boolean anyRemoteSearchAlive() {- // check primary search threads- if ( (this.primarySearchThreadsL != null) && (this.primarySearchThreadsL.size() != 0) ) {- for ( final RemoteSearch primarySearchThread : this.primarySearchThreadsL ) {- if ( (primarySearchThread != null) && (primarySearchThread.isAlive()) ) {- return true;- }- }- }- // maybe a secondary search thread is alive, check this- if ( (this.secondarySearchThreads != null) && (this.secondarySearchThreads.length != 0) ) {- for ( final Thread secondarySearchThread : this.secondarySearchThreads ) {- if ( (secondarySearchThread != null) && (secondarySearchThread.isAlive()) ) {- return true;- }- }- }- return false;- }-public List<RemoteSearch> getPrimarySearchThreads() {return this.primarySearchThreadsL;}@@ -430,14 +413,10 @@ public final class SearchEvent {return this.secondarySearchThreads;}- public RWIProcess getRankingResult() {+ public RankingProcess getRankingResult() {return this.rankingProcess;}- public ScoreMap<String> getNamespaceNavigator() {- return this.rankingProcess.getNamespaceNavigator();- }-public ScoreMap<String> getHostNavigator() {return this.rankingProcess.getHostNavigator();}@@ -447,19 +426,36 @@ public final class SearchEvent {return this.rankingProcess.getTopicNavigator(count);}- public ScoreMap<String> getAuthorNavigator() {- // returns a list of authors so far seen on result set- return this.rankingProcess.getAuthorNavigator();+ public ScoreMap<String> getNamespaceNavigator() {+ if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("namespace", 0) < 0 ) {+ return new ClusteredScoreMap<String>();+ }+ return this.namespaceNavigator;}-+public ScoreMap<String> getProtocolNavigator() {- return this.rankingProcess.getProtocolNavigator();+ if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("protocol", 0) < 0 ) {+ return new ClusteredScoreMap<String>();+ }+ return this.protocolNavigator;}public ScoreMap<String> getFiletypeNavigator() {- return this.rankingProcess.getFiletypeNavigator();+ if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("filetype", 0) < 0 ) {+ return new ClusteredScoreMap<String>();+ }+ return this.filetypeNavigator;}+ public ScoreMap<String> getAuthorNavigator() {+ // create a list of words that had been computed by statistics over all+ // words that appeared in the url or the description of all urls+ if ( !this.query.navigators.equals("all") && this.query.navigators.indexOf("authors", 0) < 0 ) {+ return new ConcurrentScoreMap<String>();+ }+ return this.authorNavigator;+ }+public Map<String,ScoreMap<String>> getVocabularyNavigators() {return this.rankingProcess.getVocabularyNavigators();}@@ -481,227 +477,485 @@ public final class SearchEvent {return this.resultFetcher.oneResult(item, timeout);}- //boolean secondarySearchStartet = false;+ public SnippetProcess result() {+ return this.resultFetcher;+ }++ protected boolean workerAlive() {+ if ( this.resultFetcher == null || this.resultFetcher.workerThreads == null ) {+ return false;+ }+ for ( final SnippetWorker w : this.resultFetcher.workerThreads ) {+ if ( w != null && w.isAlive() ) {+ return true;+ }+ }+ return false;+ }++ public void add(+ final List<URIMetadataNode> index,+ final boolean local,+ final String resourceName,+ final int fullResource) {++ this.rankingProcess.addBegin();+ assert (index != null);+ if (index.isEmpty()) return;++ if (!local) {+ assert fullResource >= 0 : "fullResource = " + fullResource;+ this.rankingProcess.remote_resourceSize += fullResource;+ this.rankingProcess.remote_peerCount++;+ }- public static class HeuristicResult /*implements Comparable<HeuristicResult>*/- {- private final byte[] urlhash;- public final String heuristicName;- public final boolean redundant;+ long timer = System.currentTimeMillis();- private HeuristicResult(final byte[] urlhash, final String heuristicName, final boolean redundant) {- this.urlhash = urlhash;- this.heuristicName = heuristicName;- this.redundant = redundant;+ // normalize entries+ int is = index.size();+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(+ this.query.id(true),+ SearchEventType.NORMALIZING,+ resourceName,+ is,+ System.currentTimeMillis() - timer), false);+ if (!local) {+ this.rankingProcess.receivedRemoteReferences.addAndGet(is);}- public int compareTo(HeuristicResult o) {- return Base64Order.enhancedCoder.compare(this.urlhash, o.urlhash);- }+ // iterate over normalized entries and select some that are better than currently stored+ timer = System.currentTimeMillis();+ final boolean nav_hosts = this.query.navigators.equals("all") || this.query.navigators.indexOf("hosts", 0) >= 0;- @Override- public int hashCode() {- return (int) Base64Order.enhancedCoder.cardinal(this.urlhash);+ // apply all constraints+ try {+ final String pattern = this.query.urlMask.pattern();+ final boolean httpPattern = pattern.equals("http://.*");+ final boolean noHttpButProtocolPattern = pattern.equals("https://.*") || pattern.equals("ftp://.*") || pattern.equals("smb://.*") || pattern.equals("file://.*");+ pollloop: for (URIMetadataNode iEntry: index) {++ // doublecheck for urls+ if (this.rankingProcess.urlhashes.has(iEntry.hash())) {+ continue pollloop;+ }++ // increase flag counts+ for ( int j = 0; j < 32; j++ ) {+ if (iEntry.flags().get(j)) this.rankingProcess.flagCount()[j]++;+ }++ // check constraints+ Bitfield flags = iEntry.flags();+ if (!this.rankingProcess.testFlags(flags)) continue pollloop;++ // check document domain+ if (this.query.contentdom.getCode() > 0 &&+ ((this.query.contentdom == ContentDomain.AUDIO && !(flags.get(Condenser.flag_cat_hasaudio))) ||+ (this.query.contentdom == ContentDomain.VIDEO && !(flags.get(Condenser.flag_cat_hasvideo))) ||+ (this.query.contentdom == ContentDomain.IMAGE && !(flags.get(Condenser.flag_cat_hasimage))) ||+ (this.query.contentdom == ContentDomain.APP && !(flags.get(Condenser.flag_cat_hasapp))))) {+ continue pollloop;+ }++ // check site constraints+ final String hosthash = iEntry.hosthash();+ if ( this.query.sitehash == null ) {+ if (this.query.siteexcludes != null && this.query.siteexcludes.contains(hosthash)) {+ continue pollloop;+ }+ } else {+ // filter out all domains that do not match with the site constraint+ if (!hosthash.equals(this.query.sitehash)) continue pollloop;+ }++ // collect host navigation information (even if we have only one; this is to provide a switch-off button)+ if (this.query.navigators.isEmpty() && (nav_hosts || this.query.urlMask_isCatchall)) {+ this.rankingProcess.hostNavigator.inc(hosthash);+ this.rankingProcess.hostResolver.put(hosthash, iEntry.hash());+ }++ // check protocol+ if ( !this.query.urlMask_isCatchall ) {+ final boolean httpFlagSet = DigestURI.flag4HTTPset(iEntry.hash());+ if ( httpPattern && !httpFlagSet ) {+ continue pollloop;+ }+ if ( noHttpButProtocolPattern && httpFlagSet ) {+ continue pollloop;+ }+ }++ // check vocabulary constraint+ String subject = YaCyMetadata.hashURI(iEntry.hash());+ Resource resource = JenaTripleStore.getResource(subject);+ if (this.query.metatags != null && !this.query.metatags.isEmpty()) {+ // all metatags must appear in the tags list+ for (Tagging.Metatag metatag: this.query.metatags) {+ Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, metatag.getPredicate());+ if (!ni.hasNext()) continue pollloop;+ String tags = ni.next().toString();+ if (tags.indexOf(metatag.getObject()) < 0) continue pollloop;+ }+ }++ // add navigators using the triplestore+ for (Map.Entry<String, String> v: this.rankingProcess.taggingPredicates.entrySet()) {+ Iterator<RDFNode> ni = JenaTripleStore.getObjects(resource, v.getValue());+ while (ni.hasNext()) {+ String[] tags = ni.next().toString().split(",");+ for (String tag: tags) {+ ScoreMap<String> voc = this.rankingProcess.vocabularyNavigator.get(v.getKey());+ if (voc == null) {+ voc = new ConcurrentScoreMap<String>();+ this.rankingProcess.vocabularyNavigator.put(v.getKey(), voc);+ }+ voc.inc(tag);+ }+ }+ }++ // finally extend the double-check and insert result to stack+ this.rankingProcess.urlhashes.putUnique(iEntry.hash());+ rankingtryloop: while (true) {+ try {+ this.nodeStack.put(new ReverseElement<URIMetadataNode>(iEntry, this.rankingProcess.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)+ break rankingtryloop;+ } catch ( final ArithmeticException e ) {+ // this may happen if the concurrent normalizer changes values during cardinal computation+ continue rankingtryloop;+ }+ }+ // increase counter for statistics+ if (local) this.rankingProcess.local_indexCount++; else this.rankingProcess.remote_indexCount++;+ }+ } catch ( final SpaceExceededException e ) {}- @Override- public boolean equals(Object o) {- return Base64Order.enhancedCoder.equal(this.urlhash, ((HeuristicResult) o).urlhash);+ //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(+ this.query.id(true),+ SearchEventType.PRESORT,+ resourceName,+ index.size(),+ System.currentTimeMillis() - timer), false);+ }++ protected long waitTimeRecommendation() {+ return this.maxExpectedRemoteReferences.get() == 0 ? 0 :+ Math.min(maxWaitPerResult,+ Math.min(+ maxWaitPerResult * this.expectedRemoteReferences.get() / this.maxExpectedRemoteReferences.get(),+ maxWaitPerResult * (100 - Math.min(100, this.rankingProcess.receivedRemoteReferences.get())) / 100));+ }++ public void addExpectedRemoteReferences(int x) {+ if ( x > 0 ) {+ this.maxExpectedRemoteReferences.addAndGet(x);}+ this.expectedRemoteReferences.addAndGet(x);}- public class SecondarySearchSuperviser extends Thread {+ protected boolean expectMoreRemoteReferences() {+ return this.expectedRemoteReferences.get() > 0;+ }++ public int getSortOutCount() {+ return this.sortout;+ }- // cache for index abstracts; word:TreeMap mapping where the embedded TreeMap is a urlhash:peerlist relation- // this relation contains the information where specific urls can be found in specific peers- private final SortedMap<String, SortedMap<String, Set<String>>> abstractsCache;- private final SortedSet<String> checkedPeers;- private final Semaphore trigger;+ private URIMetadataNode takeRWI(final boolean skipDoubleDom, final long waitingtime) {- public SecondarySearchSuperviser() {- this.abstractsCache = Collections.synchronizedSortedMap(new TreeMap<String, SortedMap<String, Set<String>>>());- this.checkedPeers = Collections.synchronizedSortedSet(new TreeSet<String>());- this.trigger = new Semaphore(0);- }+ // returns from the current RWI list the best entry and removes this entry from the list+ WeakPriorityBlockingQueue<WordReferenceVars> m;+ WeakPriorityBlockingQueue.Element<WordReferenceVars> rwi = null;+ WeakPriorityBlockingQueue.Element<URIMetadataNode> page;- /**- * add a single abstract to the existing set of abstracts- *- * @param wordhash- * @param singleAbstract // a mapping from url-hashes to a string of peer-hashes- */- public void addAbstract(final String wordhash, final SortedMap<String, Set<String>> singleAbstract) {- final SortedMap<String, Set<String>> oldAbstract = this.abstractsCache.get(wordhash);- if ( oldAbstract == null ) {- // new abstracts in the cache- this.abstractsCache.put(wordhash, singleAbstract);- return;+ // take one entry from the stack if there are entries on that stack or the feeding is not yet finished+ try {+ int loops = 0; // a loop counter to terminate the reading if all the results are from the same domain+ // wait some time if we did not get so much remote results so far to get a better ranking over remote results+ // we wait at most 30 milliseconds to get a maximum total waiting time of 300 milliseconds for 10 results+ long wait = waitTimeRecommendation();+ if ( wait > 0 ) {+ //System.out.println("*** RWIProcess extra wait: " + wait + "ms; expectedRemoteReferences = " + this.expectedRemoteReferences.get() + ", receivedRemoteReferences = " + this.receivedRemoteReferences.get() + ", initialExpectedRemoteReferences = " + this.maxExpectedRemoteReferences.get());+ Thread.sleep(wait);}- // extend the abstracts in the cache: join the single abstracts- new Thread() {- @Override- public void run() {- Thread.currentThread().setName("SearchEvent.addAbstract:" + wordhash);- for ( final Map.Entry<String, Set<String>> oneref : singleAbstract.entrySet() ) {- final String urlhash = oneref.getKey();- final Set<String> peerlistNew = oneref.getValue();- final Set<String> peerlistOld = oldAbstract.put(urlhash, peerlistNew);- if ( peerlistOld != null ) {- peerlistOld.addAll(peerlistNew);- }+ // loop as long as we can expect that we should get more results+ final long timeout = System.currentTimeMillis() + waitingtime;+ while (((!this.rankingProcess.feedingIsFinished() && this.rankingProcess.addRunning()) || this.nodeStack.sizeQueue() > 0 || this.rankingProcess.rwiQueueSize() > 0) &&+ (this.query.itemsPerPage < 1 || loops++ < this.query.itemsPerPage || (loops > 1000 && !this.rankingProcess.doubleDomCache.isEmpty()))) {+ page = null;+ rwi = null;+ if ( waitingtime <= 0 ) {+ page = this.rankingProcess.addRunning() ? this.nodeStack.poll(waitingtime) : this.nodeStack.poll();+ if (page == null) rwi = this.rankingProcess.addRunning() ? this.rankingProcess.rwiStack.poll(waitingtime) : this.rankingProcess.rwiStack.poll();+ } else {+ timeoutloop: while ( System.currentTimeMillis() < timeout ) {+ //System.out.println("### RWIProcess feedingIsFinished() = " + feedingIsFinished() + ", this.nodeStack.sizeQueue() = " + this.nodeStack.sizeQueue());+ if (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0 && this.nodeStack.sizeQueue() == 0) break timeoutloop;+ page = this.nodeStack.poll(50);+ if (page != null) break timeoutloop;+ rwi = this.rankingProcess.rwiStack.poll(50);+ if (rwi != null) break timeoutloop;}}- }.start();- // abstractsCache.put(wordhash, oldAbstract); // put not necessary since it is sufficient to just change the value content (it stays assigned)- }-- public void commitAbstract() {- this.trigger.release();- }-- private Set<String> wordsFromPeer(final String peerhash, final Set<String> urls) {- Set<String> wordlist = new HashSet<String>();- String word;- Set<String> peerlist;- SortedMap<String, Set<String>> urlPeerlist; // urlhash:peerlist- for ( Map.Entry<String, SortedMap<String, Set<String>>> entry: this.abstractsCache.entrySet()) {- word = entry.getKey();- urlPeerlist = entry.getValue();- for (String url: urls) {- peerlist = urlPeerlist.get(url);- if (peerlist != null && peerlist.contains(peerhash)) {- wordlist.add(word);- break;+ if (page != null) return page.getElement();+ if (rwi == null) break;+ if (!skipDoubleDom) {+ return this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());+ }++ // check doubledom+ final String hosthash = rwi.getElement().hosthash();+ m = this.rankingProcess.doubleDomCache.get(hosthash);+ if (m == null) {+ synchronized ( this.rankingProcess.doubleDomCache ) {+ m = this.rankingProcess.doubleDomCache.get(hosthash);+ if ( m == null ) {+ // first appearance of dom. we create an entry to signal that one of that domain was already returned+ m = new WeakPriorityBlockingQueue<WordReferenceVars>(this.query.snippetCacheStrategy == null || this.query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? RankingProcess.max_results_preparation_special : RankingProcess.max_results_preparation, false);+ this.rankingProcess.doubleDomCache.put(hosthash, m);+ return this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());+ }+ // second appearances of dom+ m.put(rwi);}+ } else {+ m.put(rwi);}}- return wordlist;+ } catch ( final InterruptedException e1 ) {+ }+ //Log.logWarning("RWIProcess", "feedingIsFinished() = " + feedingIsFinished());+ //Log.logWarning("RWIProcess", "this.addRunning = " + this.addRunning);+ //Log.logWarning("RWIProcess", "this.nodeStack.sizeQueue() = " + this.nodeStack.sizeQueue());+ //Log.logWarning("RWIProcess", "this.stack.sizeQueue() = " + this.rwiStack.sizeQueue());+ //Log.logWarning("RWIProcess", "this.doubleDomCachee.size() = " + this.doubleDomCache.size());+ if (this.rankingProcess.doubleDomCache.isEmpty()) {+ Log.logWarning("RWIProcess", "doubleDomCache.isEmpty");+ return null;}- @Override- public void run() {+ // no more entries in sorted RWI entries. Now take Elements from the doubleDomCache+ // find best entry from all caches+ WeakPriorityBlockingQueue.Element<WordReferenceVars> bestEntry = null;+ WeakPriorityBlockingQueue.Element<WordReferenceVars> o;+ final Iterator<WeakPriorityBlockingQueue<WordReferenceVars>> i = this.rankingProcess.doubleDomCache.values().iterator();+ while ( i.hasNext() ) {try {- boolean aquired;- while ( (aquired = this.trigger.tryAcquire(3000, TimeUnit.MILLISECONDS)) == true ) { // compare to true to remove warning: "Possible accidental assignement"- if ( !aquired || MemoryControl.shortStatus()) {- break;+ m = i.next();+ } catch ( final ConcurrentModificationException e ) {+ Log.logException(e);+ continue; // not the best solution...+ }+ if (m == null) continue;+ if (m.isEmpty()) continue;+ if (bestEntry == null) {+ bestEntry = m.peek();+ continue;+ }+ o = m.peek();+ if (o == null) continue;+ if (o.getWeight() < bestEntry.getWeight()) bestEntry = o;+ }+ if (bestEntry == null) {+ Log.logWarning("RWIProcess", "bestEntry == null (1)");+ return null;+ }++ // finally remove the best entry from the doubledom cache+ m = this.rankingProcess.doubleDomCache.get(bestEntry.getElement().hosthash());+ if (m != null) {+ bestEntry = m.poll();+ if (bestEntry != null && m.sizeAvailable() == 0) {+ synchronized ( this.rankingProcess.doubleDomCache ) {+ if (m.sizeAvailable() == 0) {+ this.rankingProcess.doubleDomCache.remove(bestEntry.getElement().hosthash());}- // a trigger was released- prepareSecondarySearch();}- } catch ( final InterruptedException e ) {- // the thread was interrupted- // do nothing}- // the time-out was reached:- // as we will never again prepare another secondary search, we can flush all cached data- this.abstractsCache.clear();- this.checkedPeers.clear();}+ if (bestEntry == null) {+ Log.logWarning("RWIProcess", "bestEntry == null (2)");+ return null;+ }+ return this.query.getSegment().fulltext().getMetadata(bestEntry.getElement(), bestEntry.getWeight());+ }++ /**+ * get one metadata entry from the ranked results. This will be the 'best' entry so far according to the+ * applied ranking. If there are no more entries left or the timeout limit is reached then null is+ * returned. The caller may distinguish the timeout case from the case where there will be no more also in+ * the future by calling this.feedingIsFinished()+ *+ * @param skipDoubleDom should be true if it is wanted that double domain entries are skipped+ * @param waitingtime the time this method may take for a result computation+ * @return a metadata entry for a url+ */+ public URIMetadataNode takeURL(final boolean skipDoubleDom, final long waitingtime) {+ // returns from the current RWI list the best URL entry and removes this entry from the list+ final long timeout = System.currentTimeMillis() + Math.max(10, waitingtime);+ int p = -1;+ long timeleft;+ while ( (timeleft = timeout - System.currentTimeMillis()) > 0 ) {+ //System.out.println("timeleft = " + timeleft);+ final URIMetadataNode page = takeRWI(skipDoubleDom, timeleft);+ if (page == null) {+ Log.logWarning("RWIProcess", "takeRWI returned null");+ return null; // all time was already wasted in takeRWI to get another element+ }- private void prepareSecondarySearch() {- if ( this.abstractsCache == null || this.abstractsCache.size() != SearchEvent.this.query.query_include_hashes.size() ) {- return; // secondary search not possible (yet)+ if ( !this.query.urlMask_isCatchall ) {+ // check url mask+ if ( !page.matches(this.query.urlMask) ) {+ this.sortout++;+ continue;+ }}- // catch up index abstracts and join them; then call peers again to submit their urls- /*- System.out.println("DEBUG-INDEXABSTRACT: " + this.abstractsCache.size() + " word references caught, " + SearchEvent.this.query.queryHashes.size() + " needed");- for (final Map.Entry<String, SortedMap<String, Set<String>>> entry: this.abstractsCache.entrySet()) {- System.out.println("DEBUG-INDEXABSTRACT: hash " + entry.getKey() + ": " + ((SearchEvent.this.query.queryHashes.has(entry.getKey().getBytes()) ? "NEEDED" : "NOT NEEDED") + "; " + entry.getValue().size() + " entries"));+ // check for more errors+ if ( page.url() == null ) {+ this.sortout++;+ continue; // rare case where the url is corrupted}- */- // find out if there are enough references for all words that are searched- if ( this.abstractsCache.size() != SearchEvent.this.query.query_include_hashes.size() ) {- return;+ // check content domain+ if ((this.query.contentdom.getCode() > 0 && page.url().getContentDomain() != this.query.contentdom) ||+ (this.query.contentdom == Classification.ContentDomain.TEXT && page.url().getContentDomain().getCode() > 0)) {+ this.sortout++;+ continue;}- // join all the urlhash:peerlist relations: the resulting map has values with a combined peer-list list- final SortedMap<String, Set<String>> abstractJoin = SetTools.joinConstructive(this.abstractsCache.values(), true);- if ( abstractJoin.isEmpty() ) {- return;- // the join result is now a urlhash: peer-list relation+ // Check for blacklist+ if (Switchboard.urlBlacklist.isListed(BlacklistType.SEARCH, page)) {+ this.sortout++;+ continue;}- // generate a list of peers that have the urls for the joined search result- final SortedMap<String, Set<String>> secondarySearchURLs = new TreeMap<String, Set<String>>(); // a (peerhash:urlhash-liststring) mapping- String url;- Set<String> urls;- Set<String> peerlist;- final String mypeerhash = SearchEvent.this.peers.mySeed().hash;- boolean mypeerinvolved = false;- int mypeercount;- for ( final Map.Entry<String, Set<String>> entry : abstractJoin.entrySet() ) {- url = entry.getKey();- peerlist = entry.getValue();- //System.out.println("DEBUG-INDEXABSTRACT: url " + url + ": from peers " + peerlist);- mypeercount = 0;- for (String peer: peerlist) {- if ( (peer.equals(mypeerhash)) && (mypeercount++ > 1) ) {- continue;- }- //if (peers.indexOf(peer) < j) continue; // avoid doubles that may appear in the abstractJoin- urls = secondarySearchURLs.get(peer);- if ( urls == null ) {- urls = new HashSet<String>();- urls.add(url);- secondarySearchURLs.put(peer, urls);- } else {- urls.add(url);+ // content control++ if (Switchboard.getSwitchboard().getConfigBool("contentcontrol.enabled", false) == true) {++ // check global network filter from bookmark list+ if (!Switchboard.getSwitchboard()+ .getConfig("contentcontrol.mandatoryfilterlist", "")+ .equals("")) {++ FilterEngine f = ContentControlFilterUpdateThread.getNetworkFilter();+ if (f != null) {+ if (!f.isListed(page.url(), null)) {+ this.sortout++;+ continue;+ }}- secondarySearchURLs.put(peer, urls);}- if ( mypeercount == 1 ) {- mypeerinvolved = true;+ }++ final String pageurl = page.url().toNormalform(true);+ final String pageauthor = page.dc_creator();+ final String pagetitle = page.dc_title().toLowerCase();++ // check exclusion+ if ( this.query.query_exclude_hashes != null && !this.query.query_exclude_hashes.isEmpty() &&+ ((QueryParams.anymatch(pagetitle, this.query.query_exclude_hashes))+ || (QueryParams.anymatch(pageurl.toLowerCase(), this.query.query_exclude_hashes))+ || (QueryParams.anymatch(pageauthor.toLowerCase(), this.query.query_exclude_hashes)))) {+ this.sortout++;+ continue;+ }++ // check index-of constraint+ if ( (this.query.constraint != null)+ && (this.query.constraint.get(Condenser.flag_cat_indexof))+ && (!(pagetitle.startsWith("index of"))) ) {+ final Iterator<byte[]> wi = this.query.query_include_hashes.iterator();+ while ( wi.hasNext() ) {+ this.query.getSegment().termIndex().removeDelayed(wi.next(), page.hash());}+ this.sortout++;+ continue;+ }++ // check location constraint+ if ( (this.query.constraint != null)+ && (this.query.constraint.get(Condenser.flag_cat_haslocation))+ && (page.lat() == 0.0f || page.lon() == 0.0f) ) {+ this.sortout++;+ continue;}- // compute words for secondary search and start the secondary searches- Set<String> words;- SearchEvent.this.secondarySearchThreads = new Thread[(mypeerinvolved) ? secondarySearchURLs.size() - 1 : secondarySearchURLs.size()];- int c = 0;- for ( final Map.Entry<String, Set<String>> entry : secondarySearchURLs.entrySet() ) {- String peer = entry.getKey();- if ( peer.equals(mypeerhash) ) {- continue; // we don't need to ask ourself+ // check geo coordinates+ double lat, lon;+ if (this.query.radius > 0.0d && this.query.lat != 0.0d && this.query.lon != 0.0d && (lat = page.lat()) != 0.0d && (lon = page.lon()) != 0.0d) {+ double latDelta = this.query.lat - lat;+ double lonDelta = this.query.lon - lon;+ double distance = Math.sqrt(latDelta * latDelta + lonDelta * lonDelta); // pythagoras+ if (distance > this.query.radius) {+ this.sortout++;+ continue;}- if ( this.checkedPeers.contains(peer) ) {- continue; // do not ask a peer again+ }++ // evaluate information of metadata for navigation+ // author navigation:+ if ( pageauthor != null && pageauthor.length() > 0 ) {+ // add author to the author navigator+ final String authorhash = ASCII.String(Word.word2hash(pageauthor));++ // check if we already are filtering for authors+ if ( this.query.authorhash != null && !this.query.authorhash.equals(authorhash) ) {+ this.sortout++;+ continue;}- urls = entry.getValue();- words = wordsFromPeer(peer, urls);- if ( words.isEmpty() ) {- continue; // ???++ // add author to the author navigator+ this.authorNavigator.inc(pageauthor);+ } else if ( this.query.authorhash != null ) {+ this.sortout++;+ continue;+ }++ // check Scanner+ if ( !Scanner.acceptURL(page.url()) ) {+ this.sortout++;+ continue;+ }++ // from here: collect navigation information++ // collect host navigation information (even if we have only one; this is to provide a switch-off button)+ if (!this.query.navigators.isEmpty() && (this.query.urlMask_isCatchall || this.query.navigators.equals("all") || this.query.navigators.indexOf("hosts", 0) >= 0)) {+ final String hosthash = page.hosthash();+ this.rankingProcess.hostNavigator.inc(hosthash);+ this.rankingProcess.hostResolver.put(hosthash, page.hash());+ }++ // namespace navigation+ String pagepath = page.url().getPath();+ if ( (p = pagepath.indexOf(':')) >= 0 ) {+ pagepath = pagepath.substring(0, p);+ p = pagepath.lastIndexOf('/');+ if ( p >= 0 ) {+ pagepath = pagepath.substring(p + 1);+ this.namespaceNavigator.inc(pagepath);}- Log.logInfo("SearchEvent.SecondarySearchSuperviser", "asking peer " + peer + " for urls: " + urls + " from words: " + words);- this.checkedPeers.add(peer);- SearchEvent.this.secondarySearchThreads[c++] =- RemoteSearch.secondaryRemoteSearch(- SearchEvent.this,- words,- urls.toString(),- 6000,- peer,- Switchboard.urlBlacklist);}- }- }- public SnippetProcess result() {- return this.resultFetcher;- }+ // protocol navigation+ final String protocol = page.url().getProtocol();+ this.protocolNavigator.inc(protocol);- public boolean workerAlive() {- if ( this.resultFetcher == null || this.resultFetcher.workerThreads == null ) {- return false;- }- for ( final Worker w : this.resultFetcher.workerThreads ) {- if ( w != null && w.isAlive() ) {- return true;+ // file type navigation+ final String fileext = page.url().getFileExtension();+ if ( fileext.length() > 0 ) {+ this.filetypeNavigator.inc(fileext);}++ // accept url+ return page;}- return false;+ Log.logWarning("RWIProcess", "loop terminated");+ return null;}}diff --git a/source/net/yacy/search/query/SearchEventCache.java b/source/net/yacy/search/query/SearchEventCache.javaindex 26d544a63..947e07b32 100644--- a/source/net/yacy/search/query/SearchEventCache.java+++ b/source/net/yacy/search/query/SearchEventCache.java@@ -42,11 +42,11 @@ import net.yacy.search.SwitchboardConstants;public class SearchEventCache {private volatile static Map<String, SearchEvent> lastEvents = new ConcurrentHashMap<String, SearchEvent>(); // a cache for objects from this class: re-use old search requests- public static final long eventLifetimeBigMem = 600000; // the time an event will stay in the cache when available memory is high, 10 Minutes- public static final long eventLifetimeMediumMem = 60000; // the time an event will stay in the cache when available memory is medium, 1 Minute- public static final long eventLifetimeShortMem = 10000; // the time an event will stay in the cache when memory is low, 10 seconds- public static final long memlimitHigh = 600 * 1024 * 1024; // 400 MB- public static final long memlimitMedium = 200 * 1024 * 1024; // 100 MB+ private static final long eventLifetimeBigMem = 600000; // the time an event will stay in the cache when available memory is high, 10 Minutes+ private static final long eventLifetimeMediumMem = 60000; // the time an event will stay in the cache when available memory is medium, 1 Minute+ private static final long eventLifetimeShortMem = 10000; // the time an event will stay in the cache when memory is low, 10 seconds+ private static final long memlimitHigh = 600 * 1024 * 1024; // 400 MB+ private static final long memlimitMedium = 200 * 1024 * 1024; // 100 MBpublic volatile static String lastEventID = "";public static long cacheInsert = 0, cacheHit = 0, cacheMiss = 0, cacheDelete = 0;@@ -54,7 +54,7 @@ public class SearchEventCache {return lastEvents.size();}- public static void put(final String eventID, final SearchEvent event) {+ protected static void put(final String eventID, final SearchEvent event) {if (MemoryControl.shortStatus()) cleanupEvents(false);lastEventID = eventID;final SearchEvent oldEvent = lastEvents.put(eventID, event);@@ -105,7 +105,7 @@ public class SearchEventCache {return event;}- public static int countAliveThreads() {+ private static int countAliveThreads() {int alive = 0;for (final SearchEvent e: lastEvents.values()) {if (e.workerAlive()) alive++;@@ -143,7 +143,6 @@ public class SearchEventCache {}}if (event == null) {-// check if there are too many other searches alive nowLog.logInfo("SearchEventCache", "getEvent: " + lastEvents.size() + " in cache; " + countAliveThreads() + " alive");diff --git a/source/net/yacy/search/query/SearchEventType.java b/source/net/yacy/search/query/SearchEventType.javanew file mode 100644index 000000000..927675795--- /dev/null+++ b/source/net/yacy/search/query/SearchEventType.java@@ -0,0 +1,37 @@+/**+ * SearchEventType+ * Copyright 2012 by Michael Peter Christen, [email protected], Frankfurt a. M., Germany+ * First released 01.11.2012 at http://yacy.net+ *+ * 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/>.+ */++package net.yacy.search.query;++public enum SearchEventType {+ INITIALIZATION,+ COLLECTION,+ JOIN,+ PRESORT,+ NORMALIZING,+ FINALIZATION,+ REMOTESEARCH_START,+ ABSTRACTS,+ CLEANUP,+ SNIPPETFETCH_START,+ ONERESULT,+ REFERENCECOLLECTION,+ RESULTLIST;+}diff --git a/source/net/yacy/search/query/SecondarySearchSuperviser.java b/source/net/yacy/search/query/SecondarySearchSuperviser.javanew file mode 100644index 000000000..1e651fb01--- /dev/null+++ b/source/net/yacy/search/query/SecondarySearchSuperviser.java@@ -0,0 +1,198 @@+package net.yacy.search.query;++import java.util.Collections;+import java.util.HashSet;+import java.util.Map;+import java.util.Set;+import java.util.SortedMap;+import java.util.SortedSet;+import java.util.TreeMap;+import java.util.TreeSet;+import java.util.concurrent.Semaphore;+import java.util.concurrent.TimeUnit;++import net.yacy.kelondro.logging.Log;+import net.yacy.kelondro.util.MemoryControl;+import net.yacy.kelondro.util.SetTools;+import net.yacy.peers.RemoteSearch;+import net.yacy.search.Switchboard;++public class SecondarySearchSuperviser extends Thread {++ // cache for index abstracts; word:TreeMap mapping where the embedded TreeMap is a urlhash:peerlist relation+ // this relation contains the information where specific urls can be found in specific peers+ private final SortedMap<String, SortedMap<String, Set<String>>> abstractsCache;+ private final SortedSet<String> checkedPeers;+ private final Semaphore trigger;+ private final SearchEvent searchEvent;++ protected SecondarySearchSuperviser(SearchEvent searchEvent) {+ this.abstractsCache = Collections.synchronizedSortedMap(new TreeMap<String, SortedMap<String, Set<String>>>());+ this.checkedPeers = Collections.synchronizedSortedSet(new TreeSet<String>());+ this.trigger = new Semaphore(0);+ this.searchEvent = searchEvent;+ }++ /**+ * add a single abstract to the existing set of abstracts+ *+ * @param wordhash+ * @param singleAbstract // a mapping from url-hashes to a string of peer-hashes+ */+ public void addAbstract(final String wordhash, final SortedMap<String, Set<String>> singleAbstract) {+ final SortedMap<String, Set<String>> oldAbstract = this.abstractsCache.get(wordhash);+ if ( oldAbstract == null ) {+ // new abstracts in the cache+ this.abstractsCache.put(wordhash, singleAbstract);+ return;+ }+ // extend the abstracts in the cache: join the single abstracts+ new Thread() {+ @Override+ public void run() {+ Thread.currentThread().setName("SearchEvent.addAbstract:" + wordhash);+ for ( final Map.Entry<String, Set<String>> oneref : singleAbstract.entrySet() ) {+ final String urlhash = oneref.getKey();+ final Set<String> peerlistNew = oneref.getValue();+ final Set<String> peerlistOld = oldAbstract.put(urlhash, peerlistNew);+ if ( peerlistOld != null ) {+ peerlistOld.addAll(peerlistNew);+ }+ }+ }+ }.start();+ // abstractsCache.put(wordhash, oldAbstract); // put not necessary since it is sufficient to just change the value content (it stays assigned)+ }++ public void commitAbstract() {+ this.trigger.release();+ }++ private Set<String> wordsFromPeer(final String peerhash, final Set<String> urls) {+ Set<String> wordlist = new HashSet<String>();+ String word;+ Set<String> peerlist;+ SortedMap<String, Set<String>> urlPeerlist; // urlhash:peerlist+ for ( Map.Entry<String, SortedMap<String, Set<String>>> entry: this.abstractsCache.entrySet()) {+ word = entry.getKey();+ urlPeerlist = entry.getValue();+ for (String url: urls) {+ peerlist = urlPeerlist.get(url);+ if (peerlist != null && peerlist.contains(peerhash)) {+ wordlist.add(word);+ break;+ }+ }+ }+ return wordlist;+ }++ @Override+ public void run() {+ try {+ boolean aquired;+ while ( (aquired = this.trigger.tryAcquire(3000, TimeUnit.MILLISECONDS)) == true ) { // compare to true to remove warning: "Possible accidental assignement"+ if ( !aquired || MemoryControl.shortStatus()) {+ break;+ }+ // a trigger was released+ prepareSecondarySearch();+ }+ } catch ( final InterruptedException e ) {+ // the thread was interrupted+ // do nothing+ }+ // the time-out was reached:+ // as we will never again prepare another secondary search, we can flush all cached data+ this.abstractsCache.clear();+ this.checkedPeers.clear();+ }++ private void prepareSecondarySearch() {+ if ( this.abstractsCache == null || this.abstractsCache.size() != this.searchEvent.query.query_include_hashes.size() ) {+ return; // secondary search not possible (yet)+ }++ // catch up index abstracts and join them; then call peers again to submit their urls+ /*+ System.out.println("DEBUG-INDEXABSTRACT: " + this.abstractsCache.size() + " word references caught, " + SearchEvent.this.query.queryHashes.size() + " needed");+ for (final Map.Entry<String, SortedMap<String, Set<String>>> entry: this.abstractsCache.entrySet()) {+ System.out.println("DEBUG-INDEXABSTRACT: hash " + entry.getKey() + ": " + ((SearchEvent.this.query.queryHashes.has(entry.getKey().getBytes()) ? "NEEDED" : "NOT NEEDED") + "; " + entry.getValue().size() + " entries"));+ }+ */++ // find out if there are enough references for all words that are searched+ if ( this.abstractsCache.size() != this.searchEvent.query.query_include_hashes.size() ) {+ return;+ }++ // join all the urlhash:peerlist relations: the resulting map has values with a combined peer-list list+ final SortedMap<String, Set<String>> abstractJoin = SetTools.joinConstructive(this.abstractsCache.values(), true);+ if ( abstractJoin.isEmpty() ) {+ return;+ // the join result is now a urlhash: peer-list relation+ }++ // generate a list of peers that have the urls for the joined search result+ final SortedMap<String, Set<String>> secondarySearchURLs = new TreeMap<String, Set<String>>(); // a (peerhash:urlhash-liststring) mapping+ String url;+ Set<String> urls;+ Set<String> peerlist;+ final String mypeerhash = this.searchEvent.peers.mySeed().hash;+ boolean mypeerinvolved = false;+ int mypeercount;+ for ( final Map.Entry<String, Set<String>> entry : abstractJoin.entrySet() ) {+ url = entry.getKey();+ peerlist = entry.getValue();+ //System.out.println("DEBUG-INDEXABSTRACT: url " + url + ": from peers " + peerlist);+ mypeercount = 0;+ for (String peer: peerlist) {+ if ( (peer.equals(mypeerhash)) && (mypeercount++ > 1) ) {+ continue;+ }+ //if (peers.indexOf(peer) < j) continue; // avoid doubles that may appear in the abstractJoin+ urls = secondarySearchURLs.get(peer);+ if ( urls == null ) {+ urls = new HashSet<String>();+ urls.add(url);+ secondarySearchURLs.put(peer, urls);+ } else {+ urls.add(url);+ }+ secondarySearchURLs.put(peer, urls);+ }+ if ( mypeercount == 1 ) {+ mypeerinvolved = true;+ }+ }++ // compute words for secondary search and start the secondary searches+ Set<String> words;+ this.searchEvent.secondarySearchThreads = new Thread[(mypeerinvolved) ? secondarySearchURLs.size() - 1 : secondarySearchURLs.size()];+ int c = 0;+ for ( final Map.Entry<String, Set<String>> entry : secondarySearchURLs.entrySet() ) {+ String peer = entry.getKey();+ if ( peer.equals(mypeerhash) ) {+ continue; // we don't need to ask ourself+ }+ if ( this.checkedPeers.contains(peer) ) {+ continue; // do not ask a peer again+ }+ urls = entry.getValue();+ words = wordsFromPeer(peer, urls);+ if ( words.isEmpty() ) {+ continue; // ???+ }+ Log.logInfo("SearchEvent.SecondarySearchSuperviser", "asking peer " + peer + " for urls: " + urls + " from words: " + words);+ this.checkedPeers.add(peer);+ this.searchEvent.secondarySearchThreads[c++] =+ RemoteSearch.secondaryRemoteSearch(+ this.searchEvent,+ words,+ urls.toString(),+ 6000,+ peer,+ Switchboard.urlBlacklist);+ }+ }+}diff --git a/source/net/yacy/search/query/SnippetProcess.java b/source/net/yacy/search/query/SnippetProcess.javaindex b763c89ef..f33233077 100644--- a/source/net/yacy/search/query/SnippetProcess.java+++ b/source/net/yacy/search/query/SnippetProcess.java@@ -31,11 +31,7 @@ import java.util.Iterator;import java.util.List;import net.yacy.cora.document.ASCII;-import net.yacy.cora.document.Classification;-import net.yacy.cora.document.MultiProtocolURI;-import net.yacy.cora.federate.yacy.CacheStrategy;import net.yacy.cora.protocol.ResponseHeader;-import net.yacy.cora.sorting.ScoreMap;import net.yacy.cora.sorting.WeakPriorityBlockingQueue;import net.yacy.cora.sorting.WeakPriorityBlockingQueue.Element;import net.yacy.cora.sorting.WeakPriorityBlockingQueue.ReverseElement;@@ -43,9 +39,6 @@ import net.yacy.cora.storage.HandleSet;import net.yacy.cora.util.SpaceExceededException;import net.yacy.crawler.data.Cache;import net.yacy.data.WorkTables;-import net.yacy.document.Condenser;-import net.yacy.kelondro.data.meta.URIMetadataNode;-import net.yacy.kelondro.data.word.Word;import net.yacy.kelondro.index.RowHandleSet;import net.yacy.kelondro.logging.Log;import net.yacy.kelondro.util.MemoryControl;@@ -54,10 +47,8 @@ import net.yacy.peers.graphics.ProfilingGraph;import net.yacy.repository.LoaderDispatcher;import net.yacy.search.EventTracker;import net.yacy.search.Switchboard;-import net.yacy.search.index.Segment;import net.yacy.search.snippet.MediaSnippet;import net.yacy.search.snippet.ResultEntry;-import net.yacy.search.snippet.TextSnippet;public class SnippetProcess {@@ -67,40 +58,41 @@ public class SnippetProcess {private final static int SNIPPET_WORKER_THREADS = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);// input values- private final RWIProcess rankingProcess; // ordered search results, grows dynamically as all the query threads enrich this container- QueryParams query;- private final SeedDB peers;- private final WorkTables workTables;+ final SearchEvent searchEvent;+ QueryParams query;+ final SeedDB peers;+ final WorkTables workTables;// result values- private final LoaderDispatcher loader;- protected Worker[] workerThreads;- private final WeakPriorityBlockingQueue<ResultEntry> result;- private final WeakPriorityBlockingQueue<MediaSnippet> images; // container to sort images by size- private final HandleSet snippetFetchWordHashes; // a set of word hashes that are used to match with the snippets- private long urlRetrievalAllTime;- private long snippetComputationAllTime;- private final boolean deleteIfSnippetFail, remote;+ private final WeakPriorityBlockingQueue<MediaSnippet> images; // container to sort images by size+ protected final WeakPriorityBlockingQueue<ResultEntry> result;+ protected final LoaderDispatcher loader;+ protected final HandleSet snippetFetchWordHashes; // a set of word hashes that are used to match with the snippets+ protected final boolean deleteIfSnippetFail;+ protected SnippetWorker[] workerThreads;+ protected long urlRetrievalAllTime;+ protected long snippetComputationAllTime;++ private final boolean remote;private boolean cleanupState;protected SnippetProcess(+ final SearchEvent searchEvent,final LoaderDispatcher loader,- final RWIProcess rankedCache,final QueryParams query,final SeedDB peers,final WorkTables workTables,final boolean deleteIfSnippetFail,final boolean remote) {assert query != null;+ this.searchEvent = searchEvent;this.loader = loader;- this.rankingProcess = rankedCache;this.query = query;this.peers = peers;this.workTables = workTables;this.deleteIfSnippetFail = deleteIfSnippetFail;this.remote = remote;this.cleanupState = false;-this.urlRetrievalAllTime = 0;this.snippetComputationAllTime = 0;this.result = new WeakPriorityBlockingQueue<ResultEntry>(Math.max(1000, 10 * query.itemsPerPage()), true); // this is the result, enriched with snippets, ranked and ordered by ranking@@ -123,7 +115,7 @@ public class SnippetProcess {// start worker threads to fetch urls and snippetsthis.workerThreads = null;deployWorker(Math.min(SNIPPET_WORKER_THREADS, query.itemsPerPage), query.neededResults());- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(query.id(true), SearchEvent.Type.SNIPPETFETCH_START, ((this.workerThreads == null) ? "no" : this.workerThreads.length) + " online snippet fetch threads started", 0, 0), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(query.id(true), SearchEventType.SNIPPETFETCH_START, ((this.workerThreads == null) ? "no" : this.workerThreads.length) + " online snippet fetch threads started", 0, 0), false);}protected void setCleanupState() {@@ -142,12 +134,12 @@ public class SnippetProcess {// check if we already retrieved this item// (happens if a search pages is accessed a second time)final long finishTime = System.currentTimeMillis() + timeout;- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEvent.Type.ONERESULT, "started, item = " + item + ", available = " + this.result.sizeAvailable(), 0, 0), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "started, item = " + item + ", available = " + this.result.sizeAvailable(), 0, 0), false);//Log.logInfo("SnippetProcess", "*start method for item = " + item + "; anyWorkerAlive=" + anyWorkerAlive() + "; this.rankingProcess.isAlive() = " + this.rankingProcess.isAlive() + "; this.rankingProcess.feedingIsFinished() = " + this.rankingProcess.feedingIsFinished() + "; this.result.sizeAvailable() = " + this.result.sizeAvailable() + ", this.rankingProcess.sizeQueue() = " + this.rankingProcess.sizeQueue());// we must wait some time until the first result page is full to get enough elements for rankingfinal long waittimeout = System.currentTimeMillis() + 300;- if (this.remote && item < 10 && !this.rankingProcess.feedingIsFinished()) {+ if (this.remote && item < 10 && !this.searchEvent.rankingProcess.feedingIsFinished()) {// the first 10 results have a very special timing to get most of the remote results ordered// before they are presented on the first lines .. yes sleeps seem to be bad. but how shall we predict how long other// peers will take until they respond?@@ -158,7 +150,7 @@ public class SnippetProcess {int thisRankingQueueSize, lastRankingQueueSize = 0;if (item < 10) {while (- ((thisRankingQueueSize = this.rankingProcess.rwiQueueSize()) > 0 || !this.rankingProcess.feedingIsFinished()) &&+ ((thisRankingQueueSize = this.searchEvent.rankingProcess.rwiQueueSize()) > 0 || !this.searchEvent.rankingProcess.feedingIsFinished()) &&(thisRankingQueueSize > lastRankingQueueSize || this.result.sizeAvailable() < item + 1) &&System.currentTimeMillis() < waittimeout &&anyWorkerAlive()@@ -172,7 +164,7 @@ public class SnippetProcess {if (this.result.sizeAvailable() > item) {// we have the wanted result already in the result array .. return thatfinal ResultEntry re = this.result.element(item).getElement();- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEvent.Type.ONERESULT, "prefetched, item = " + item + ", available = " + this.result.sizeAvailable() + ": " + re.urlstring(), 0, 0), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "prefetched, item = " + item + ", available = " + this.result.sizeAvailable() + ": " + re.urlstring(), 0, 0), false);return re;}@@ -180,9 +172,9 @@ public class SnippetProcess {WeakPriorityBlockingQueue.Element<ResultEntry> entry = null;while (System.currentTimeMillis() < finishTime) {- Log.logInfo("SnippetProcess", "item = " + item + "; anyWorkerAlive=" + anyWorkerAlive() + "; this.rankingProcess.isAlive() = " + this.rankingProcess.isAlive() + "; this.rankingProcess.feedingIsFinished() = " + this.rankingProcess.feedingIsFinished() + "; this.result.sizeAvailable() = " + this.result.sizeAvailable() + ", this.rankingProcess.sizeQueue() = " + this.rankingProcess.rwiQueueSize() + ", this.rankingProcess.nodeStack.sizeAvailable() = " + this.rankingProcess.nodeStack.sizeAvailable());+ Log.logInfo("SnippetProcess", "item = " + item + "; anyWorkerAlive=" + anyWorkerAlive() + "; this.rankingProcess.isAlive() = " + this.searchEvent.rankingProcess.isAlive() + "; this.rankingProcess.feedingIsFinished() = " + this.searchEvent.rankingProcess.feedingIsFinished() + "; this.result.sizeAvailable() = " + this.result.sizeAvailable() + ", this.rankingProcess.sizeQueue() = " + this.searchEvent.rankingProcess.rwiQueueSize() + ", this.rankingProcess.nodeStack.sizeAvailable() = " + this.searchEvent.nodeStack.sizeAvailable());- if (!anyWorkerAlive() && !this.rankingProcess.isAlive() && this.result.sizeAvailable() + this.rankingProcess.rwiQueueSize() + this.rankingProcess.nodeStack.sizeAvailable() <= item && this.rankingProcess.feedingIsFinished()) {+ if (!anyWorkerAlive() && !this.searchEvent.rankingProcess.isAlive() && this.result.sizeAvailable() + this.searchEvent.rankingProcess.rwiQueueSize() + this.searchEvent.nodeStack.sizeAvailable() <= item && this.searchEvent.rankingProcess.feedingIsFinished()) {//Log.logInfo("SnippetProcess", "interrupted result fetching; item = " + item + "; this.result.sizeAvailable() = " + this.result.sizeAvailable() + ", this.rankingProcess.sizeQueue() = " + this.rankingProcess.sizeQueue() + "; this.rankingProcess.feedingIsFinished() = " + this.rankingProcess.feedingIsFinished());break; // the fail case}@@ -199,12 +191,12 @@ public class SnippetProcess {// finally, if there is something, return the resultif (entry == null) {- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEvent.Type.ONERESULT, "not found, item = " + item + ", available = " + this.result.sizeAvailable(), 0, 0), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "not found, item = " + item + ", available = " + this.result.sizeAvailable(), 0, 0), false);//Log.logInfo("SnippetProcess", "NO ENTRY computed (possible timeout); anyWorkerAlive=" + anyWorkerAlive() + "; this.rankingProcess.isAlive() = " + this.rankingProcess.isAlive() + "; this.rankingProcess.feedingIsFinished() = " + this.rankingProcess.feedingIsFinished() + "; this.result.sizeAvailable() = " + this.result.sizeAvailable() + ", this.rankingProcess.sizeQueue() = " + this.rankingProcess.sizeQueue());return null;}final ResultEntry re = entry.getElement();- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEvent.Type.ONERESULT, "retrieved, item = " + item + ", available = " + this.result.sizeAvailable() + ": " + re.urlstring(), 0, 0), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "retrieved, item = " + item + ", available = " + this.result.sizeAvailable() + ": " + re.urlstring(), 0, 0), false);if (item == this.query.offset + this.query.itemsPerPage - 1) {stopAllWorker(); // we don't need more}@@ -281,87 +273,27 @@ public class SnippetProcess {return this.result.list(Math.min(this.query.neededResults(), this.result.sizeAvailable()));}- private long postRanking(- final ResultEntry rentry,- final ScoreMap<String> topwords) {-- long r = 0;-- // for media search: prefer pages with many links- r += rentry.limage() << this.query.ranking.coeff_cathasimage;- r += rentry.laudio() << this.query.ranking.coeff_cathasaudio;- r += rentry.lvideo() << this.query.ranking.coeff_cathasvideo;- r += rentry.lapp() << this.query.ranking.coeff_cathasapp;-- // apply citation count- //System.out.println("POSTRANKING CITATION: references = " + rentry.referencesCount() + ", inbound = " + rentry.llocal() + ", outbound = " + rentry.lother());- r += (128 * rentry.referencesCount() / (1 + 2 * rentry.llocal() + rentry.lother())) << this.query.ranking.coeff_citation;-- // prefer hit with 'prefer' pattern- if (this.query.prefer.matcher(rentry.url().toNormalform(true)).matches()) {- r += 256 << this.query.ranking.coeff_prefer;- }- if (this.query.prefer.matcher(rentry.title()).matches()) {- r += 256 << this.query.ranking.coeff_prefer;- }-- // apply 'common-sense' heuristic using references- final String urlstring = rentry.url().toNormalform(true);- final String[] urlcomps = MultiProtocolURI.urlComps(urlstring);- final String[] descrcomps = MultiProtocolURI.splitpattern.split(rentry.title().toLowerCase());- int tc;- for (final String urlcomp : urlcomps) {- tc = topwords.get(urlcomp);- if (tc > 0) {- r += Math.max(1, tc) << this.query.ranking.coeff_urlcompintoplist;- }- }- for (final String descrcomp : descrcomps) {- tc = topwords.get(descrcomp);- if (tc > 0) {- r += Math.max(1, tc) << this.query.ranking.coeff_descrcompintoplist;- }- }-- // apply query-in-result matching- final HandleSet urlcomph = Word.words2hashesHandles(urlcomps);- final HandleSet descrcomph = Word.words2hashesHandles(descrcomps);- final Iterator<byte[]> shi = this.query.query_include_hashes.iterator();- byte[] queryhash;- while (shi.hasNext()) {- queryhash = shi.next();- if (urlcomph.has(queryhash)) {- r += 256 << this.query.ranking.coeff_appurl;- }- if (descrcomph.has(queryhash)) {- r += 256 << this.query.ranking.coeff_app_dc_title;- }- }-- return r;- }-private void deployWorker(int deployCount, final int neededResults) {if (this.cleanupState ||- (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0 && this.rankingProcess.nodeStack.sizeAvailable() == 0) ||+ (this.searchEvent.rankingProcess.feedingIsFinished() && this.searchEvent.rankingProcess.rwiQueueSize() == 0 && this.searchEvent.nodeStack.sizeAvailable() == 0) ||this.result.sizeAvailable() >= neededResults) {return;}- Worker worker;+ SnippetWorker worker;if (this.workerThreads == null) {- this.workerThreads = new Worker[deployCount];+ this.workerThreads = new SnippetWorker[deployCount];synchronized(this.workerThreads) {try {for (int i = 0; i < this.workerThreads.length; i++) {if (this.result.sizeAvailable() >= neededResults ||- (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0) && this.rankingProcess.nodeStack.sizeAvailable() == 0) {+ (this.searchEvent.rankingProcess.feedingIsFinished() && this.searchEvent.rankingProcess.rwiQueueSize() == 0) && this.searchEvent.nodeStack.sizeAvailable() == 0) {break;}- worker = new Worker(this.query.maxtime, this.query.snippetCacheStrategy, neededResults);+ worker = new SnippetWorker(this, this.query.maxtime, this.query.snippetCacheStrategy, neededResults);worker.start();this.workerThreads[i] = worker;- if (this.rankingProcess.expectMoreRemoteReferences()) {- long wait = this.rankingProcess.waitTimeRecommendation();+ if (this.searchEvent.expectMoreRemoteReferences()) {+ long wait = this.searchEvent.waitTimeRecommendation();if (wait > 0) {try {Thread.sleep(wait);} catch ( InterruptedException e ) {}}@@ -375,17 +307,17 @@ public class SnippetProcess {for (int i = 0; i < this.workerThreads.length; i++) {if (deployCount <= 0 ||this.result.sizeAvailable() >= neededResults ||- (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0) && this.rankingProcess.nodeStack.sizeAvailable() == 0) {+ (this.searchEvent.rankingProcess.feedingIsFinished() && this.searchEvent.rankingProcess.rwiQueueSize() == 0) && this.searchEvent.nodeStack.sizeAvailable() == 0) {break;}if (this.workerThreads[i] == null || !this.workerThreads[i].isAlive()) {- worker = new Worker(this.query.maxtime, this.query.snippetCacheStrategy, neededResults);+ worker = new SnippetWorker(this, this.query.maxtime, this.query.snippetCacheStrategy, neededResults);worker.start();this.workerThreads[i] = worker;deployCount--;}- if (this.rankingProcess.expectMoreRemoteReferences()) {- long wait = this.rankingProcess.waitTimeRecommendation();+ if (this.searchEvent.expectMoreRemoteReferences()) {+ long wait = this.searchEvent.waitTimeRecommendation();if (wait > 0) {try {Thread.sleep(wait);} catch ( InterruptedException e ) {}}@@ -412,7 +344,7 @@ public class SnippetProcess {return false;}synchronized(this.workerThreads) {- for (final Worker workerThread : this.workerThreads) {+ for (final SnippetWorker workerThread : this.workerThreads) {if ((workerThread != null) &&(workerThread.isAlive()) &&(workerThread.busytime() < 10000)) {@@ -423,177 +355,6 @@ public class SnippetProcess {return false;}- protected class Worker extends Thread {-- 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 CacheStrategy cacheStrategy;- private final int neededResults;- private boolean shallrun;-- private Worker(final long maxlifetime, final CacheStrategy cacheStrategy, final int neededResults) {- this.cacheStrategy = cacheStrategy;- this.lastLifeSign = System.currentTimeMillis();- this.timeout = System.currentTimeMillis() + Math.max(1000, maxlifetime);- this.neededResults = neededResults;- this.shallrun = true;- }-- @Override- public void run() {-- // start fetching urls and snippets- URIMetadataNode page;- ResultEntry resultEntry;- //final int fetchAhead = snippetMode == 0 ? 0 : 10;- final boolean nav_topics = SnippetProcess.this.query.navigators.equals("all") || SnippetProcess.this.query.navigators.indexOf("topics",0) >= 0;- try {- while (this.shallrun && System.currentTimeMillis() < this.timeout) {- this.lastLifeSign = System.currentTimeMillis();-- if (MemoryControl.shortStatus()) {- Log.logWarning("SnippetProcess", "shortStatus");- break;- }-- // check if we have enough; we stop only if we can fetch online; otherwise its better to run this to get better navigation- if ((this.cacheStrategy == null || this.cacheStrategy.isAllowedToFetchOnline()) && SnippetProcess.this.result.sizeAvailable() >= this.neededResults) {- Log.logWarning("SnippetProcess", SnippetProcess.this.result.sizeAvailable() + " = result.sizeAvailable() >= this.neededResults = " + this.neededResults);- break;- }-- // check if we can succeed if we try to take another url- if (SnippetProcess.this.rankingProcess.feedingIsFinished() && SnippetProcess.this.rankingProcess.rwiQueueSize() == 0 && SnippetProcess.this.rankingProcess.nodeStack.sizeAvailable() == 0) {- Log.logWarning("SnippetProcess", "rankingProcess.feedingIsFinished() && rankingProcess.sizeQueue() == 0");- break;- }-- // get next entry- page = SnippetProcess.this.rankingProcess.takeURL(true, Math.min(500, Math.max(20, this.timeout - System.currentTimeMillis())));- //if (page != null) Log.logInfo("SnippetProcess", "got one page: " + page.metadata().url().toNormalform(true, false));- //if (page == null) page = rankedCache.takeURL(false, this.timeout - System.currentTimeMillis());- if (page == null) {- Log.logWarning("SnippetProcess", "page == null");- break; // no more available- }-- this.setName(page.url().toNormalform(true)); // to support debugging- if (SnippetProcess.this.query.filterfailurls && SnippetProcess.this.workTables.failURLsContains(page.hash())) {- continue;- }-- // in case that we have an attached solr, we load also the solr document- String solrContent = page.getText();-- resultEntry = fetchSnippet(page, solrContent, this.cacheStrategy); // does not fetch snippets if snippetMode == 0- if (resultEntry == null) {- continue; // the entry had some problems, cannot be used- }-- //if (result.contains(resultEntry)) continue;- SnippetProcess.this.urlRetrievalAllTime += resultEntry.dbRetrievalTime;- SnippetProcess.this.snippetComputationAllTime += resultEntry.snippetComputationTime;-- // place the result to the result vector- // apply post-ranking- long ranking = resultEntry.word() == null ? 0 : Long.valueOf(SnippetProcess.this.rankingProcess.getOrder().cardinal(resultEntry.word()));- ranking += postRanking(resultEntry, SnippetProcess.this.rankingProcess.getTopicNavigator(10));- resultEntry.ranking = ranking;- SnippetProcess.this.result.put(new ReverseElement<ResultEntry>(resultEntry, ranking)); // remove smallest in case of overflow- if (nav_topics) {- SnippetProcess.this.rankingProcess.addTopics(resultEntry);- }- }- if (System.currentTimeMillis() >= this.timeout) {- Log.logWarning("SnippetProcess", "worker ended with timeout");- }- //System.out.println("FINISHED WORKER " + id + " FOR " + this.neededResults + " RESULTS, loops = " + loops);- } catch (final Exception e) { Log.logException(e); }- //Log.logInfo("SEARCH", "resultWorker thread " + this.id + " terminated");- }-- protected void pleaseStop() {- this.shallrun = false;- }-- /**- * calculate the time since the worker has had the latest activity- * @return time in milliseconds lasted since latest activity- */- private long busytime() {- return System.currentTimeMillis() - this.lastLifeSign;- }- }-- private ResultEntry fetchSnippet(final URIMetadataNode page, final String solrText, final CacheStrategy cacheStrategy) {- // Snippet Fetching can has 3 modes:- // 0 - do not fetch snippets- // 1 - fetch snippets offline only- // 2 - online snippet fetch-- // load only urls if there was not yet a root url of that hash- // find the url entry-- long startTime = System.currentTimeMillis();- if (page == null) {- return null;- }- final long dbRetrievalTime = System.currentTimeMillis() - startTime;-- if (cacheStrategy == null) {- final TextSnippet snippet = new TextSnippet(- null,- solrText,- page,- this.snippetFetchWordHashes,- //this.query.queryString,- null,- ((this.query.constraint != null) && (this.query.constraint.get(Condenser.flag_cat_indexof))),- SNIPPET_MAX_LENGTH,- !this.query.isLocal());- return new ResultEntry(page, this.query.getSegment(), this.peers, snippet, null, dbRetrievalTime, 0); // result without snippet- }-- // load snippet- if (page.url().getContentDomain() == Classification.ContentDomain.TEXT || page.url().getContentDomain() == Classification.ContentDomain.ALL) {- // attach text snippet- startTime = System.currentTimeMillis();- final TextSnippet snippet = new TextSnippet(- this.loader,- solrText,- page,- this.snippetFetchWordHashes,- cacheStrategy,- ((this.query.constraint != null) && (this.query.constraint.get(Condenser.flag_cat_indexof))),- 180,- !this.query.isLocal());- final long snippetComputationTime = System.currentTimeMillis() - startTime;- log.logInfo("text snippet load time for " + page.url() + ": " + snippetComputationTime + ", " + (!snippet.getErrorCode().fail() ? "snippet found" : ("no snippet found (" + snippet.getError() + ")")));-- if (!snippet.getErrorCode().fail()) {- // we loaded the file and found the snippet- return new ResultEntry(page, this.query.getSegment(), this.peers, snippet, null, dbRetrievalTime, snippetComputationTime); // result with snippet attached- } else if (cacheStrategy.mustBeOffline()) {- // we did not demand online loading, therefore a failure does not mean that the missing snippet causes a rejection of this result- // this may happen during a remote search, because snippet loading is omitted to retrieve results faster- return new ResultEntry(page, this.query.getSegment(), this.peers, null, null, dbRetrievalTime, snippetComputationTime); // result without snippet- } else {- // problems with snippet fetch- if (this.snippetFetchWordHashes.has(Segment.catchallHash)) {- // we accept that because the word cannot be on the page- return new ResultEntry(page, this.query.getSegment(), this.peers, null, null, dbRetrievalTime, 0);- }- final String reason = "no text snippet; errorCode = " + snippet.getErrorCode();- if (this.deleteIfSnippetFail) {- this.workTables.failURLsRegisterMissingWord(this.query.getSegment().termIndex(), page.url(), this.query.query_include_hashes, reason);- }- log.logInfo("sorted out url " + page.url().toNormalform(true) + " during search: " + reason);- return null;- }- }- return new ResultEntry(page, this.query.getSegment(), this.peers, null, null, dbRetrievalTime, 0); // result without snippet- }-/*** delete a specific entry from the search results* this is used if the user clicks on a '-' sign beside the search resultdiff --git a/source/net/yacy/search/query/SnippetWorker.java b/source/net/yacy/search/query/SnippetWorker.javanew file mode 100644index 000000000..abc9bec66--- /dev/null+++ b/source/net/yacy/search/query/SnippetWorker.java@@ -0,0 +1,270 @@+/**+ * SnippetWorker+ * Copyright 2012 by Michael Peter Christen, [email protected], Frankfurt a. M., Germany+ * First released 01.11.2012 at http://yacy.net+ *+ * 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/>.+ */++package net.yacy.search.query;++import java.util.Iterator;++import net.yacy.cora.document.Classification;+import net.yacy.cora.document.MultiProtocolURI;+import net.yacy.cora.federate.yacy.CacheStrategy;+import net.yacy.cora.sorting.ScoreMap;+import net.yacy.cora.sorting.WeakPriorityBlockingQueue.ReverseElement;+import net.yacy.cora.storage.HandleSet;+import net.yacy.document.Condenser;+import net.yacy.kelondro.data.meta.URIMetadataNode;+import net.yacy.kelondro.data.word.Word;+import net.yacy.kelondro.logging.Log;+import net.yacy.kelondro.util.MemoryControl;+import net.yacy.search.index.Segment;+import net.yacy.search.snippet.ResultEntry;+import net.yacy.search.snippet.TextSnippet;++public class SnippetWorker extends Thread {+ private final SnippetProcess snippetProcess;+ 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 CacheStrategy cacheStrategy;+ private final int neededResults;+ private boolean shallrun;++ public SnippetWorker(final SnippetProcess snippetProcess, final long maxlifetime, final CacheStrategy cacheStrategy, final int neededResults) {+ this.snippetProcess = snippetProcess;+ this.cacheStrategy = cacheStrategy;+ this.lastLifeSign = System.currentTimeMillis();+ this.timeout = System.currentTimeMillis() + Math.max(1000, maxlifetime);+ this.neededResults = neededResults;+ this.shallrun = true;+ }++ @Override+ public void run() {++ // start fetching urls and snippets+ URIMetadataNode page;+ ResultEntry resultEntry;+ //final int fetchAhead = snippetMode == 0 ? 0 : 10;+ final boolean nav_topics = this.snippetProcess.query.navigators.equals("all") || this.snippetProcess.query.navigators.indexOf("topics",0) >= 0;+ try {+ while (this.shallrun && System.currentTimeMillis() < this.timeout) {+ this.lastLifeSign = System.currentTimeMillis();++ if (MemoryControl.shortStatus()) {+ Log.logWarning("SnippetProcess", "shortStatus");+ break;+ }++ // check if we have enough; we stop only if we can fetch online; otherwise its better to run this to get better navigation+ if ((this.cacheStrategy == null || this.cacheStrategy.isAllowedToFetchOnline()) && this.snippetProcess.result.sizeAvailable() >= this.neededResults) {+ Log.logWarning("SnippetProcess", this.snippetProcess.result.sizeAvailable() + " = result.sizeAvailable() >= this.neededResults = " + this.neededResults);+ break;+ }++ // check if we can succeed if we try to take another url+ if (this.snippetProcess.searchEvent.rankingProcess.feedingIsFinished() && this.snippetProcess.searchEvent.rankingProcess.rwiQueueSize() == 0 && this.snippetProcess.searchEvent.nodeStack.sizeAvailable() == 0) {+ Log.logWarning("SnippetProcess", "rankingProcess.feedingIsFinished() && rankingProcess.sizeQueue() == 0");+ break;+ }++ // get next entry+ page = this.snippetProcess.searchEvent.takeURL(true, Math.min(500, Math.max(20, this.timeout - System.currentTimeMillis())));+ //if (page != null) Log.logInfo("SnippetProcess", "got one page: " + page.metadata().url().toNormalform(true, false));+ //if (page == null) page = rankedCache.takeURL(false, this.timeout - System.currentTimeMillis());+ if (page == null) {+ Log.logWarning("SnippetProcess", "page == null");+ break; // no more available+ }++ this.setName(page.url().toNormalform(true)); // to support debugging+ if (this.snippetProcess.query.filterfailurls && this.snippetProcess.workTables.failURLsContains(page.hash())) {+ continue;+ }++ // in case that we have an attached solr, we load also the solr document+ String solrContent = page.getText();++ resultEntry = fetchSnippet(page, solrContent, this.cacheStrategy); // does not fetch snippets if snippetMode == 0+ if (resultEntry == null) {+ continue; // the entry had some problems, cannot be used+ }++ //if (result.contains(resultEntry)) continue;+ this.snippetProcess.urlRetrievalAllTime += resultEntry.dbRetrievalTime;+ this.snippetProcess.snippetComputationAllTime += resultEntry.snippetComputationTime;++ // place the result to the result vector+ // apply post-ranking+ long ranking = resultEntry.word() == null ? 0 : Long.valueOf(this.snippetProcess.searchEvent.rankingProcess.order.cardinal(resultEntry.word()));+ ranking += postRanking(resultEntry, this.snippetProcess.searchEvent.rankingProcess.getTopicNavigator(10));+ resultEntry.ranking = ranking;+ this.snippetProcess.result.put(new ReverseElement<ResultEntry>(resultEntry, ranking)); // remove smallest in case of overflow+ if (nav_topics) {+ this.snippetProcess.searchEvent.rankingProcess.addTopics(resultEntry);+ }+ }+ if (System.currentTimeMillis() >= this.timeout) {+ Log.logWarning("SnippetProcess", "worker ended with timeout");+ }+ //System.out.println("FINISHED WORKER " + id + " FOR " + this.neededResults + " RESULTS, loops = " + loops);+ } catch (final Exception e) { Log.logException(e); }+ //Log.logInfo("SEARCH", "resultWorker thread " + this.id + " terminated");+ }++ protected void pleaseStop() {+ this.shallrun = false;+ }++ /**+ * calculate the time since the worker has had the latest activity+ * @return time in milliseconds lasted since latest activity+ */+ public long busytime() {+ return System.currentTimeMillis() - this.lastLifeSign;+ }++ private long postRanking(+ final ResultEntry rentry,+ final ScoreMap<String> topwords) {++ long r = 0;++ // for media search: prefer pages with many links+ r += rentry.limage() << this.snippetProcess.query.ranking.coeff_cathasimage;+ r += rentry.laudio() << this.snippetProcess.query.ranking.coeff_cathasaudio;+ r += rentry.lvideo() << this.snippetProcess.query.ranking.coeff_cathasvideo;+ r += rentry.lapp() << this.snippetProcess.query.ranking.coeff_cathasapp;++ // apply citation count+ //System.out.println("POSTRANKING CITATION: references = " + rentry.referencesCount() + ", inbound = " + rentry.llocal() + ", outbound = " + rentry.lother());+ r += (128 * rentry.referencesCount() / (1 + 2 * rentry.llocal() + rentry.lother())) << this.snippetProcess.query.ranking.coeff_citation;++ // prefer hit with 'prefer' pattern+ if (this.snippetProcess.query.prefer.matcher(rentry.url().toNormalform(true)).matches()) {+ r += 256 << this.snippetProcess.query.ranking.coeff_prefer;+ }+ if (this.snippetProcess.query.prefer.matcher(rentry.title()).matches()) {+ r += 256 << this.snippetProcess.query.ranking.coeff_prefer;+ }++ // apply 'common-sense' heuristic using references+ final String urlstring = rentry.url().toNormalform(true);+ final String[] urlcomps = MultiProtocolURI.urlComps(urlstring);+ final String[] descrcomps = MultiProtocolURI.splitpattern.split(rentry.title().toLowerCase());+ int tc;+ for (final String urlcomp : urlcomps) {+ tc = topwords.get(urlcomp);+ if (tc > 0) {+ r += Math.max(1, tc) << this.snippetProcess.query.ranking.coeff_urlcompintoplist;+ }+ }+ for (final String descrcomp : descrcomps) {+ tc = topwords.get(descrcomp);+ if (tc > 0) {+ r += Math.max(1, tc) << this.snippetProcess.query.ranking.coeff_descrcompintoplist;+ }+ }++ // apply query-in-result matching+ final HandleSet urlcomph = Word.words2hashesHandles(urlcomps);+ final HandleSet descrcomph = Word.words2hashesHandles(descrcomps);+ final Iterator<byte[]> shi = this.snippetProcess.query.query_include_hashes.iterator();+ byte[] queryhash;+ while (shi.hasNext()) {+ queryhash = shi.next();+ if (urlcomph.has(queryhash)) {+ r += 256 << this.snippetProcess.query.ranking.coeff_appurl;+ }+ if (descrcomph.has(queryhash)) {+ r += 256 << this.snippetProcess.query.ranking.coeff_app_dc_title;+ }+ }++ return r;+ }++ private ResultEntry fetchSnippet(final URIMetadataNode page, final String solrText, final CacheStrategy cacheStrategy) {+ // Snippet Fetching can has 3 modes:+ // 0 - do not fetch snippets+ // 1 - fetch snippets offline only+ // 2 - online snippet fetch++ // load only urls if there was not yet a root url of that hash+ // find the url entry++ long startTime = System.currentTimeMillis();+ if (page == null) {+ return null;+ }+ final long dbRetrievalTime = System.currentTimeMillis() - startTime;++ if (cacheStrategy == null) {+ final TextSnippet snippet = new TextSnippet(+ null,+ solrText,+ page,+ this.snippetProcess.snippetFetchWordHashes,+ //this.query.queryString,+ null,+ ((this.snippetProcess.query.constraint != null) && (this.snippetProcess.query.constraint.get(Condenser.flag_cat_indexof))),+ SnippetProcess.SNIPPET_MAX_LENGTH,+ !this.snippetProcess.query.isLocal());+ return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, snippet, null, dbRetrievalTime, 0); // result without snippet+ }++ // load snippet+ if (page.url().getContentDomain() == Classification.ContentDomain.TEXT || page.url().getContentDomain() == Classification.ContentDomain.ALL) {+ // attach text snippet+ startTime = System.currentTimeMillis();+ final TextSnippet snippet = new TextSnippet(+ this.snippetProcess.loader,+ solrText,+ page,+ this.snippetProcess.snippetFetchWordHashes,+ cacheStrategy,+ ((this.snippetProcess.query.constraint != null) && (this.snippetProcess.query.constraint.get(Condenser.flag_cat_indexof))),+ 180,+ !this.snippetProcess.query.isLocal());+ final long snippetComputationTime = System.currentTimeMillis() - startTime;+ SnippetProcess.log.logInfo("text snippet load time for " + page.url() + ": " + snippetComputationTime + ", " + (!snippet.getErrorCode().fail() ? "snippet found" : ("no snippet found (" + snippet.getError() + ")")));++ if (!snippet.getErrorCode().fail()) {+ // we loaded the file and found the snippet+ return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, snippet, null, dbRetrievalTime, snippetComputationTime); // result with snippet attached+ } else if (cacheStrategy.mustBeOffline()) {+ // we did not demand online loading, therefore a failure does not mean that the missing snippet causes a rejection of this result+ // this may happen during a remote search, because snippet loading is omitted to retrieve results faster+ return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, null, null, dbRetrievalTime, snippetComputationTime); // result without snippet+ } else {+ // problems with snippet fetch+ if (this.snippetProcess.snippetFetchWordHashes.has(Segment.catchallHash)) {+ // we accept that because the word cannot be on the page+ return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, null, null, dbRetrievalTime, 0);+ }+ final String reason = "no text snippet; errorCode = " + snippet.getErrorCode();+ if (this.snippetProcess.deleteIfSnippetFail) {+ this.snippetProcess.workTables.failURLsRegisterMissingWord(this.snippetProcess.query.getSegment().termIndex(), page.url(), this.snippetProcess.query.query_include_hashes, reason);+ }+ SnippetProcess.log.logInfo("sorted out url " + page.url().toNormalform(true) + " during search: " + reason);+ return null;+ }+ }+ return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, null, null, dbRetrievalTime, 0); // result without snippet+ }+}