Skip to content

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

Merge branch 'master' of ssh://[email protected]/yacy/rc1.git

Michael Peter Christen14cceb6b17fd
diff --cc htroot/IndexFederated_p.html
index 3baaea700,f2b3f8eb8..778944774
--- a/htroot/IndexFederated_p.html
+++ b/htroot/IndexFederated_p.html
@@@ -64,8 -64,12 +64,12 @@@
<dt class="TableCellDark">Solr URL(s)</dt>
<dd><textarea rows="2" cols="80" name="solr.indexing.url" id="solr.indexing.url"/>#[solr.indexing.url]#</textarea><br/>
You can set one or more Solr targets here which are accessed as a shard. For several targets, list them using a ',' (comma) as separator.</dd>
++ <!-- will be moved here again...
+ <dt class="TableCellDark">Lazy Value Initialization</dt>
+ <dd><input type="checkbox" name="solr.indexing.lazy" id="solr.indexing.lazy" #(solr.indexing.lazy.checked)#:: checked="checked"#(/solr.indexing.lazy.checked)# /> (if checked, only non-zero values and non-empty strings are written)</dd>
++ -->
<dt class="TableCellDark">Sharding Method</dt>
<dd><input type="text" size="50" maxlength="50" value="#[solr.indexing.sharding]#" name="solr.indexing.sharding" id="solr.indexing.sharding" disabled="disabled"/></dd>
- <dt class="TableCellDark">Scheme</dt>
- <dd><input type="text" size="50" maxlength="50" value="#[solr.indexing.schemefile]#" name="solr.indexing.schemefile" id="solr.indexing.schemefile" disabled="disabled"/></dd>
<dt></dt><dd><input type="submit" name="set" value="Set" /></dd>
</dl>
</div>
diff --cc htroot/portalsearch/portalsearch-dev.js
index d5ff27736,d5ff27736..000000000
deleted file mode 100644,100644
--- a/htroot/portalsearch/portalsearch-dev.js
+++ /dev/null
@@@ -1,464 -1,464 +1,0 @@@
--/*
-- * YaCy Portalsearch
-- *
-- * @author Stefan Förster (apfelmaennchen) <[email protected]>
-- * @version 1.2
-- *
-- * Dual licensed under the MIT and GPL licenses:
-- * http://www.opensource.org/licenses/mit-license.php
-- * http://www.gnu.org/licenses/gpl.html
-- *
-- * Date: 10-Nov-2011
-- *
-- */
--
--function statuscheck() {
-- if(load_status < 5) {
-- return;
-- } else {
-- window.clearInterval(loading);
-- yrun();
-- }
--}
--
--$(document).ready(function() {
-- ynavigators = new Array();
-- $.ajaxSetup({
-- timeout: 5000,
-- cache: true
-- })
-- // apply default properties
-- ycurr = '';
-- startRecord = 0;
-- maximumRecords = 10;
-- submit = false;
-- yconf = $.extend({
-- url : '',
-- 'global' : false,
-- theme : 'start',
-- title : 'YaCy Search Widget',
-- logo : yconf.url + '/yacy/ui/img/yacy-logo.png',
-- link : 'http://yacy.net',
-- width : 640,
-- height : 640,
-- position : [150,50],
-- modal : false,
-- resizable: true,
-- show : '',
-- hide : '',
-- load_js : true,
-- load_css : true
-- }, yconf);
--
-- $('<div id="ypopup" class="classic"></div>').appendTo("#yacylivesearch");
--
-- if(yconf.load_css) {
-- var style1 = yconf.url + '/portalsearch/yacy-portalsearch.css';
-- var style2 = yconf.url + '/jquery/themes/'+yconf.theme+'/jquery-ui-1.8.16.custom.css';
-- var style3 = yconf.url + '/jquery/css/jquery-ui-combobox.css';
--
-- var head = document.getElementsByTagName('head')[0];
--
-- $(document.createElement('link'))
-- .attr({type:'text/css', href: style1, rel:'stylesheet', media:'screen'})
-- .appendTo(head);
-- $(document.createElement('link'))
-- .attr({type:'text/css', href: style2, rel:'stylesheet', media:'screen'})
-- .appendTo(head);
-- $(document.createElement('link'))
-- .attr({type:'text/css', href: style3, rel:'stylesheet', media:'screen'})
-- .appendTo(head);
-- }
--
-- load_status = 0;
-- loading = window.setInterval("statuscheck()", 200);
-- if(yconf.load_js) {
-- var script1 = yconf.url + '/jquery/js/jquery.query-2.1.7.js';
-- var script2 = yconf.url + '/jquery/js/jquery.form-2.73.js';
-- var script3 = yconf.url + '/jquery/js/jquery.field-0.9.2.min.js';
-- var script4 = yconf.url + '/jquery/js/jquery-ui-1.8.16.custom.min.js';
-- var script5 = yconf.url + '/jquery/js/jquery-ui-combobox.js';
--
-- $.getScript(script1, function(){ load_status++; });
-- $.getScript(script2, function(){ load_status++; });
-- $.getScript(script3, function(){ load_status++; });
-- $.getScript(script4, function(){ load_status++; });
-- $.getScript(script5, function(){ load_status++; });
-- } else {
-- yrun();
-- }
--});
--
--function yrun() {
-- maximumRecords = parseInt($("#ysearch input[name='maximumRecords']").getValue());
-- global = yconf.global;
--
-- $("#ypopup").dialog({
-- autoOpen: false,
-- height: yconf.height,
-- width: yconf.width,
-- minWidth: yconf.width,
-- position: yconf.position,
-- modal: yconf.modal,
-- resizable: yconf.resizable,
-- title: yconf.title,
-- show: yconf.show,
-- hide: yconf.hide,
-- drag: function(event, ui) {
-- var position = $("#ypopup").parent(".ui-dialog").position();
-- var left = $("#ypopup").parent(".ui-dialog").width()+5+position.left;
-- $("#yside").dialog('option', 'position', [left,position.top+32]);
-- },
-- dragStop: function(event, ui) {
-- var position = $("#ypopup").parent(".ui-dialog").position();
-- var left = $("#ypopup").parent(".ui-dialog").width()+5+position.left;
-- $("#yside").dialog('option', 'position', [left,position.top+32]);
-- },
-- resizeStop: function(event, ui) {
-- var position = $("#ypopup").parent(".ui-dialog").position();
-- var height = $("#ypopup").parent(".ui-dialog").height()-55;
-- var left = $("#ypopup").parent(".ui-dialog").width()+5+position.left;
-- $("#yside").dialog('option', 'height', height);
-- $("#yside").dialog('option', 'position', [left,position.top+32]);
-- },
-- close: function(event, ui) {
-- $("#yquery").setValue('');
-- $("#yside").dialog('destroy');
-- $('#yside').remove();
-- },
-- open: function(event, ui) {
-- $('<div id="yside" style="padding:0px;"></div>').insertAfter("#ypopup").parent(".ui-dialog-content");
-- var position = $("#ypopup").parent(".ui-dialog").position();
-- $("#yside").dialog({
-- title: 'Navigation',
-- autoOpen: false,
-- draggable: false,
-- resizable: false,
-- width: 220,
-- height: $("#ypopup").parent(".ui-dialog").height()-55,
-- minHeight: $("#ypopup").parent(".ui-dialog").height()-55,
-- show: 'slide',
-- hide: 'slide',
-- position : [position.left+$("#ypopup").parent(".ui-dialog").width()+5,position.top+32],
-- open: function(event, ui) {
-- $('div.ui-widget-shadow').remove();
-- $('#ypopup').dialog( 'moveToTop' );
-- }
-- });
-- $('.ui-widget-shadow').remove();
-- $('div[aria-labelledby="ui-dialog-title-yside"] div.ui-dialog-titlebar').remove();
--
-- $("#ypopup").bind("scroll", function(e){
-- p1 = $("#ypopup h3 :last").position().top;
-- if(p1-$("#ypopup").dialog( "option", "height" ) < 0) {
-- startRecord = startRecord + maximumRecords;
-- yacysearch(false);
-- }
-- });
--
--
-- }
-- });
--
-- $('#ysearch').keyup(function(e) { // React to keyboard input
--
-- if(e.which == 27) { // Close popup on ESC
-- $("#ypopup").dialog('close');
-- $("#yquery").setValue("");
-- }
--
-- if(e.which == 18) { // Global search on ALT
-- global = true;
-- ycurr = $("#yquery").getValue();
-- yacysearch(true);
-- }
--
-- if(ycurr == $("#yquery").getValue()) { // Do nothing if search term hasn't changed
-- return false;
-- }
--
-- global = yconf.global; // As this is a new search, revert to default resource
--
-- if ($("#yquery").getValue() == '') { // If search term is empty reset to default resource and close popup
-- if($("#ypopup").dialog('isOpen'))
-- $("#ypopup").dialog('close');
-- } else { // Else fire up a search request and remeber the current search term
-- ycurr = $("#yquery").getValue();
-- yacysearch(true);
-- }
-- return false;
-- });
--
-- $('#ysearch').submit(function() { // Submit a search request
-- ycurr = $("#yquery").getValue();
--
-- if (!$("#ypopup").dialog('isOpen'))
-- $("#ypopup").dialog('open');
-- else
-- if ($("#yside").dialog('isOpen'))
-- $("#yside").dialog('close');
--
-- $("#yquery").focus();
--
-- yacysearch(true);
-- return false;
-- });
--}
--
--function yacysearch(clear) {
-- var url = yconf.url + '/yacysearch.json?callback=?' // JSONP (cross domain) request URL
--
-- if(clear) {
-- $('#ypopup').empty();
-- var loading = "<div class='yloading'><h3 class='linktitle'><em>Loading: "+yconf.url+"</em><br/>";
-- var loadimg = "<img src='"+yconf.url+"/yacy/ui/img/loading2.gif' align='absmiddle'/></h3></div>";
-- $('#ypopup').append(loading+loadimg);
--
-- if (!$("#ypopup").dialog('isOpen'))
-- $("#ypopup").dialog('open');
-- else
-- if ($("#yside").dialog('isOpen'))
-- $("#yside").dialog('close');
--
-- $("#yquery").focus();
-- }
--
-- var param = []; // Generate search request parameters from HTML form
-- $("#ysearch input").each(function(i){
-- var item = { name : $(this).attr('name'), value : $(this).attr('value') };
-- if(item.name == 'resource') { // Set parameter for resource according to global
-- if(global)
-- item.value = 'global';
-- else {
-- item.value = 'local'
-- }
-- }
-- if(item.name == 'query' || item.name == 'search') {
-- item.value = $.trim(item.value); // remove heading and trailing white spaces from querey
-- if(item.value != ycurr) // in case of fast typing ycurr needs to be updated
-- ycurr = item.value;
-- }
-- param[i] = item;
-- });
-- param[param.length] = { name : 'startRecord', value : startRecord };
--
-- $.ajaxSetup({
-- timeout: 10000,
-- error: function(x,e) {
-- var err = 'Unknow Error: '+x.responseText;
-- if(x.status==0) {
-- err = 'Unknown Network Error! I try to reload...';
-- yacysearch(true);
-- } else if(x.status==404) {
-- err = x.status + ' - Requested URL not found.';
-- } else if(x.status==500) {
-- err = x.status + ' - Internel Server Error.';
-- } else if(e=='parsererror') {
-- err = 'Parsing JSON Request failed.';
-- } else if(e=='timeout') {
-- err = 'Request Time out.';
-- };
-- if (clear) $('#ypopup').empty();
-- var favicon = "<img src='"+yconf.url+"/yacy/ui/img-2/stop.png' class='favicon'/>";
-- var title = "<h3 class='linktitle'>"+favicon+" "+err+"</h3>";
-- var url = "<p class='url'><a href=''>Current search terms: "+ycurr+"</a></p>"
-- $(title+url).appendTo("#ypopup");
-- }
-- });
--
-- $.getJSON(url, param,
-- function(json, status) {
--
-- if (json[0]) data = json[0];
-- else data = json;
--
-- var searchTerms = "";
-- searchTerms = data.channels[0].searchTerms;
--
-- if($.trim(ycurr.replace(/ /g,"+")) != searchTerms) {
-- return false;
-- }
-- if(clear) {
-- $('#ypopup').empty();
-- }
--
-- var total = data.channels[0].totalResults;
--
-- if(global) var result = 'global';
-- else var result = 'local';
--
-- var count = 0;
-- $.each (
-- data.channels[0].items,
-- function(i,item) {
-- if (item) {
-- var favicon = "<img src='"+yconf.url+"/ViewImage.png?width=16&amp;height=16&amp;code="+item.faviconCode+"' class='favicon'/>";
-- var title = "<h3 class='linktitle'>"+favicon+"<a href='"+item.link+"' target='_blank'>"+item.title+"</a></h3>";
-- var url = "<p class='url'><a href='"+item.link+"' target='_blank'>"+item.link+"</a></p>"
-- var desc = "<p class='desc'>"+item.description+"</p>";
-- var date = "<p class='date'>"+item.pubDate.substring(0,16);
-- var size = " | "+item.sizename+"</p>";
-- $(title+desc+url+date+size).appendTo("#ypopup");
-- }
-- count++;
-- }
-- );
--
-- if(count == 0) {
-- if (clear) $('#ypopup').empty();
-- var favicon = "<img src='"+yconf.url+"/yacy/ui/img-2/stop.png' class='favicon'/>";
-- var title = "<h3 class='linktitle'>"+favicon+"No search results!</h3>";
-- var url = "<p class='url'><a href=''>Current search terms: "+searchTerms+"</a></p>"
-- var desc = "<p class='desc'>You could restate your search, release some navigators or switch to global search...</p>";
-- $(title+desc+url).appendTo("#ypopup");
-- }
--
-- if(clear) {
-- $('#yside').empty();
--
-- var ylogo = "<a href='"+yconf.link+"' target='_blank'><img style='padding-left: 24px;' src='"+yconf.logo+"' alt='"+yconf.logo+"' title='"+yconf.logo+"' /></a>";
-- var ymsg= "Total "+result+" results: "+total;
-- $("<div class='ymsg'><table><tr><td width='55px'>"+ylogo+"</td><td id='yresult'>"+ymsg+"</td></tr></div").appendTo('#yside');
-- $('<hr />').appendTo("#yside");
--
-- var selected = 'selected="selected">';
-- var select1 = '<select class="selector" id="yglobal"><option value="local"';
-- var select2 = 'local</option><option value="global"';
-- var select3 = 'global</option></select>';
--
-- if(global) {
-- select = select1 + '>' + select2 + selected + select3;
-- } else {
-- select = select1 + selected + select2 + '>' + select3;
-- }
--
-- $('<div class="ui-widget ynav"><label for="yglobal">Get local/global results:</label><br />'+select+'</div>').appendTo('#yside');
-- $("#yglobal").combobox({
-- selected: function(event, ui) {
-- if(ui.item.value == "global") {
-- global = true;
-- } else {
-- global = false;
-- }
-- yacysearch(true);
-- }
-- });
--
-- select1 = '<select class="selector" id="yrecent"><option value="relevance"';
-- select2 = 'Relevance</option><option value="date"';
-- select3 = 'Date</option></select>';
--
-- var query = unescape($("#yquery").getValue());
-- if(query.indexOf("/date") != -1) {
-- select = select1 + '>' + select2 + selected + select3;
-- } else {
-- select = select1 + selected + select2 + '>' + select3;
-- }
-- $('<div class="ui-widget ynav"><label for="yrecent">Sort result by:</label><br />'+select+'</div>').appendTo('#yside');
-- $("#yrecent").combobox({
-- selected: function(event, ui) {
-- if(ui.item.value == "date") {
-- query = query + " /date";
-- } else {
-- query = query.replace(/\s\/date/g,"");
-- }
-- $("#yquery").setValue($.trim(query));
-- $("#yquery").trigger('keyup');
-- }
-- });
--
-- $('<hr />').appendTo("#yside");
-- $("<p class='ytxt'>You can narrow down your search by selecting one of the below navigators:</p>").appendTo('#yside');
--
-- /*
-- var label = '<label for="ylang">Language:</label><br />';
-- var select = '<select class="selector" id="ylang"><option value="">Select one...</option><option value="en" >en-English</option><option value="fr" >fr-French</option><option value="es" >es-Spanish</option><option value="de" >de-German</option><option value="zh" >zh-Chinese</option></select>';
-- $('<div class="ui-widget ynav">'+label+select+'</div>').appendTo('#yside');
-- $("#ylang").combobox({
-- selected: function(event, ui) {
-- var query = unescape($("#yquery").getValue() + " /language/" +ui.item.value);
-- $("#yquery").setValue(query);
-- ynavigators.push("/language/"+ui.item.value);
-- $("#yquery").trigger('keyup');
-- }
-- });
-- */
--
-- $.each ( // Loop through all available navigators and include comboboxes in sidebar
-- data.channels[0].navigation,
-- function(i,facet) {
-- if (facet) {
-- var id = "#y"+facet.facetname;
-- var label = '<label for="y' +facet.facetname+ '">' +facet.displayname+ ': </label><br />';
-- var select = '<select id="y' +facet.facetname+ '"><option value="">Select one...</option></select>';
-- $('<div class="ui-widget ynav">'+label+select+'</div>').appendTo('#yside');
-- $.each (
-- facet.elements,
-- function(j,element) {
-- var mod = '<option value="'+element.modifier +'">'+element.name+ ' (' +element.count+ ')</option>';
-- $(mod).appendTo(id);
-- }
-- )
-- $(id).combobox({
-- selected: function(event, ui) {
-- var query = unescape($("#yquery").getValue() + " " +ui.item.value);
-- $("#yquery").setValue(query);
-- ynavigators.push(ui.item.value);
-- $("#yquery").trigger('submit');
-- }
-- });
-- }
-- }
-- );
--
-- $('<hr />').appendTo("#yside");
-- if(ynavigators.length > 0) {
-- $("<p class='ytxt'>Uncheck to release navigators:</p>").appendTo('#yside');
-- }
--
-- cancelNavigators(ynavigators, "#yside");
--
-- if($("#ypopup .yloading").length == 0) {
-- $(".ynav-cancel").bind("change", function(event) {
-- var query = $("#yquery").getValue();
-- var str = $(event.target).val();
-- var idx = ynavigators.indexOf($.trim(str));
-- if(idx!=-1) ynavigators.splice(idx, 1);
-- var regexp = new RegExp(' '+str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); // properly escape string for regexp
-- $("#yquery").setValue($.trim(query.replace(regexp,"")));
-- startRecord = 0;
-- $("#yquery").trigger('submit');
-- });
-- autoOpenSidebar();
-- if ($("#ypopup").dialog('isOpen')) {
-- // If you got maximumRecords results, but still have display space, load more results
-- if($("#ypopup h3 :last").position().top < $("#ypopup").dialog( "option", "height" ) && count == maximumRecords) {
-- startRecord = startRecord + maximumRecords;
-- yacysearch(false);
-- }
-- }
-- }
-- }
-- }
-- );
-- function autoOpenSidebar() {
-- window.setTimeout(function() { // The delay prevents the sidebar to open on every intermediate search results
-- if($("#ypopup .yloading").length == 0) { // Check again wether a search result is still loading
-- if( $("#yquery").getValue() == ycurr) { // Open side bar only if result matches current search term
-- $("#yside").dialog('open');
-- $("#yquery").focus();
-- }
-- }
-- } , 1000);
-- }
-- function cancelNavigators(ynavigators, appendTo) { // Include checkboxes to release navigators
-- var arLen=ynavigators.length;
-- var query = $("#yquery").getValue();
-- for ( var i=0, len=arLen; i<len; ++i ){
-- if(query.indexOf(ynavigators[i]) != -1) // Check wether search term still contains the navigator
-- $(' <input type="checkbox" checked="checked" class="ynav-cancel" name="ynav'+i+'" value="'+ynavigators[i]+'"><span class="ytxt">'+ynavigators[i]+'</span><br>').appendTo(appendTo);
-- else
-- ynavigators.splice(i, 1); // Remove navigator from array as it has been removed manually from search term
-- }
-- }
--}
diff --cc htroot/portalsearch/yacy-portalsearch.js
index cc6788f3c,cc6788f3c..d5ff27736
--- a/htroot/portalsearch/yacy-portalsearch.js
+++ b/htroot/portalsearch/yacy-portalsearch.js
@@@ -1,1 -1,1 +1,464 @@@
--function yacysearch(a){function g(a,b){var c=a.length;var d=$("#yquery").getValue();for(var e=0,f=c;e<f;++e){if(d.indexOf(a[e])!=-1)$(' <input type="checkbox" checked="checked" class="ynav-cancel" name="ynav'+e+'" value="'+a[e]+'"><span class="ytxt">'+a[e]+"</span><br>").appendTo(b);else a.splice(e,1)}}function f(){window.setTimeout(function(){if($("#ypopup .yloading").length==0){if($("#yquery").getValue()==ycurr){$("#yside").dialog("open");$("#yquery").focus()}}},1e3)}var b=yconf.url+"/yacysearch.json?callback=?";if(a){$("#ypopup").empty();var c="<div class='yloading'><h3 class='linktitle'><em>Loading: "+yconf.url+"</em><br/>";var d="<img src='"+yconf.url+"/yacy/ui/img/loading2.gif' align='absmiddle'/></h3></div>";$("#ypopup").append(c+d);if(!$("#ypopup").dialog("isOpen"))$("#ypopup").dialog("open");else if($("#yside").dialog("isOpen"))$("#yside").dialog("close");$("#yquery").focus()}var e=[];$("#ysearch input").each(function(a){var b={name:$(this).attr("name"),value:$(this).attr("value")};if(b.name=="resource"){if(global)b.value="global";else{b.value="local"}}if(b.name=="query"||b.name=="search"){b.value=$.trim(b.value);if(b.value!=ycurr)ycurr=b.value}e[a]=b});e[e.length]={name:"startRecord",value:startRecord};$.ajaxSetup({timeout:1e4,error:function(b,c){var d="Unknow Error: "+b.responseText;if(b.status==0){d="Unknown Network Error! I try to reload...";yacysearch(true)}else if(b.status==404){d=b.status+" - Requested URL not found."}else if(b.status==500){d=b.status+" - Internel Server Error."}else if(c=="parsererror"){d="Parsing JSON Request failed."}else if(c=="timeout"){d="Request Time out."}if(a)$("#ypopup").empty();var e="<img src='"+yconf.url+"/yacy/ui/img-2/stop.png' class='favicon'/>";var f="<h3 class='linktitle'>"+e+" "+d+"</h3>";var g="<p class='url'><a href=''>Current search terms: "+ycurr+"</a></p>";$(f+g).appendTo("#ypopup")}});$.getJSON(b,e,function(b,c){if(b[0])data=b[0];else data=b;var d="";d=data.channels[0].searchTerms;if($.trim(ycurr.replace(/ /g,"+"))!=d){return false}if(a){$("#ypopup").empty()}var e=data.channels[0].totalResults;if(global)var h="global";else var h="local";var i=0;$.each(data.channels[0].items,function(a,b){if(b){var c="<img src='"+yconf.url+"/ViewImage.png?width=16&height=16&code="+b.faviconCode+"' class='favicon'/>";var d="<h3 class='linktitle'>"+c+"<a href='"+b.link+"' target='_blank'>"+b.title+"</a></h3>";var e="<p class='url'><a href='"+b.link+"' target='_blank'>"+b.link+"</a></p>";var f="<p class='desc'>"+b.description+"</p>";var g="<p class='date'>"+b.pubDate.substring(0,16);var h=" | "+b.sizename+"</p>";$(d+f+e+g+h).appendTo("#ypopup")}i++});if(i==0){if(a)$("#ypopup").empty();var j="<img src='"+yconf.url+"/yacy/ui/img-2/stop.png' class='favicon'/>";var k="<h3 class='linktitle'>"+j+"No search results!</h3>";var l="<p class='url'><a href=''>Current search terms: "+d+"</a></p>";var m="<p class='desc'>You could restate your search, release some navigators or switch to global search...</p>";$(k+m+l).appendTo("#ypopup")}if(a){$("#yside").empty();var n="<a href='"+yconf.link+"' target='_blank'><img style='padding-left: 24px;' src='"+yconf.logo+"' alt='"+yconf.logo+"' title='"+yconf.logo+"' /></a>";var o="Total "+h+" results: "+e;$("<div class='ymsg'><table><tr><td width='55px'>"+n+"</td><td id='yresult'>"+o+"</td></tr></div").appendTo("#yside");$("<hr />").appendTo("#yside");var p='selected="selected">';var q='<select class="selector" id="yglobal"><option value="local"';var r='local</option><option value="global"';var s="global</option></select>";if(global){select=q+">"+r+p+s}else{select=q+p+r+">"+s}$('<div class="ui-widget ynav"><label for="yglobal">Get local/global results:</label><br />'+select+"</div>").appendTo("#yside");$("#yglobal").combobox({selected:function(a,b){if(b.item.value=="global"){global=true}else{global=false}yacysearch(true)}});q='<select class="selector" id="yrecent"><option value="relevance"';r='Relevance</option><option value="date"';s="Date</option></select>";var t=unescape($("#yquery").getValue());if(t.indexOf("/date")!=-1){select=q+">"+r+p+s}else{select=q+p+r+">"+s}$('<div class="ui-widget ynav"><label for="yrecent">Sort result by:</label><br />'+select+"</div>").appendTo("#yside");$("#yrecent").combobox({selected:function(a,b){if(b.item.value=="date"){t=t+" /date"}else{t=t.replace(/\s\/date/g,"")}$("#yquery").setValue($.trim(t));$("#yquery").trigger("keyup")}});$("<hr />").appendTo("#yside");$("<p class='ytxt'>You can narrow down your search by selecting one of the below navigators:</p>").appendTo("#yside");$.each(data.channels[0].navigation,function(a,b){if(b){var c="#y"+b.facetname;var d='<label for="y'+b.facetname+'">'+b.displayname+": </label><br />";var e='<select id="y'+b.facetname+'"><option value="">Select one...</option></select>';$('<div class="ui-widget ynav">'+d+e+"</div>").appendTo("#yside");$.each(b.elements,function(a,b){var d='<option value="'+b.modifier+'">'+b.name+" ("+b.count+")</option>";$(d).appendTo(c)});$(c).combobox({selected:function(a,b){var c=unescape($("#yquery").getValue()+" "+b.item.value);$("#yquery").setValue(c);ynavigators.push(b.item.value);$("#yquery").trigger("submit")}})}});$("<hr />").appendTo("#yside");if(ynavigators.length>0){$("<p class='ytxt'>Uncheck to release navigators:</p>").appendTo("#yside")}g(ynavigators,"#yside");if($("#ypopup .yloading").length==0){$(".ynav-cancel").bind("change",function(a){var b=$("#yquery").getValue();var c=$(a.target).val();var d=ynavigators.indexOf($.trim(c));if(d!=-1)ynavigators.splice(d,1);var e=new RegExp(" "+c.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"));$("#yquery").setValue($.trim(b.replace(e,"")));startRecord=0;$("#yquery").trigger("submit")});f();if($("#ypopup").dialog("isOpen")){if($("#ypopup h3 :last").position().top<$("#ypopup").dialog("option","height")&&i==maximumRecords){startRecord=startRecord+maximumRecords;yacysearch(false)}}}}})}function yrun(){maximumRecords=parseInt($("#ysearch input[name='maximumRecords']").getValue());global=yconf.global;$("#ypopup").dialog({autoOpen:false,height:yconf.height,width:yconf.width,minWidth:yconf.width,position:yconf.position,modal:yconf.modal,resizable:yconf.resizable,title:yconf.title,show:yconf.show,hide:yconf.hide,drag:function(a,b){var c=$("#ypopup").parent(".ui-dialog").position();var d=$("#ypopup").parent(".ui-dialog").width()+5+c.left;$("#yside").dialog("option","position",[d,c.top+32])},dragStop:function(a,b){var c=$("#ypopup").parent(".ui-dialog").position();var d=$("#ypopup").parent(".ui-dialog").width()+5+c.left;$("#yside").dialog("option","position",[d,c.top+32])},resizeStop:function(a,b){var c=$("#ypopup").parent(".ui-dialog").position();var d=$("#ypopup").parent(".ui-dialog").height()-55;var e=$("#ypopup").parent(".ui-dialog").width()+5+c.left;$("#yside").dialog("option","height",d);$("#yside").dialog("option","position",[e,c.top+32])},close:function(a,b){$("#yquery").setValue("");$("#yside").dialog("destroy");$("#yside").remove()},open:function(a,b){$('<div id="yside" style="padding:0px;"></div>').insertAfter("#ypopup").parent(".ui-dialog-content");var c=$("#ypopup").parent(".ui-dialog").position();$("#yside").dialog({title:"Navigation",autoOpen:false,draggable:false,resizable:false,width:220,height:$("#ypopup").parent(".ui-dialog").height()-55,minHeight:$("#ypopup").parent(".ui-dialog").height()-55,show:"slide",hide:"slide",position:[c.left+$("#ypopup").parent(".ui-dialog").width()+5,c.top+32],open:function(a,b){$("div.ui-widget-shadow").remove();$("#ypopup").dialog("moveToTop")}});$(".ui-widget-shadow").remove();$('div[aria-labelledby="ui-dialog-title-yside"] div.ui-dialog-titlebar').remove();$("#ypopup").bind("scroll",function(a){p1=$("#ypopup h3 :last").position().top;if(p1-$("#ypopup").dialog("option","height")<0){startRecord=startRecord+maximumRecords;yacysearch(false)}})}});$("#ysearch").keyup(function(a){if(a.which==27){$("#ypopup").dialog("close");$("#yquery").setValue("")}if(a.which==18){global=true;ycurr=$("#yquery").getValue();yacysearch(true)}if(ycurr==$("#yquery").getValue()){return false}global=yconf.global;if($("#yquery").getValue()==""){if($("#ypopup").dialog("isOpen"))$("#ypopup").dialog("close")}else{ycurr=$("#yquery").getValue();yacysearch(true)}return false});$("#ysearch").submit(function(){ycurr=$("#yquery").getValue();if(!$("#ypopup").dialog("isOpen"))$("#ypopup").dialog("open");else if($("#yside").dialog("isOpen"))$("#yside").dialog("close");$("#yquery").focus();yacysearch(true);return false})}function statuscheck(){if(load_status<5){return}else{window.clearInterval(loading);yrun()}}$(document).ready(function(){ynavigators=new Array;$.ajaxSetup({timeout:5e3,cache:true});ycurr="";startRecord=0;maximumRecords=10;submit=false;yconf=$.extend({url:"",global:false,theme:"start",title:"YaCy Search Widget",logo:yconf.url+"/yacy/ui/img/yacy-logo.png",link:"http://yacy.net",width:640,height:640,position:[150,50],modal:false,resizable:true,show:"",hide:"",load_js:true,load_css:true},yconf);$('<div id="ypopup" class="classic"></div>').appendTo("#yacylivesearch");if(yconf.load_css){var a=yconf.url+"/portalsearch/yacy-portalsearch.css";var b=yconf.url+"/jquery/themes/"+yconf.theme+"/jquery-ui-1.8.16.custom.css";var c=yconf.url+"/jquery/css/jquery-ui-combobox.css";var d=document.getElementsByTagName("head")[0];$(document.createElement("link")).attr({type:"text/css",href:a,rel:"stylesheet",media:"screen"}).appendTo(d);$(document.createElement("link")).attr({type:"text/css",href:b,rel:"stylesheet",media:"screen"}).appendTo(d);$(document.createElement("link")).attr({type:"text/css",href:c,rel:"stylesheet",media:"screen"}).appendTo(d)}load_status=0;loading=window.setInterval("statuscheck()",200);if(yconf.load_js){var e=yconf.url+"/jquery/js/jquery.query-2.1.7.js";var f=yconf.url+"/jquery/js/jquery.form-2.73.js";var g=yconf.url+"/jquery/js/jquery.field-0.9.2.min.js";var h=yconf.url+"/jquery/js/jquery-ui-1.8.16.custom.min.js";var i=yconf.url+"/jquery/js/jquery-ui-combobox.js";$.getScript(e,function(){load_status++});$.getScript(f,function(){load_status++});$.getScript(g,function(){load_status++});$.getScript(h,function(){load_status++});$.getScript(i,function(){load_status++})}else{yrun()}})
++/*
++ * YaCy Portalsearch
++ *
++ * @author Stefan Förster (apfelmaennchen) <[email protected]>
++ * @version 1.2
++ *
++ * Dual licensed under the MIT and GPL licenses:
++ * http://www.opensource.org/licenses/mit-license.php
++ * http://www.gnu.org/licenses/gpl.html
++ *
++ * Date: 10-Nov-2011
++ *
++ */
++
++function statuscheck() {
++ if(load_status < 5) {
++ return;
++ } else {
++ window.clearInterval(loading);
++ yrun();
++ }
++}
++
++$(document).ready(function() {
++ ynavigators = new Array();
++ $.ajaxSetup({
++ timeout: 5000,
++ cache: true
++ })
++ // apply default properties
++ ycurr = '';
++ startRecord = 0;
++ maximumRecords = 10;
++ submit = false;
++ yconf = $.extend({
++ url : '',
++ 'global' : false,
++ theme : 'start',
++ title : 'YaCy Search Widget',
++ logo : yconf.url + '/yacy/ui/img/yacy-logo.png',
++ link : 'http://yacy.net',
++ width : 640,
++ height : 640,
++ position : [150,50],
++ modal : false,
++ resizable: true,
++ show : '',
++ hide : '',
++ load_js : true,
++ load_css : true
++ }, yconf);
++
++ $('<div id="ypopup" class="classic"></div>').appendTo("#yacylivesearch");
++
++ if(yconf.load_css) {
++ var style1 = yconf.url + '/portalsearch/yacy-portalsearch.css';
++ var style2 = yconf.url + '/jquery/themes/'+yconf.theme+'/jquery-ui-1.8.16.custom.css';
++ var style3 = yconf.url + '/jquery/css/jquery-ui-combobox.css';
++
++ var head = document.getElementsByTagName('head')[0];
++
++ $(document.createElement('link'))
++ .attr({type:'text/css', href: style1, rel:'stylesheet', media:'screen'})
++ .appendTo(head);
++ $(document.createElement('link'))
++ .attr({type:'text/css', href: style2, rel:'stylesheet', media:'screen'})
++ .appendTo(head);
++ $(document.createElement('link'))
++ .attr({type:'text/css', href: style3, rel:'stylesheet', media:'screen'})
++ .appendTo(head);
++ }
++
++ load_status = 0;
++ loading = window.setInterval("statuscheck()", 200);
++ if(yconf.load_js) {
++ var script1 = yconf.url + '/jquery/js/jquery.query-2.1.7.js';
++ var script2 = yconf.url + '/jquery/js/jquery.form-2.73.js';
++ var script3 = yconf.url + '/jquery/js/jquery.field-0.9.2.min.js';
++ var script4 = yconf.url + '/jquery/js/jquery-ui-1.8.16.custom.min.js';
++ var script5 = yconf.url + '/jquery/js/jquery-ui-combobox.js';
++
++ $.getScript(script1, function(){ load_status++; });
++ $.getScript(script2, function(){ load_status++; });
++ $.getScript(script3, function(){ load_status++; });
++ $.getScript(script4, function(){ load_status++; });
++ $.getScript(script5, function(){ load_status++; });
++ } else {
++ yrun();
++ }
++});
++
++function yrun() {
++ maximumRecords = parseInt($("#ysearch input[name='maximumRecords']").getValue());
++ global = yconf.global;
++
++ $("#ypopup").dialog({
++ autoOpen: false,
++ height: yconf.height,
++ width: yconf.width,
++ minWidth: yconf.width,
++ position: yconf.position,
++ modal: yconf.modal,
++ resizable: yconf.resizable,
++ title: yconf.title,
++ show: yconf.show,
++ hide: yconf.hide,
++ drag: function(event, ui) {
++ var position = $("#ypopup").parent(".ui-dialog").position();
++ var left = $("#ypopup").parent(".ui-dialog").width()+5+position.left;
++ $("#yside").dialog('option', 'position', [left,position.top+32]);
++ },
++ dragStop: function(event, ui) {
++ var position = $("#ypopup").parent(".ui-dialog").position();
++ var left = $("#ypopup").parent(".ui-dialog").width()+5+position.left;
++ $("#yside").dialog('option', 'position', [left,position.top+32]);
++ },
++ resizeStop: function(event, ui) {
++ var position = $("#ypopup").parent(".ui-dialog").position();
++ var height = $("#ypopup").parent(".ui-dialog").height()-55;
++ var left = $("#ypopup").parent(".ui-dialog").width()+5+position.left;
++ $("#yside").dialog('option', 'height', height);
++ $("#yside").dialog('option', 'position', [left,position.top+32]);
++ },
++ close: function(event, ui) {
++ $("#yquery").setValue('');
++ $("#yside").dialog('destroy');
++ $('#yside').remove();
++ },
++ open: function(event, ui) {
++ $('<div id="yside" style="padding:0px;"></div>').insertAfter("#ypopup").parent(".ui-dialog-content");
++ var position = $("#ypopup").parent(".ui-dialog").position();
++ $("#yside").dialog({
++ title: 'Navigation',
++ autoOpen: false,
++ draggable: false,
++ resizable: false,
++ width: 220,
++ height: $("#ypopup").parent(".ui-dialog").height()-55,
++ minHeight: $("#ypopup").parent(".ui-dialog").height()-55,
++ show: 'slide',
++ hide: 'slide',
++ position : [position.left+$("#ypopup").parent(".ui-dialog").width()+5,position.top+32],
++ open: function(event, ui) {
++ $('div.ui-widget-shadow').remove();
++ $('#ypopup').dialog( 'moveToTop' );
++ }
++ });
++ $('.ui-widget-shadow').remove();
++ $('div[aria-labelledby="ui-dialog-title-yside"] div.ui-dialog-titlebar').remove();
++
++ $("#ypopup").bind("scroll", function(e){
++ p1 = $("#ypopup h3 :last").position().top;
++ if(p1-$("#ypopup").dialog( "option", "height" ) < 0) {
++ startRecord = startRecord + maximumRecords;
++ yacysearch(false);
++ }
++ });
++
++
++ }
++ });
++
++ $('#ysearch').keyup(function(e) { // React to keyboard input
++
++ if(e.which == 27) { // Close popup on ESC
++ $("#ypopup").dialog('close');
++ $("#yquery").setValue("");
++ }
++
++ if(e.which == 18) { // Global search on ALT
++ global = true;
++ ycurr = $("#yquery").getValue();
++ yacysearch(true);
++ }
++
++ if(ycurr == $("#yquery").getValue()) { // Do nothing if search term hasn't changed
++ return false;
++ }
++
++ global = yconf.global; // As this is a new search, revert to default resource
++
++ if ($("#yquery").getValue() == '') { // If search term is empty reset to default resource and close popup
++ if($("#ypopup").dialog('isOpen'))
++ $("#ypopup").dialog('close');
++ } else { // Else fire up a search request and remeber the current search term
++ ycurr = $("#yquery").getValue();
++ yacysearch(true);
++ }
++ return false;
++ });
++
++ $('#ysearch').submit(function() { // Submit a search request
++ ycurr = $("#yquery").getValue();
++
++ if (!$("#ypopup").dialog('isOpen'))
++ $("#ypopup").dialog('open');
++ else
++ if ($("#yside").dialog('isOpen'))
++ $("#yside").dialog('close');
++
++ $("#yquery").focus();
++
++ yacysearch(true);
++ return false;
++ });
++}
++
++function yacysearch(clear) {
++ var url = yconf.url + '/yacysearch.json?callback=?' // JSONP (cross domain) request URL
++
++ if(clear) {
++ $('#ypopup').empty();
++ var loading = "<div class='yloading'><h3 class='linktitle'><em>Loading: "+yconf.url+"</em><br/>";
++ var loadimg = "<img src='"+yconf.url+"/yacy/ui/img/loading2.gif' align='absmiddle'/></h3></div>";
++ $('#ypopup').append(loading+loadimg);
++
++ if (!$("#ypopup").dialog('isOpen'))
++ $("#ypopup").dialog('open');
++ else
++ if ($("#yside").dialog('isOpen'))
++ $("#yside").dialog('close');
++
++ $("#yquery").focus();
++ }
++
++ var param = []; // Generate search request parameters from HTML form
++ $("#ysearch input").each(function(i){
++ var item = { name : $(this).attr('name'), value : $(this).attr('value') };
++ if(item.name == 'resource') { // Set parameter for resource according to global
++ if(global)
++ item.value = 'global';
++ else {
++ item.value = 'local'
++ }
++ }
++ if(item.name == 'query' || item.name == 'search') {
++ item.value = $.trim(item.value); // remove heading and trailing white spaces from querey
++ if(item.value != ycurr) // in case of fast typing ycurr needs to be updated
++ ycurr = item.value;
++ }
++ param[i] = item;
++ });
++ param[param.length] = { name : 'startRecord', value : startRecord };
++
++ $.ajaxSetup({
++ timeout: 10000,
++ error: function(x,e) {
++ var err = 'Unknow Error: '+x.responseText;
++ if(x.status==0) {
++ err = 'Unknown Network Error! I try to reload...';
++ yacysearch(true);
++ } else if(x.status==404) {
++ err = x.status + ' - Requested URL not found.';
++ } else if(x.status==500) {
++ err = x.status + ' - Internel Server Error.';
++ } else if(e=='parsererror') {
++ err = 'Parsing JSON Request failed.';
++ } else if(e=='timeout') {
++ err = 'Request Time out.';
++ };
++ if (clear) $('#ypopup').empty();
++ var favicon = "<img src='"+yconf.url+"/yacy/ui/img-2/stop.png' class='favicon'/>";
++ var title = "<h3 class='linktitle'>"+favicon+" "+err+"</h3>";
++ var url = "<p class='url'><a href=''>Current search terms: "+ycurr+"</a></p>"
++ $(title+url).appendTo("#ypopup");
++ }
++ });
++
++ $.getJSON(url, param,
++ function(json, status) {
++
++ if (json[0]) data = json[0];
++ else data = json;
++
++ var searchTerms = "";
++ searchTerms = data.channels[0].searchTerms;
++
++ if($.trim(ycurr.replace(/ /g,"+")) != searchTerms) {
++ return false;
++ }
++ if(clear) {
++ $('#ypopup').empty();
++ }
++
++ var total = data.channels[0].totalResults;
++
++ if(global) var result = 'global';
++ else var result = 'local';
++
++ var count = 0;
++ $.each (
++ data.channels[0].items,
++ function(i,item) {
++ if (item) {
++ var favicon = "<img src='"+yconf.url+"/ViewImage.png?width=16&amp;height=16&amp;code="+item.faviconCode+"' class='favicon'/>";
++ var title = "<h3 class='linktitle'>"+favicon+"<a href='"+item.link+"' target='_blank'>"+item.title+"</a></h3>";
++ var url = "<p class='url'><a href='"+item.link+"' target='_blank'>"+item.link+"</a></p>"
++ var desc = "<p class='desc'>"+item.description+"</p>";
++ var date = "<p class='date'>"+item.pubDate.substring(0,16);
++ var size = " | "+item.sizename+"</p>";
++ $(title+desc+url+date+size).appendTo("#ypopup");
++ }
++ count++;
++ }
++ );
++
++ if(count == 0) {
++ if (clear) $('#ypopup').empty();
++ var favicon = "<img src='"+yconf.url+"/yacy/ui/img-2/stop.png' class='favicon'/>";
++ var title = "<h3 class='linktitle'>"+favicon+"No search results!</h3>";
++ var url = "<p class='url'><a href=''>Current search terms: "+searchTerms+"</a></p>"
++ var desc = "<p class='desc'>You could restate your search, release some navigators or switch to global search...</p>";
++ $(title+desc+url).appendTo("#ypopup");
++ }
++
++ if(clear) {
++ $('#yside').empty();
++
++ var ylogo = "<a href='"+yconf.link+"' target='_blank'><img style='padding-left: 24px;' src='"+yconf.logo+"' alt='"+yconf.logo+"' title='"+yconf.logo+"' /></a>";
++ var ymsg= "Total "+result+" results: "+total;
++ $("<div class='ymsg'><table><tr><td width='55px'>"+ylogo+"</td><td id='yresult'>"+ymsg+"</td></tr></div").appendTo('#yside');
++ $('<hr />').appendTo("#yside");
++
++ var selected = 'selected="selected">';
++ var select1 = '<select class="selector" id="yglobal"><option value="local"';
++ var select2 = 'local</option><option value="global"';
++ var select3 = 'global</option></select>';
++
++ if(global) {
++ select = select1 + '>' + select2 + selected + select3;
++ } else {
++ select = select1 + selected + select2 + '>' + select3;
++ }
++
++ $('<div class="ui-widget ynav"><label for="yglobal">Get local/global results:</label><br />'+select+'</div>').appendTo('#yside');
++ $("#yglobal").combobox({
++ selected: function(event, ui) {
++ if(ui.item.value == "global") {
++ global = true;
++ } else {
++ global = false;
++ }
++ yacysearch(true);
++ }
++ });
++
++ select1 = '<select class="selector" id="yrecent"><option value="relevance"';
++ select2 = 'Relevance</option><option value="date"';
++ select3 = 'Date</option></select>';
++
++ var query = unescape($("#yquery").getValue());
++ if(query.indexOf("/date") != -1) {
++ select = select1 + '>' + select2 + selected + select3;
++ } else {
++ select = select1 + selected + select2 + '>' + select3;
++ }
++ $('<div class="ui-widget ynav"><label for="yrecent">Sort result by:</label><br />'+select+'</div>').appendTo('#yside');
++ $("#yrecent").combobox({
++ selected: function(event, ui) {
++ if(ui.item.value == "date") {
++ query = query + " /date";
++ } else {
++ query = query.replace(/\s\/date/g,"");
++ }
++ $("#yquery").setValue($.trim(query));
++ $("#yquery").trigger('keyup');
++ }
++ });
++
++ $('<hr />').appendTo("#yside");
++ $("<p class='ytxt'>You can narrow down your search by selecting one of the below navigators:</p>").appendTo('#yside');
++
++ /*
++ var label = '<label for="ylang">Language:</label><br />';
++ var select = '<select class="selector" id="ylang"><option value="">Select one...</option><option value="en" >en-English</option><option value="fr" >fr-French</option><option value="es" >es-Spanish</option><option value="de" >de-German</option><option value="zh" >zh-Chinese</option></select>';
++ $('<div class="ui-widget ynav">'+label+select+'</div>').appendTo('#yside');
++ $("#ylang").combobox({
++ selected: function(event, ui) {
++ var query = unescape($("#yquery").getValue() + " /language/" +ui.item.value);
++ $("#yquery").setValue(query);
++ ynavigators.push("/language/"+ui.item.value);
++ $("#yquery").trigger('keyup');
++ }
++ });
++ */
++
++ $.each ( // Loop through all available navigators and include comboboxes in sidebar
++ data.channels[0].navigation,
++ function(i,facet) {
++ if (facet) {
++ var id = "#y"+facet.facetname;
++ var label = '<label for="y' +facet.facetname+ '">' +facet.displayname+ ': </label><br />';
++ var select = '<select id="y' +facet.facetname+ '"><option value="">Select one...</option></select>';
++ $('<div class="ui-widget ynav">'+label+select+'</div>').appendTo('#yside');
++ $.each (
++ facet.elements,
++ function(j,element) {
++ var mod = '<option value="'+element.modifier +'">'+element.name+ ' (' +element.count+ ')</option>';
++ $(mod).appendTo(id);
++ }
++ )
++ $(id).combobox({
++ selected: function(event, ui) {
++ var query = unescape($("#yquery").getValue() + " " +ui.item.value);
++ $("#yquery").setValue(query);
++ ynavigators.push(ui.item.value);
++ $("#yquery").trigger('submit');
++ }
++ });
++ }
++ }
++ );
++
++ $('<hr />').appendTo("#yside");
++ if(ynavigators.length > 0) {
++ $("<p class='ytxt'>Uncheck to release navigators:</p>").appendTo('#yside');
++ }
++
++ cancelNavigators(ynavigators, "#yside");
++
++ if($("#ypopup .yloading").length == 0) {
++ $(".ynav-cancel").bind("change", function(event) {
++ var query = $("#yquery").getValue();
++ var str = $(event.target).val();
++ var idx = ynavigators.indexOf($.trim(str));
++ if(idx!=-1) ynavigators.splice(idx, 1);
++ var regexp = new RegExp(' '+str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); // properly escape string for regexp
++ $("#yquery").setValue($.trim(query.replace(regexp,"")));
++ startRecord = 0;
++ $("#yquery").trigger('submit');
++ });
++ autoOpenSidebar();
++ if ($("#ypopup").dialog('isOpen')) {
++ // If you got maximumRecords results, but still have display space, load more results
++ if($("#ypopup h3 :last").position().top < $("#ypopup").dialog( "option", "height" ) && count == maximumRecords) {
++ startRecord = startRecord + maximumRecords;
++ yacysearch(false);
++ }
++ }
++ }
++ }
++ }
++ );
++ function autoOpenSidebar() {
++ window.setTimeout(function() { // The delay prevents the sidebar to open on every intermediate search results
++ if($("#ypopup .yloading").length == 0) { // Check again wether a search result is still loading
++ if( $("#yquery").getValue() == ycurr) { // Open side bar only if result matches current search term
++ $("#yside").dialog('open');
++ $("#yquery").focus();
++ }
++ }
++ } , 1000);
++ }
++ function cancelNavigators(ynavigators, appendTo) { // Include checkboxes to release navigators
++ var arLen=ynavigators.length;
++ var query = $("#yquery").getValue();
++ for ( var i=0, len=arLen; i<len; ++i ){
++ if(query.indexOf(ynavigators[i]) != -1) // Check wether search term still contains the navigator
++ $(' <input type="checkbox" checked="checked" class="ynav-cancel" name="ynav'+i+'" value="'+ynavigators[i]+'"><span class="ytxt">'+ynavigators[i]+'</span><br>').appendTo(appendTo);
++ else
++ ynavigators.splice(i, 1); // Remove navigator from array as it has been removed manually from search term
++ }
++ }
++}
diff --cc source/net/yacy/peers/Protocol.java
index 8660091e9,3bb532b54..2352c110b
--- a/source/net/yacy/peers/Protocol.java
+++ b/source/net/yacy/peers/Protocol.java
@@@ -1,1736 -1,1733 +1,1736 @@@
-// yacyClient.java
-// -------------------------------------
-// (C) by Michael Peter Christen; [email protected]
-// first published on http://www.anomic.de
-// Frankfurt, Germany, 2004
-//
-// $LastChangedDate$
-// $LastChangedRevision$
-// $LastChangedBy$
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// Using this software in any meaning (reading, learning, copying, compiling,
-// running) means that you agree that the Author(s) is (are) not responsible
-// for cost, loss of data or any harm that may be caused directly or indirectly
-// by usage of this softare or this documentation. The usage of this software
-// is on your own risk. The installation and usage (starting/running) of this
-// software may allow other people or application to access your computer and
-// any attached devices and is highly dependent on the configuration of the
-// software which must be done by the user of the software; the author(s) is
-// (are) also not responsible for proper configuration and usage of the
-// software, even if provoked by documentation provided together with
-// the software.
-//
-// Any changes to this file according to the GPL as documented in the file
-// gpl.txt aside this file in the shipment you received can be done to the
-// lines that follows this copyright notice here, but changes must not be
-// done inside the copyright notice above. A re-distribution must contain
-// the intact and unchanged copyright notice.
-// Contributions and changes to the program code must be marked as such.
-
-package net.yacy.peers;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import net.yacy.migration;
-import net.yacy.cora.date.GenericFormatter;
-import net.yacy.cora.document.ASCII;
-import net.yacy.cora.document.JSONArray;
-import net.yacy.cora.document.JSONException;
-import net.yacy.cora.document.JSONObject;
-import net.yacy.cora.document.JSONTokener;
-import net.yacy.cora.document.MultiProtocolURI;
-import net.yacy.cora.document.RSSFeed;
-import net.yacy.cora.document.RSSMessage;
-import net.yacy.cora.document.RSSReader;
-import net.yacy.cora.document.UTF8;
-import net.yacy.cora.federate.opensearch.SRURSSConnector;
-import net.yacy.cora.federate.solr.YaCySchema;
-import net.yacy.cora.federate.solr.connector.RemoteSolrConnector;
-import net.yacy.cora.federate.solr.connector.SolrConnector;
-import net.yacy.cora.federate.yacy.CacheStrategy;
-import net.yacy.cora.order.Base64Order;
-import net.yacy.cora.order.Digest;
-import net.yacy.cora.protocol.ClientIdentification;
-import net.yacy.cora.protocol.Domains;
-import net.yacy.cora.protocol.http.HTTPClient;
-import net.yacy.cora.sorting.ClusteredScoreMap;
-import net.yacy.cora.sorting.ReversibleScoreMap;
-import net.yacy.cora.storage.HandleSet;
-import net.yacy.cora.util.SpaceExceededException;
-import net.yacy.crawler.data.ResultURLs;
-import net.yacy.crawler.data.ResultURLs.EventOrigin;
-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.WordReferenceFactory;
-import net.yacy.kelondro.logging.Log;
-import net.yacy.kelondro.rwi.Reference;
-import net.yacy.kelondro.rwi.ReferenceContainer;
-import net.yacy.kelondro.rwi.ReferenceContainerCache;
-import net.yacy.kelondro.util.ByteBuffer;
-import net.yacy.kelondro.util.FileUtils;
-import net.yacy.peers.graphics.ProfilingGraph;
-import net.yacy.peers.graphics.WebStructureGraph;
-import net.yacy.peers.graphics.WebStructureGraph.HostReference;
-import net.yacy.peers.operation.yacyVersion;
-import net.yacy.repository.Blacklist;
-import net.yacy.repository.Blacklist.BlacklistType;
-import net.yacy.search.EventTracker;
-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;
-import net.yacy.server.serverSwitch;
-import net.yacy.utils.crypt;
-
-import org.apache.http.entity.mime.content.ContentBody;
-import org.apache.solr.client.solrj.SolrQuery;
-import org.apache.solr.client.solrj.response.FacetField;
-import org.apache.solr.client.solrj.response.QueryResponse;
-import org.apache.solr.client.solrj.response.FacetField.Count;
-import org.apache.solr.common.SolrDocument;
-import org.apache.solr.common.SolrDocumentList;
-import org.apache.solr.common.params.FacetParams;
-
-
-public final class Protocol {
-
- private static byte[] postToFile(
- final Seed target,
- final String filename,
- final Map<String, ContentBody> parts,
- final int timeout) throws IOException {
- return postToFile(target.getClusterAddress(), target.hash, filename, parts, timeout);
- }
-
- private static byte[] postToFile(
- final SeedDB seedDB,
- final String targetHash,
- final String filename,
- final Map<String, ContentBody> parts,
- final int timeout) throws IOException {
- return postToFile(seedDB.targetAddress(targetHash), targetHash, filename, parts, timeout);
- }
-
- private static byte[] postToFile(
- final String targetAddress,
- final String targetPeerHash,
- final String filename,
- final Map<String, ContentBody> parts,
- final int timeout) throws IOException {
- final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
- return httpClient.POSTbytes(
- new MultiProtocolURI("http://" + targetAddress + "/yacy/" + filename),
- Seed.b64Hash2hexHash(targetPeerHash) + ".yacyh",
- parts,
- false);
- }
-
- /**
- * this is called to enrich the seed information by - own address (if peer is behind a nat/router) - check
- * peer type (virgin/junior/senior/principal) to do this, we send a 'Hello' to another peer this carries
- * the following information: 'iam' - own hash 'youare' - remote hash, to verify that we are correct 'key'
- * - a session key that the remote peer may use to answer and the own seed string we expect the following
- * information to be send back: - 'yourip' the ip of the connection peer (we) - 'yourtype' the type of
- * this peer that the other peer checked by asking for a specific word and the remote seed string one
- * exceptional failure case is when we know the other's peers hash, the other peers responds correctly but
- * they appear to be another peer by comparisment of the other peer's hash this works of course only if we
- * know the other peer's hash.
- *
- * @return the number of new seeds
- */
- public static int hello(
- final Seed mySeed,
- final PeerActions peerActions,
- final String address,
- final String otherHash,
- final String otherName) {
-
- Map<String, String> result = null;
- final String salt = crypt.randomSalt();
- long responseTime = Long.MAX_VALUE;
- byte[] content = null;
- try {
- // generate request
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), null, salt);
- parts.put("count", UTF8.StringBody("20"));
- parts.put("magic", UTF8.StringBody(Long.toString(Network.magic)));
- parts.put("seed", UTF8.StringBody(mySeed.genSeedStr(salt)));
- // send request
- final long start = System.currentTimeMillis();
- // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/hello.html"), 30000, yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", parts);
- final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 30000);
- content =
- httpClient.POSTbytes(
- new MultiProtocolURI("http://" + address + "/yacy/hello.html"),
- Seed.b64Hash2hexHash(otherHash) + ".yacyh",
- parts,
- false);
- responseTime = System.currentTimeMillis() - start;
- result = FileUtils.table(content);
- } catch ( final Exception e ) {
- if ( Thread.currentThread().isInterrupted() ) {
- Network.log.logInfo("yacyClient.hello thread '"
- + Thread.currentThread().getName()
- + "' interrupted.");
- return -1;
- }
- Network.log.logInfo("yacyClient.hello thread '"
- + Thread.currentThread().getName()
- + "', peer "
- + address
- + "; exception: "
- + e.getMessage());
- // try again (go into loop)
- result = null;
- }
-
- if (result == null || result.size() == 0) {
- Network.log.logInfo("yacyClient.hello result error: "
- + ((result == null) ? "result null" : ("result=" + result.toString())));
- return -1;
- }
- Network.log.logInfo("yacyClient.hello thread '"
- + Thread.currentThread().getName()
- + "' contacted peer at "
- + address
- + ", received "
- + ((content == null) ? "null" : content.length)
- + " bytes, time = "
- + responseTime
- + " milliseconds");
-
- // check consistency with expectation
- Seed otherPeer = null;
- String seed;
- if ( (otherHash != null) && (otherHash.length() > 0) && ((seed = result.get("seed0")) != null) ) {
- if ( seed.length() > Seed.maxsize ) {
- Network.log.logInfo("hello/client 0: rejected contacting seed; too large ("
- + seed.length()
- + " > "
- + Seed.maxsize
- + ")");
- } else {
- try {
- final int p = address.indexOf(':');
- if ( p < 0 ) {
- return -1;
- }
- String h = address.substring(0, p);
- InetAddress ie = Domains.dnsResolve(h);
- final String host = ie == null ? h : ie.getHostAddress(); // hack to prevent NPEs
- otherPeer = Seed.genRemoteSeed(seed, false, host);
- if ( !otherPeer.hash.equals(otherHash) ) {
- Network.log.logInfo("yacyClient.hello: consistency error: otherPeer.hash = "
- + otherPeer.hash
- + ", otherHash = "
- + otherHash);
- return -1; // no success
- }
- } catch ( final IOException e ) {
- Network.log.logInfo("yacyClient.hello: consistency error: other seed bad:"
- + e.getMessage()
- + ", seed="
- + seed);
- return -1; // no success
- }
- }
- }
-
- // get access type response
- String mytype = result.get(Seed.YOURTYPE);
- if ( mytype == null ) {
- mytype = "";
- }
-
- // set my own seed according to new information
- // we overwrite our own IP number only
- if ( serverCore.useStaticIP ) {
- mySeed.setIP(Switchboard.getSwitchboard().myPublicIP());
- } else {
- final String myIP = result.get("yourip");
- final String properIP = Seed.isProperIP(myIP);
- mySeed.setFlagRootNode((mytype.equals(Seed.PEERTYPE_SENIOR) || mytype.equals(Seed.PEERTYPE_PRINCIPAL)) && responseTime < 1000 && Domains.isThisHostIP(myIP));
- if ( properIP == null ) {
- mySeed.setIP(myIP);
- }
- }
-
- // change our seed-type
- final Accessible accessible = new Accessible();
- if ( mytype.equals(Seed.PEERTYPE_SENIOR) || mytype.equals(Seed.PEERTYPE_PRINCIPAL) ) {
- accessible.IWasAccessed = true;
- if ( mySeed.isPrincipal() ) {
- mytype = Seed.PEERTYPE_PRINCIPAL;
- }
- } else {
- accessible.IWasAccessed = false;
- }
- accessible.lastUpdated = System.currentTimeMillis();
- Network.amIAccessibleDB.put(otherHash, accessible);
-
- /*
- * If we were reported as junior we have to check if your port forwarding channel is broken
- * If this is true we try to reconnect the sch channel to the remote server now.
- */
- if ( mytype.equalsIgnoreCase(Seed.PEERTYPE_JUNIOR) ) {
- Network.log.logInfo("yacyClient.hello: Peer '"
- + ((otherPeer == null) ? "unknown" : otherPeer.getName())
- + "' reported us as junior.");
- } else if ( (mytype.equalsIgnoreCase(Seed.PEERTYPE_SENIOR))
- || (mytype.equalsIgnoreCase(Seed.PEERTYPE_PRINCIPAL)) ) {
- if ( Network.log.isFine() ) {
- Network.log.logFine("yacyClient.hello: Peer '"
- + ((otherPeer == null) ? "unknown" : otherPeer.getName())
- + "' reported us as "
- + mytype
- + ", accepted other peer.");
- }
- } else {
- // wrong type report
- if ( Network.log.isFine() ) {
- Network.log.logFine("yacyClient.hello: Peer '"
- + ((otherPeer == null) ? "unknown" : otherPeer.getName())
- + "' reported us as "
- + mytype
- + ", rejecting other peer.");
- }
- return -1;
- }
- if ( mySeed.orVirgin().equals(Seed.PEERTYPE_VIRGIN) ) {
- mySeed.put(Seed.PEERTYPE, mytype);
- }
-
- final String error = mySeed.isProper(true);
- if ( error != null ) {
- Network.log.logWarning("yacyClient.hello mySeed error - not proper: " + error);
- return -1;
- }
-
- //final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time
-
- // read the seeds that the peer returned and integrate them into own database
- int i = 0;
- int count = 0;
- String seedStr;
- Seed s;
- final int connectedBefore = peerActions.sizeConnected();
- while ( (seedStr = result.get("seed" + i++)) != null ) {
- // integrate new seed into own database
- // the first seed, "seed0" is the seed of the responding peer
- if ( seedStr.length() > Seed.maxsize ) {
- Network.log.logInfo("hello/client: rejected contacting seed; too large ("
- + seedStr.length()
- + " > "
- + Seed.maxsize
- + ")");
- } else {
- try {
- if ( i == 1 ) {
- final int p = address.indexOf(':');
- if ( p < 0 ) {
- return -1;
- }
- InetAddress ia = Domains.dnsResolve(address.substring(0, p));
- if (ia == null) continue;
- final String host = ia.getHostAddress();
- s = Seed.genRemoteSeed(seedStr, false, host);
- } else {
- s = Seed.genRemoteSeed(seedStr, false, null);
- }
- if ( peerActions.peerArrival(s, (i == 1)) ) {
- count++;
- }
- } catch ( final IOException e ) {
- Network.log.logInfo("hello/client: rejected contacting seed; bad ("
- + e.getMessage()
- + ")");
- }
- }
- }
- final int connectedAfter = peerActions.sizeConnected();
-
- // update event tracker
- EventTracker.update(EventTracker.EClass.PEERPING, new ProfilingGraph.EventPing(
- mySeed.getName(),
- otherName,
- true,
- connectedAfter - connectedBefore), false);
-
- return count;
- }
-
- public static Seed querySeed(final Seed target, final String seedHash) {
- // prepare request
- final String salt = crypt.randomSalt();
-
- // send request
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
- parts.put("object", UTF8.StringBody("seed"));
- parts.put("env", UTF8.StringBody(seedHash));
- final byte[] content = postToFile(target, "query.html", parts, 10000);
- final Map<String, String> result = FileUtils.table(content);
-
- if ( result == null || result.isEmpty() ) {
- return null;
- }
- //final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time
- return Seed.genRemoteSeed(result.get("response"), false, target.getIP());
- } catch ( final Exception e ) {
- Network.log.logWarning("yacyClient.querySeed error:" + e.getMessage());
- return null;
- }
- }
-
- public static int queryRWICount(final Seed target, final String wordHash) {
- // prepare request
- final String salt = crypt.randomSalt();
-
- // send request
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
- parts.put("object", UTF8.StringBody("rwicount"));
- parts.put("ttl", UTF8.StringBody("0"));
- parts.put("env", UTF8.StringBody(wordHash));
- final byte[] content = postToFile(target, "query.html", parts, 6000);
- final Map<String, String> result = FileUtils.table(content);
-
- if ( result == null || result.isEmpty() ) {
- return -1;
- }
- return Integer.parseInt(result.get("response"));
- } catch ( final Exception e ) {
- Network.log.logWarning("yacyClient.queryRWICount error:" + e.getMessage());
- return -1;
- }
- }
-
- /**
- * check the status of a remote peer
- *
- * @param target
- * @return an array of two long: [0] is the count of urls, [1] is a magic
- */
- public static long[] queryUrlCount(final Seed target) {
- if ( target == null ) {
- return new long[] {
- -1, -1
- };
- }
-
- // prepare request
- final String salt = crypt.randomSalt();
-
- // send request
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
- parts.put("object", UTF8.StringBody("lurlcount"));
- parts.put("ttl", UTF8.StringBody("0"));
- parts.put("env", UTF8.StringBody(""));
- final byte[] content = postToFile(target, "query.html", parts, 6000);
- final Map<String, String> result = FileUtils.table(content);
-
- if ( result == null || result.isEmpty() ) {
- return new long[] {
- -1, -1
- };
- }
- final String resp = result.get("response");
- if ( resp == null ) {
- return new long[] {
- -1, -1
- };
- }
- String magic = result.get("magic");
- if ( magic == null ) {
- magic = "0";
- }
- try {
- return new long[] {
- Long.parseLong(resp), Long.parseLong(magic)
- };
- } catch ( final NumberFormatException e ) {
- return new long[] {
- -1, -1
- };
- }
- } catch ( final IOException e ) {
- if ( Network.log.isFine() ) {
- Network.log.logFine("yacyClient.queryUrlCount error asking peer '"
- + target.getName()
- + "':"
- + e.toString());
- }
- return new long[] {
- -1, -1
- };
- }
- }
-
- public static RSSFeed queryRemoteCrawlURLs(
- final SeedDB seedDB,
- final Seed target,
- final int maxCount,
- final long maxTime) {
- // returns a list of
- if ( target == null ) {
- return null;
- }
- final int targetCount = Integer.parseInt(target.get(Seed.RCOUNT, "0"));
- if ( targetCount <= 0 ) {
- Network.log.logWarning("yacyClient.queryRemoteCrawlURLs wrong peer '"
- + target.getName()
- + "' selected: not enough links available");
- return null;
- }
- // prepare request
- final String salt = crypt.randomSalt();
-
- // send request
- try {
- /* a long time-out is needed */
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
- parts.put("call", UTF8.StringBody("remotecrawl"));
- parts.put("count", UTF8.StringBody(Integer.toString(maxCount)));
- parts.put("time", UTF8.StringBody(Long.toString(maxTime)));
- // final byte[] result = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/urls.xml"), (int) maxTime, target.getHexHash() + ".yacyh", parts);
- final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), (int) maxTime);
- final byte[] result =
- httpClient.POSTbytes(new MultiProtocolURI("http://"
- + target.getClusterAddress()
- + "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false);
- final RSSReader reader = RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, result);
- if ( reader == null ) {
- Network.log.logWarning("yacyClient.queryRemoteCrawlURLs failed asking peer '"
- + target.getName()
- + "': probably bad response from remote peer (1), reader == null");
- target.put(Seed.RCOUNT, "0");
- seedDB.update(target.hash, target); // overwrite number of remote-available number to avoid that this peer is called again (until update is done by peer ping)
- //Log.logException(e);
- return null;
- }
- final RSSFeed feed = reader.getFeed();
- if ( feed == null ) {
- // case where the rss reader does not understand the content
- Network.log.logWarning("yacyClient.queryRemoteCrawlURLs failed asking peer '"
- + target.getName()
- + "': probably bad response from remote peer (2)");
- //System.out.println("***DEBUG*** rss input = " + UTF8.String(result));
- target.put(Seed.RCOUNT, "0");
- seedDB.update(target.hash, target); // overwrite number of remote-available number to avoid that this peer is called again (until update is done by peer ping)
- //Log.logException(e);
- return null;
- }
- // update number of remotely available links in seed
- target.put(Seed.RCOUNT, Integer.toString(Math.max(0, targetCount - feed.size())));
- seedDB.update(target.hash, target);
- return feed;
- } catch ( final IOException e ) {
- Network.log.logWarning("yacyClient.queryRemoteCrawlURLs error asking peer '"
- + target.getName()
- + "':"
- + e.toString());
- return null;
- }
- }
-
- public static RSSFeed search(
- final Seed targetSeed,
- final String query,
- final CacheStrategy verify,
- final boolean global,
- final long timeout,
- final int startRecord,
- final int maximumRecords) throws IOException {
- final String address =
- (targetSeed == null || targetSeed == Switchboard.getSwitchboard().peers.mySeed()) ? "localhost:"
- + Switchboard.getSwitchboard().getConfig("port", "8090") : targetSeed.getClusterAddress();
- final String urlBase = "http://" + address + "/yacysearch.rss";
- return SRURSSConnector.loadSRURSS(
- urlBase,
- query,
- timeout,
- startRecord,
- maximumRecords,
- verify,
- global,
- null);
- }
-
- protected static int primarySearch(
- final SearchEvent event,
- final String wordhashes,
- final String excludehashes,
- final String language,
- final String contentdom,
- final int count,
- final long time,
- final int maxDistance,
- final int partitions,
- final Seed target,
- final SecondarySearchSuperviser secondarySearchSuperviser,
- final Blacklist blacklist) {
- // send a search request to peer with remote Hash
-
- // INPUT:
- // iam : complete seed of the requesting peer
- // youare : seed hash of the target peer, used for testing network stability
- // key : transmission key for response
- // search : a list of search words
- // hsearch : a string of word hashes
- // fwdep : forward depth. if "0" then peer may NOT ask another peer for more results
- // fwden : forward deny, a list of seed hashes. They may NOT be target of forward hopping
- // count : maximum number of wanted results
- // global : if "true", then result may consist of answers from other peers
- // partitions : number of remote peers that are asked (for evaluation of QPM)
- // duetime : maximum time that a peer should spent to create a result
-
- final long timestamp = System.currentTimeMillis();
- event.addExpectedRemoteReferences(count);
- SearchResult result;
- try {
- result =
- new SearchResult(
- event,
- basicRequestParts(Switchboard.getSwitchboard(), target.hash, crypt.randomSalt()),
- wordhashes,
- excludehashes,
- "",
- language,
- contentdom,
- count,
- time,
- maxDistance,
- partitions,
- target.getHexHash() + ".yacyh",
- target.getClusterAddress(),
- secondarySearchSuperviser
- );
- } catch ( final IOException e ) {
- Network.log.logInfo("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + ")");
- event.peers.peerActions.peerDeparture(target, "search request to peer created io exception: " + e.getMessage());
- return -1;
- }
- // computation time
- final long totalrequesttime = System.currentTimeMillis() - timestamp;
-
- try {
- remoteSearchProcess(event, count, totalrequesttime, wordhashes, target, blacklist, result);
- } catch (SpaceExceededException e) {
- Log.logException(e);
- return -1;
- }
-
- // read index abstract
- if ( secondarySearchSuperviser != null ) {
- String wordhash;
- String whacc = "";
- ByteBuffer ci;
- int ac = 0;
- for ( final Map.Entry<byte[], String> abstractEntry : result.indexabstract.entrySet() ) {
- try {
- ci = new ByteBuffer(abstractEntry.getValue());
- wordhash = ASCII.String(abstractEntry.getKey());
- } catch ( final OutOfMemoryError e ) {
- Log.logException(e);
- continue;
- }
- whacc += wordhash;
- secondarySearchSuperviser.addAbstract(
- wordhash,
- WordReferenceFactory.decompressIndex(ci, target.hash));
- ac++;
-
- }
- if ( ac > 0 ) {
- secondarySearchSuperviser.commitAbstract();
- Network.log.logInfo("remote search: peer " + target.getName() + " sent " + ac + " index abstracts for words " + whacc);
- }
- }
- return result.urlcount;
- }
-
- protected static int secondarySearch(
- final SearchEvent event,
- final String wordhashes,
- final String urlhashes,
- final String contentdom,
- final int count,
- final long time,
- final int maxDistance,
- final int partitions,
- final Seed target,
- final Blacklist blacklist) {
-
- final long timestamp = System.currentTimeMillis();
- event.addExpectedRemoteReferences(count);
- SearchResult result;
- try {
- result =
- new SearchResult(
- event,
- basicRequestParts(Switchboard.getSwitchboard(), target.hash, crypt.randomSalt()),
- wordhashes,
- "",
- urlhashes,
- "",
- contentdom,
- count,
- time,
- maxDistance,
- partitions,
- target.getHexHash() + ".yacyh",
- target.getClusterAddress(),
- null
- );
- } catch ( final IOException e ) {
- Network.log.logInfo("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + ")");
- event.peers.peerActions.peerDeparture(target, "search request to peer created io exception: " + e.getMessage());
- return -1;
- }
- // computation time
- final long totalrequesttime = System.currentTimeMillis() - timestamp;
-
- try {
- remoteSearchProcess(event, count, totalrequesttime, wordhashes, target, blacklist, result);
- } catch (SpaceExceededException e) {
- Log.logException(e);
- return -1;
- }
- return result.urlcount;
- }
-
- private static void remoteSearchProcess(
- final SearchEvent event,
- final int count,
- final long time,
- final String wordhashes,
- final Seed target,
- final Blacklist blacklist,
- final SearchResult result
- ) throws SpaceExceededException {
-
- // create containers
- final int words = wordhashes.length() / Word.commonHashLength;
- assert words > 0 : "wordhashes = " + wordhashes;
- final List<ReferenceContainer<WordReference>> container = new ArrayList<ReferenceContainer<WordReference>>(words);
- for ( int i = 0; i < words; i++ ) {
- container.add(ReferenceContainer.emptyContainer(
- Segment.wordReferenceFactory,
- ASCII.getBytes(wordhashes.substring(i * Word.commonHashLength, (i + 1) * Word.commonHashLength)),
- count)); // throws SpaceExceededException
- }
-
- // insert results to containers
- int term = count;
- for ( final URIMetadataRow urlEntry : result.links ) {
- if ( term-- <= 0 ) {
- break; // do not process more that requested (in case that evil peers fill us up with rubbish)
- }
- // get one single search result
- if ( urlEntry == null ) {
- continue;
- }
- assert (urlEntry.hash().length == 12) : "urlEntry.hash() = " + ASCII.String(urlEntry.hash());
- if ( urlEntry.hash().length != 12 ) {
- continue; // bad url hash
- }
- if ( blacklist.isListed(BlacklistType.SEARCH, urlEntry) ) {
- if ( Network.log.isInfo() ) {
- Network.log.logInfo("remote search: filtered blacklisted url " + urlEntry.url() + " from peer " + target.getName());
- }
- continue; // block with backlist
- }
-
- final String urlRejectReason =
- Switchboard.getSwitchboard().crawlStacker.urlInAcceptedDomain(urlEntry.url());
- if ( urlRejectReason != null ) {
- if ( Network.log.isInfo() ) {
- Network.log.logInfo("remote search: rejected url '" + urlEntry.url() + "' (" + urlRejectReason + ") from peer " + target.getName());
- }
- continue; // reject url outside of our domain
- }
-
- // save the url entry
- final Reference entry = urlEntry.word();
- if ( entry == null ) {
- if ( Network.log.isWarning() ) {
- Network.log.logWarning("remote search: no word attached from peer " + target.getName() + ", version " + target.getVersion());
- }
- continue; // no word attached
- }
-
- // the search-result-url transports all the attributes of word indexes
- if ( !Base64Order.enhancedCoder.equal(entry.urlhash(), urlEntry.hash()) ) {
- Network.log.logInfo("remote search: url-hash " + ASCII.String(urlEntry.hash()) + " does not belong to word-attached-hash " + ASCII.String(entry.urlhash()) + "; url = " + urlEntry.url() + " from peer " + target.getName());
- continue; // spammed
- }
-
- // passed all checks, store url
- try {
- event.query.getSegment().fulltext().putMetadata(urlEntry);
- ResultURLs.stack(
- ASCII.String(urlEntry.url().hash()),
- urlEntry.url().getHost(),
- event.peers.mySeed().hash.getBytes(),
- UTF8.getBytes(target.hash),
- EventOrigin.QUERIES);
- } catch ( final IOException e ) {
- Network.log.logWarning("could not store search result", e);
- continue; // db-error
- }
-
- if ( urlEntry.snippet() != null
- && urlEntry.snippet().length() > 0
- && !urlEntry.snippet().equals("null") ) {
- // we don't store the snippets along the url entry,
- // because they are search-specific.
- // instead, they are placed in a snipped-search cache.
- // System.out.println("--- RECEIVED SNIPPET '" + urlEntry.snippet() + "'");
- TextSnippet.snippetsCache.put(wordhashes, ASCII.String(urlEntry.hash()), urlEntry.snippet());
- }
-
- // add the url entry to the word indexes
- for ( final ReferenceContainer<WordReference> c : container ) {
- try {
- c.add(entry);
- } catch ( final SpaceExceededException e ) {
- Log.logException(e);
- break;
- }
- }
- }
-
- // store remote result to local result container
- // insert one container into the search result buffer
- // one is enough, only the references are used, not the word
- event.rankingProcess.add(container.get(0), false, target.getName() + "/" + target.hash, result.joincount, time);
- event.rankingProcess.addFinalize();
- event.addExpectedRemoteReferences(-count);
-
- // insert the containers to the index
- for ( final ReferenceContainer<WordReference> c : container ) {
- try {
- event.query.getSegment().storeRWI(c);
- } catch ( final Exception e ) {
- Log.logException(e);
- }
- }
-
- // integrate remote top-words/topics
- if ( result.references != null && result.references.length > 0 ) {
- Network.log.logInfo("remote search: peer " + target.getName() + " sent " + result.references.length + " topics");
- // add references twice, so they can be counted (must have at least 2 entries)
- synchronized ( event.rankingProcess ) {
- event.rankingProcess.addTopic(result.references);
- event.rankingProcess.addTopic(result.references);
- }
- }
- Network.log.logInfo("remote search: peer " + target.getName() + " sent " + container.get(0).size() + "/" + result.joincount + " references");
- }
-
- private static class SearchResult {
- public int urlcount; // number of returned LURL's for this search
- public int joincount; //
- public Map<byte[], Integer> indexcount; //
- public long searchtime; // time that the peer actually spent to create the result
- public String[] references; // search hints, the top-words
- public List<URIMetadataRow> links; // LURLs of search
- public Map<byte[], String> indexabstract; // index abstracts, a collection of url-hashes per word
-
- public SearchResult(
- final SearchEvent event,
- final Map<String, ContentBody> parts,
- final String wordhashes,
- final String excludehashes,
- final String urlhashes,
- final String language,
- final String contentdom,
- final int count,
- final long time,
- final int maxDistance,
- final int partitions,
- final String hostname,
- final String hostaddress,
- final SecondarySearchSuperviser secondarySearchSuperviser
- ) throws IOException {
- // send a search request to peer with remote Hash
-
- //if (hostaddress.equals(mySeed.getClusterAddress())) hostaddress = "127.0.0.1:" + mySeed.getPort(); // for debugging
-
- // INPUT:
- // iam : complete seed of the requesting peer
- // youare : seed hash of the target peer, used for testing network stability
- // key : transmission key for response
- // search : a list of search words
- // hsearch : a string of word hashes
- // fwdep : forward depth. if "0" then peer may NOT ask another peer for more results
- // fwden : forward deny, a list of seed hashes. They may NOT be target of forward hopping
- // count : maximum number of wanted results
- // global : if "true", then result may consist of answers from other peers
- // partitions : number of remote peers that are asked (for evaluation of QPM)
- // duetime : maximum time that a peer should spent to create a result
-
- // send request
- Map<String, String> resultMap = null;
- String key = "";
- final ContentBody keyBody = parts.get("key");
- if ( keyBody != null ) {
- final ByteArrayOutputStream baos = new ByteArrayOutputStream(20);
- keyBody.writeTo(baos);
- key = baos.toString();
- }
-
- String filter = event.query.urlMask.pattern().toString();
- if (event.query.tld != null) filter = ".*" + event.query.tld + ".*" + filter;
- if (event.query.modifier.protocol != null) filter = ".*" + event.query.modifier.protocol + ".*" + filter;
- if (event.query.modifier.filetype != null) filter = filter + ".*" + event.query.modifier.filetype + ".*";
- parts.put("myseed", UTF8.StringBody((event.peers.mySeed() == null) ? "" : event.peers.mySeed().genSeedStr(key)));
- parts.put("count", UTF8.StringBody(Integer.toString(Math.max(10, count))));
- parts.put("time", UTF8.StringBody(Long.toString(Math.max(3000, time))));
- parts.put("partitions", UTF8.StringBody(Integer.toString(partitions)));
- parts.put("query", UTF8.StringBody(wordhashes));
- parts.put("exclude", UTF8.StringBody(excludehashes));
- parts.put("duetime", UTF8.StringBody("1000"));
- parts.put("urls", UTF8.StringBody(urlhashes));
- parts.put("prefer", UTF8.StringBody(event.query.prefer.pattern()));
- parts.put("filter", UTF8.StringBody(filter));
- parts.put("modifier", UTF8.StringBody(event.query.modifier.toString()));
- parts.put("language", UTF8.StringBody(language));
- parts.put("sitehash", UTF8.StringBody(event.query.modifier.sitehash));
- parts.put("author", UTF8.StringBody(event.query.modifier.author));
- parts.put("contentdom", UTF8.StringBody(contentdom));
- parts.put("ttl", UTF8.StringBody("0"));
- parts.put("maxdist", UTF8.StringBody(Integer.toString(maxDistance)));
- parts.put("profile", UTF8.StringBody(crypt.simpleEncode(event.query.ranking.toExternalString())));
- parts.put("constraint", UTF8.StringBody((event.query.constraint == null) ? "" : event.query.constraint.exportB64()));
- if ( secondarySearchSuperviser != null ) {
- parts.put("abstracts", UTF8.StringBody("auto"));
- // resultMap = FileUtils.table(HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + hostaddress + "/yacy/search.html"), 60000, hostname, parts));
- //resultMap = FileUtils.table(HTTPConnector.getConnector(MultiProtocolURI.crawlerUserAgent).post(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/search.html"), 60000, target.getHexHash() + ".yacyh", parts));
- }
-
- final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 8000);
- byte[] a = httpClient.POSTbytes(new MultiProtocolURI("http://" + hostaddress + "/yacy/search.html"), hostname, parts, false);
- if (a != null && a.length > 200000) {
- // there is something wrong. This is too large, maybe a hack on the other side?
- a = null;
- }
- resultMap = FileUtils.table(a);
-
- // evaluate request result
- if ( resultMap == null || resultMap.isEmpty() ) {
- throw new IOException("resultMap is NULL");
- }
- try {
- this.searchtime = Integer.parseInt(resultMap.get("searchtime"));
- } catch ( final NumberFormatException e ) {
- throw new IOException("wrong output format for searchtime: "
- + e.getMessage()
- + ", map = "
- + resultMap.toString());
- }
- try {
- this.joincount = Integer.parseInt(resultMap.get("joincount")); // the complete number of hits at remote site
- } catch ( final NumberFormatException e ) {
- throw new IOException("wrong output format for joincount: " + e.getMessage());
- }
- try {
- this.urlcount = Integer.parseInt(resultMap.get("count")); // the number of hits that are returned in the result list
- } catch ( final NumberFormatException e ) {
- throw new IOException("wrong output format for count: " + e.getMessage());
- }
- // scan the result map for entries with special prefix
- this.indexcount = new TreeMap<byte[], Integer>(Base64Order.enhancedCoder);
- this.indexabstract = new TreeMap<byte[], String>(Base64Order.enhancedCoder);
- for ( final Map.Entry<String, String> entry : resultMap.entrySet() ) {
- if ( entry.getKey().startsWith("indexcount.") ) {
- this.indexcount.put(
- UTF8.getBytes(entry.getKey().substring(11)),
- Integer.parseInt(entry.getValue()));
- }
- if ( entry.getKey().startsWith("indexabstract.") ) {
- this.indexabstract.put(UTF8.getBytes(entry.getKey().substring(14)), entry.getValue());
- }
- }
- this.references = resultMap.get("references").split(",");
- this.links = new ArrayList<URIMetadataRow>(this.urlcount);
- for ( int n = 0; n < this.urlcount; n++ ) {
- // get one single search result
- final String resultLine = resultMap.get("resource" + n);
- if ( resultLine == null ) {
- continue;
- }
- final URIMetadataRow urlEntry = URIMetadataRow.importEntry(resultLine);
- if ( urlEntry == null ) {
- continue;
- }
- this.links.add(urlEntry);
- }
- }
- }
-
- private final static YaCySchema[] snippetFields = new YaCySchema[]{YaCySchema.h1_txt, YaCySchema.h2_txt, YaCySchema.text_t};
-
- protected static int solrQuery(
- final SearchEvent event,
- final int offset,
- final int count,
- boolean getFacets,
- final Seed target,
- final Blacklist blacklist) {
-
- if (event.query.getQueryGoal().getOriginalQueryString(false) == null || event.query.getQueryGoal().getOriginalQueryString(false).length() == 0) {
- return -1; // we cannot query solr only with word hashes, there is no clear text string
- }
- event.addExpectedRemoteReferences(count);
- final SolrQuery solrQuery = event.query.solrQuery();
- solrQuery.setStart(offset);
- solrQuery.setRows(count);
-
- // set facet query attributes
- if (getFacets && event.query.facetfields.size() > 0) {
- solrQuery.setFacet(true);
- solrQuery.setFacetLimit(event.query.maxfacets);
- solrQuery.setFacetSort(FacetParams.FACET_SORT_COUNT);
- for (String field: event.query.facetfields) solrQuery.addFacetField(field);
- } else {
- solrQuery.setFacet(false);
- }
-
- // set highlightning query attributes
- solrQuery.setHighlight(true);
- solrQuery.setHighlightFragsize(SearchEvent.SNIPPET_MAX_LENGTH);
- //solrQuery.setHighlightRequireFieldMatch();
- solrQuery.setHighlightSimplePost("</b>");
- solrQuery.setHighlightSimplePre("<b>");
- solrQuery.setHighlightSnippets(1);
- for (YaCySchema field: snippetFields) solrQuery.addHighlightField(field.getSolrFieldName());
-
- boolean localsearch = target == null || target.equals(event.peers.mySeed());
- SolrDocumentList docList = null;
- QueryResponse rsp = null;
- if (localsearch) {
- // search the local index
- try {
- rsp = event.rankingProcess.getQuery().getSegment().fulltext().getSolr().query(solrQuery);
- docList = rsp.getResults();
- } catch (Throwable e) {
- Network.log.logInfo("SEARCH failed (solr), localpeer (" + e.getMessage() + ")", e);
- return -1;
- }
- } else {
- final String solrURL = "http://" + target.getPublicAddress() + "/solr";
- try {
- SolrConnector solrConnector = new RemoteSolrConnector(solrURL);
- rsp = solrConnector.query(solrQuery);
- docList = rsp.getResults();
- // no need to close this here because that sends a commit to remote solr which is not wanted here
- } catch (Throwable e) {
- Network.log.logInfo("SEARCH failed (solr), remote Peer: " +target.getName() + "/" + target.getPublicAddress() + " (" + e.getMessage() + ")", e);
- return -1;
- }
- }
-
- // evaluate facets
- Map<String, ReversibleScoreMap<String>> facets = new HashMap<String, ReversibleScoreMap<String>>(event.query.facetfields.size());
- for (String field: event.query.facetfields) {
- FacetField facet = rsp.getFacetField(field);
- ReversibleScoreMap<String> result = new ClusteredScoreMap<String>(UTF8.insensitiveUTF8Comparator);
- List<Count> values = facet == null ? null : facet.getValues();
- if (values == null) continue;
- for (Count ff: values) {
- int c = (int) ff.getCount();
- if (c == 0) continue;
- result.set(ff.getName(), c);
- }
- facets.put(field, result);
- }
-
- // evaluate snippets
- Map<String, Map<String, List<String>>> rawsnippets = rsp.getHighlighting(); // a map from the urlhash to a map with key=field and value = list of snippets
- Map<String, String> snippets = new HashMap<String, String>(); // this will be a list of urlhash-snippet entries
- if (rawsnippets != null) {
- nextsnippet: for (Map.Entry<String, Map<String, List<String>>> re: rawsnippets.entrySet()) {
- Map<String, List<String>> rs = re.getValue();
- for (YaCySchema field: snippetFields) {
- if (rs.containsKey(field.getSolrFieldName())) {
- List<String> s = rs.get(field.getSolrFieldName());
- if (s.size() > 0) {
- snippets.put(re.getKey(), s.get(0));
- continue nextsnippet;
- }
- }
- }
- // no snippet found :( --we don't assign a value here by default; that can be done as an evaluation outside this method
- }
- }
-
- // evaluate result
- List<URIMetadataNode> container = new ArrayList<URIMetadataNode>();
- if (docList == null || docList.size() == 0) {
- Network.log.logInfo("SEARCH (solr), returned 0 out of 0 documents from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())) + " query = " + solrQuery.toString()) ;
- return 0;
- }
-
- Network.log.logInfo("SEARCH (solr), returned " + docList.size() + " out of " + docList.getNumFound() + " documents from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));
- int term = count;
- for (final SolrDocument doc: docList) {
- if ( term-- <= 0 ) {
- break; // do not process more that requested (in case that evil peers fill us up with rubbish)
- }
- // get one single search result
- if ( doc == null ) {
- continue;
- }
- URIMetadataNode urlEntry = new URIMetadataNode(doc);
-
- if ( blacklist.isListed(BlacklistType.SEARCH, urlEntry) ) {
- if ( Network.log.isInfo() ) {
- if (localsearch) {
- Network.log.logInfo("local search (solr): filtered blacklisted url " + urlEntry.url());
- } else {
- Network.log.logInfo("remote search (solr): filtered blacklisted url " + urlEntry.url() + " from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));
- }
- }
- continue; // block with blacklist
- }
-
- final String urlRejectReason = Switchboard.getSwitchboard().crawlStacker.urlInAcceptedDomain(urlEntry.url());
- if ( urlRejectReason != null ) {
- if ( Network.log.isInfo() ) {
- if (localsearch) {
- Network.log.logInfo("local search (solr): rejected url '" + urlEntry.url() + "' (" + urlRejectReason + ")");
- } else {
- Network.log.logInfo("remote search (solr): rejected url '" + urlEntry.url() + "' (" + urlRejectReason + ") from peer " + target.getName());
- }
- }
- continue; // reject url outside of our domain
- }
-
- // passed all checks, store url
- if (!localsearch) {
- try {
- event.query.getSegment().fulltext().putDocument(YaCySchema.toSolrInputDocument(doc,Switchboard.getSwitchboard().index.fulltext().getSolrScheme()));
- ResultURLs.stack(
- ASCII.String(urlEntry.url().hash()),
- urlEntry.url().getHost(),
- event.peers.mySeed().hash.getBytes(),
- UTF8.getBytes(target.hash),
- EventOrigin.QUERIES);
- } catch ( final IOException e ) {
- Network.log.logWarning("could not store search result", e);
- continue; // db-error
- }
- }
-
- // add the url entry to the word indexes
- container.add(urlEntry);
- }
-
- if (localsearch) {
- event.add(container, facets, snippets, true, "localpeer", (int) docList.getNumFound());
- event.rankingProcess.addFinalize();
- event.addExpectedRemoteReferences(-count);
- Network.log.logInfo("local search (solr): localpeer sent " + container.get(0).size() + "/" + docList.size() + " references");
- } else {
- event.add(container, facets, snippets, false, target.getName() + "/" + target.hash, (int) docList.getNumFound());
- event.rankingProcess.addFinalize();
- event.addExpectedRemoteReferences(-count);
- Network.log.logInfo("remote search (solr): peer " + target.getName() + " sent " + container.get(0).size() + "/" + docList.size() + " references");
- }
- return docList.size();
- }
-
- public static Map<String, String> permissionMessage(final SeedDB seedDB, final String targetHash) {
- // ask for allowed message size and attachement size
- // if this replies null, the peer does not answer
-
- // prepare request
- final String salt = crypt.randomSalt();
-
- // send request
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), targetHash, salt);
- parts.put("process", UTF8.StringBody("permission"));
- final byte[] content = postToFile(seedDB, targetHash, "message.html", parts, 6000);
- final Map<String, String> result = FileUtils.table(content);
- return result;
- } catch ( final Exception e ) {
- // most probably a network time-out exception
- Network.log.logWarning("yacyClient.permissionMessage error:" + e.getMessage());
- return null;
- }
- }
-
- public static Map<String, String> postMessage(
- final SeedDB seedDB,
- final String targetHash,
- final String subject,
- final byte[] message) {
- // this post a message to the remote message board
-
- // prepare request
- final String salt = crypt.randomSalt();
-
- // send request
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), targetHash, salt);
- parts.put("process", UTF8.StringBody("post"));
- parts.put("myseed", UTF8.StringBody(seedDB.mySeed().genSeedStr(salt)));
- parts.put("subject", UTF8.StringBody(subject));
- parts.put("message", UTF8.StringBody(message));
- final byte[] content = postToFile(seedDB, targetHash, "message.html", parts, 20000);
- final Map<String, String> result = FileUtils.table(content);
- return result;
- } catch ( final Exception e ) {
- Network.log.logWarning("yacyClient.postMessage error:" + e.getMessage());
- return null;
- }
- }
-
- public static Map<String, String> crawlReceipt(
- final Seed mySeed,
- final Seed target,
- final String process,
- final String result,
- final String reason,
- final URIMetadataNode entry,
- final String wordhashes) {
- assert (target != null);
- assert (mySeed != null);
- assert (mySeed != target);
-
- /*
- the result can have one of the following values:
- negative cases, no retry
- unavailable - the resource is not avaiable (a broken link); not found or interrupted
- robot - a robot-file has denied to crawl that resource
-
- negative cases, retry possible
- rejected - the peer has rejected to load the resource
- dequeue - peer too busy - rejected to crawl
-
- positive cases with crawling
- fill - the resource was loaded and processed
- update - the resource was already in database but re-loaded and processed
-
- positive cases without crawling
- known - the resource is already in database, believed to be fresh and not reloaded
- stale - the resource was reloaded but not processed because source had no changes
-
- */
-
- // prepare request
- final String salt = crypt.randomSalt();
-
- // determining target address
- final String address = target.getClusterAddress();
- if ( address == null ) {
- return null;
- }
-
- // send request
- try {
- // prepare request
- final Map<String, ContentBody> parts = basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
- parts.put("process", UTF8.StringBody(process));
- parts.put("urlhash", UTF8.StringBody(((entry == null) ? "" : ASCII.String(entry.hash()))));
- parts.put("result", UTF8.StringBody(result));
- parts.put("reason", UTF8.StringBody(reason));
- parts.put("wordh", UTF8.StringBody(wordhashes));
- parts.put(
- "lurlEntry",
- UTF8.StringBody(((entry == null) ? "" : crypt.simpleEncode(entry.toString(), salt))));
- // send request
- // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/crawlReceipt.html"), 10000, target.getHexHash() + ".yacyh", parts);
- final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 10000);
- final byte[] content =
- httpClient.POSTbytes(
- new MultiProtocolURI("http://" + address + "/yacy/crawlReceipt.html"),
- target.getHexHash() + ".yacyh",
- parts,
- false);
- return FileUtils.table(content);
- } catch ( final Exception e ) {
- // most probably a network time-out exception
- Network.log.logWarning("yacyClient.crawlReceipt error:" + e.getMessage());
- return null;
- }
- }
-
- /**
- * transfer the index. If the transmission fails, return a string describing the cause. If everything is
- * ok, return null.
- *
- * @param targetSeed
- * @param indexes
- * @param urlCache
- * @param gzipBody
- * @param timeout
- * @return
- */
- public static String transferIndex(
- final Seed targetSeed,
- final ReferenceContainerCache<WordReference> indexes,
- final HandleSet urlRefs,
- final Segment segment,
- final boolean gzipBody,
- final int timeout) {
-
- // check if we got all necessary urls in the urlCache (only for debugging)
- Iterator<WordReference> eenum;
- Reference entry;
- for ( final ReferenceContainer<WordReference> ic : indexes ) {
- eenum = ic.entries();
- while ( eenum.hasNext() ) {
- entry = eenum.next();
- if ( !urlRefs.has(entry.urlhash()) ) {
- if ( Network.log.isFine() ) {
- Network.log.logFine("DEBUG transferIndex: to-send url hash '"
- + ASCII.String(entry.urlhash())
- + "' is not contained in urlCache");
- }
- }
- }
- }
-
- // transfer the RWI without the URLs
- Map<String, String> in = transferRWI(targetSeed, indexes, gzipBody, timeout);
-
- if ( in == null ) {
- return "no connection from transferRWI";
- }
-
- String result = in.get("result");
- if ( result == null ) {
- return "no result from transferRWI";
- }
-
- if ( !(result.equals("ok")) ) {
- return result;
- }
-
- // in now contains a list of unknown hashes
- String uhss = in.get("unknownURL");
- if ( uhss == null ) {
- return "no unknownURL tag in response";
- }
- EventChannel
- .channels(EventChannel.DHTSEND)
- .addMessage(
- new RSSMessage(
- "Sent " + indexes.size() + " RWIs to " + targetSeed.getName(),
- "",
- targetSeed.hash));
-
- uhss = uhss.trim();
- if ( uhss.isEmpty() || uhss.equals(",") ) {
- return null;
- } // all url's known, we are ready here
-
- final String[] uhs = uhss.split(",");
- if ( uhs.length == 0 ) {
- return null;
- } // all url's known
-
- // extract the urlCache from the result
- final URIMetadataNode[] urls = new URIMetadataNode[uhs.length];
- byte[] key;
- for ( int i = 0; i < uhs.length; i++ ) {
- key = ASCII.getBytes(uhs[i]);
- if ( urlRefs.has(key) ) urls[i] = segment.fulltext().getMetadata(key);
- if ( urls[i] == null ) {
- if ( Network.log.isFine() ) {
- Network.log.logFine("DEBUG transferIndex: requested url hash '"
- + uhs[i]
- + "', unknownURL='"
- + uhss
- + "'");
- }
- }
- }
-
- in = transferURL(targetSeed, urls, gzipBody, timeout);
-
- if ( in == null ) {
- return "no connection from transferURL";
- }
-
- result = in.get("result");
- if ( result == null ) {
- return "no result from transferURL";
- }
-
- if ( !result.equals("ok") ) {
- return result;
- }
- EventChannel.channels(EventChannel.DHTSEND).addMessage(
- new RSSMessage(
- "Sent " + uhs.length + " URLs to peer " + targetSeed.getName(),
- "",
- targetSeed.hash));
-
- return null;
- }
-
- private static Map<String, String> transferRWI(
- final Seed targetSeed,
- final ReferenceContainerCache<WordReference> indexes,
- boolean gzipBody,
- final int timeout) {
- final String address = targetSeed.getPublicAddress();
- if ( address == null ) {
- Network.log.logWarning("no address for transferRWI");
- return null;
- }
-
- // prepare post values
- final String salt = crypt.randomSalt();
-
- // enabling gzip compression for post request body
- if ( gzipBody && (targetSeed.getVersion() < yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS_CHUNKED) ) {
- gzipBody = false;
- }
-
- int indexcount = 0;
- final StringBuilder entrypost = new StringBuilder(indexes.size() * 73);
- Iterator<WordReference> eenum;
- Reference entry;
- for ( final ReferenceContainer<WordReference> ic : indexes ) {
- eenum = ic.entries();
- while ( eenum.hasNext() ) {
- entry = eenum.next();
- entrypost
- .append(ASCII.String(ic.getTermHash()))
- .append(entry.toPropertyForm())
- .append(serverCore.CRLF_STRING);
- indexcount++;
- }
- }
-
- if ( indexcount == 0 ) {
- // nothing to do but everything ok
- final Map<String, String> result = new HashMap<String, String>(2);
- result.put("result", "ok");
- result.put("unknownURL", "");
- return result;
- }
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), targetSeed.hash, salt);
- parts.put("wordc", UTF8.StringBody(Integer.toString(indexes.size())));
- parts.put("entryc", UTF8.StringBody(Integer.toString(indexcount)));
- parts.put("indexes", UTF8.StringBody(entrypost.toString()));
- // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/transferRWI.html"), timeout, targetSeed.getHexHash() + ".yacyh", parts, gzipBody);
- final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
- final byte[] content =
- httpClient.POSTbytes(
- new MultiProtocolURI("http://" + address + "/yacy/transferRWI.html"),
- targetSeed.getHexHash() + ".yacyh",
- parts,
- gzipBody);
- final Iterator<String> v = FileUtils.strings(content);
- // this should return a list of urlhashes that are unknown
-
- final Map<String, String> result = FileUtils.table(v);
- // return the transfered index data in bytes (for debugging only)
- result.put("indexPayloadSize", Integer.toString(entrypost.length()));
- return result;
- } catch ( final Exception e ) {
- Network.log.logInfo("yacyClient.transferRWI to " + address + " error: " + e.getMessage());
- return null;
- }
- }
-
- private static Map<String, String> transferURL(
- final Seed targetSeed,
- final URIMetadataNode[] urls,
- boolean gzipBody,
- final int timeout) {
- // this post a message to the remote message board
- final String address = targetSeed.getPublicAddress();
- if ( address == null ) {
- return null;
- }
-
- // prepare post values
- final String salt = crypt.randomSalt();
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), targetSeed.hash, salt);
-
- // enabling gzip compression for post request body
- if ( gzipBody && (targetSeed.getVersion() < yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS_CHUNKED) ) {
- gzipBody = false;
- }
-
- String resource;
- int urlc = 0;
- int urlPayloadSize = 0;
- for ( final URIMetadataNode url : urls ) {
- if ( url != null ) {
- resource = url.toString();
- //System.out.println("*** DEBUG resource = " + resource);
- if ( resource != null && resource.indexOf(0) == -1 ) {
- parts.put("url" + urlc, UTF8.StringBody(resource));
- urlPayloadSize += resource.length();
- urlc++;
- }
- }
- }
- try {
- parts.put("urlc", UTF8.StringBody(Integer.toString(urlc)));
- // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/transferURL.html"), timeout, targetSeed.getHexHash() + ".yacyh", parts, gzipBody);
- final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
- final byte[] content =
- httpClient.POSTbytes(
- new MultiProtocolURI("http://" + address + "/yacy/transferURL.html"),
- targetSeed.getHexHash() + ".yacyh",
- parts,
- gzipBody);
- final Iterator<String> v = FileUtils.strings(content);
-
- final Map<String, String> result = FileUtils.table(v);
- // return the transfered url data in bytes (for debugging only)
- result.put("urlPayloadSize", Integer.toString(urlPayloadSize));
- return result;
- } catch ( final Exception e ) {
- Network.log.logWarning("yacyClient.transferURL to " + address + " error: " + e.getMessage());
- return null;
- }
- }
-
- public static Map<String, String> getProfile(final Seed targetSeed) {
- // ReferenceContainerCache<HostReference> ref = loadIDXHosts(targetSeed);
-
- // this post a message to the remote message board
- final String salt = crypt.randomSalt();
-
- String address = targetSeed.getClusterAddress();
- if ( address == null ) {
- address = "localhost:8090";
- }
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), targetSeed.hash, salt);
- // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/profile.html"), 5000, targetSeed.getHexHash() + ".yacyh", parts);
- final HTTPClient httpclient = new HTTPClient(ClientIdentification.getUserAgent(), 15000);
- final byte[] content =
- httpclient.POSTbytes(
- new MultiProtocolURI("http://" + address + "/yacy/profile.html"),
- targetSeed.getHexHash() + ".yacyh",
- parts,
- false);
- return FileUtils.table(content);
- } catch ( final Exception e ) {
- Network.log.logWarning("yacyClient.getProfile error:" + e.getMessage());
- return null;
- }
- }
-
- public static ReferenceContainerCache<HostReference> loadIDXHosts(final Seed target) {
- final ReferenceContainerCache<HostReference> index =
- new ReferenceContainerCache<HostReference>(
- WebStructureGraph.hostReferenceFactory,
- Base64Order.enhancedCoder,
- 6);
- // check if the host supports this protocol
- if ( target.getRevision() < migration.IDX_HOST ) {
- // if the protocol is not supported then we just return an empty host reference container
- return index;
- }
-
- // prepare request
- final String salt = crypt.randomSalt();
-
- // send request
- try {
- final Map<String, ContentBody> parts =
- basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
- parts.put("object", UTF8.StringBody("host"));
- final byte[] content = postToFile(target, "idx.json", parts, 30000);
- if ( content == null || content.length == 0 ) {
- Network.log.logWarning("yacyClient.loadIDXHosts error: empty result");
- return null;
- }
- final JSONObject json =
- new JSONObject(new JSONTokener(new InputStreamReader(new ByteArrayInputStream(content))));
- /* the json has the following form:
- {
- "version":"#[version]#",
- "uptime":"#[uptime]#",
- "name":"#[name]#",
- "rowdef":"#[rowdef]#",
- "idx":{
- #{list}#"#[term]#":[#[references]#]#(comma)#::,#(/comma)#
- #{/list}#
- }
- }
- */
- final JSONObject idx = json.getJSONObject("idx");
- // iterate over all references
- final Iterator<String> termIterator = idx.keys();
- String term;
- while ( termIterator.hasNext() ) {
- term = termIterator.next();
- final JSONArray references = idx.getJSONArray(term);
- // iterate until we get an exception or null
- int c = 0;
- String reference;
- final ReferenceContainer<HostReference> referenceContainer =
- new ReferenceContainer<HostReference>(
- WebStructureGraph.hostReferenceFactory,
- UTF8.getBytes(term));
- try {
- while ( (reference = references.getString(c++)) != null ) {
- //System.out.println("REFERENCE: " + reference);
- referenceContainer.add(new HostReference(reference));
- }
- } catch ( final JSONException e ) {
- } // this finishes the iteration
- index.add(referenceContainer);
- }
- return index;
- } catch ( final Exception e ) {
- Network.log.logWarning("yacyClient.loadIDXHosts error:" + e.getMessage());
- return index;
- }
- }
-
- public static final boolean authentifyRequest(final serverObjects post, final serverSwitch env) {
- if ( post == null || env == null ) {
- return false;
- }
-
- // identify network
- final String unitName = post.get(SwitchboardConstants.NETWORK_NAME, Seed.DFLT_NETWORK_UNIT); // the network unit
- if ( !unitName.equals(env.getConfig(SwitchboardConstants.NETWORK_NAME, Seed.DFLT_NETWORK_UNIT)) ) {
- return false;
- }
-
- // check authentication method
- final String authenticationControl = env.getConfig("network.unit.protocol.control", "uncontrolled");
- if ( authenticationControl.equals("uncontrolled") ) {
- return true;
- }
- final String authenticationMethod =
- env.getConfig("network.unit.protocol.request.authentication.method", "");
- if ( authenticationMethod.isEmpty() ) {
- return false;
- }
- if ( authenticationMethod.equals("salted-magic-sim") ) {
- // authorize the peer using the md5-magic
- final String salt = post.get("key", "");
- final String iam = post.get("iam", "");
- final String magic = env.getConfig("network.unit.protocol.request.authentication.essentials", "");
- final String md5 = Digest.encodeMD5Hex(salt + iam + magic);
- return post.get("magicmd5", "").equals(md5);
- }
-
- // unknown authentication method
- return false;
- }
-
- private static final LinkedHashMap<String, ContentBody> basicRequestParts(
- final Switchboard sb,
- final String targetHash,
- final String salt) {
- // put in all the essentials for routing and network authentication
- // generate a session key
- final LinkedHashMap<String, ContentBody> parts =
- basicRequestParts(
- sb.peers.mySeed().hash,
- targetHash,
- Switchboard.getSwitchboard().getConfig(
- SwitchboardConstants.NETWORK_NAME,
- Seed.DFLT_NETWORK_UNIT));
- parts.put("key", UTF8.StringBody(salt));
-
- // authentication essentials
- final String authenticationControl = sb.getConfig("network.unit.protocol.control", "uncontrolled");
- final String authenticationMethod =
- sb.getConfig("network.unit.protocol.request.authentication.method", "");
- if ( (authenticationControl.equals("controlled")) && (authenticationMethod.length() > 0) ) {
- if ( authenticationMethod.equals("salted-magic-sim") ) {
- // generate an authentication essential using the salt, the iam-hash and the network magic
- final String magic =
- sb.getConfig("network.unit.protocol.request.authentication.essentials", "");
- final String md5 = Digest.encodeMD5Hex(salt + sb.peers.mySeed().hash + magic);
- parts.put("magicmd5", UTF8.StringBody(md5));
- }
- }
-
- return parts;
- }
-
- private static final LinkedHashMap<String, ContentBody> basicRequestParts(
- final String myHash,
- final String targetHash,
- final String networkName) {
- // put in all the essentials for routing and network authentication
- // generate a session key
- final LinkedHashMap<String, ContentBody> parts = new LinkedHashMap<String, ContentBody>();
-
- // just standard identification essentials
- if ( myHash != null ) {
- parts.put("iam", UTF8.StringBody(myHash));
- if ( targetHash != null ) {
- parts.put("youare", UTF8.StringBody(targetHash));
- }
-
- // time information for synchronization
- // use our own formatter to prevent concurrency locks with other processes
- final GenericFormatter my_SHORT_SECOND_FORMATTER =
- new GenericFormatter(GenericFormatter.FORMAT_SHORT_SECOND, GenericFormatter.time_second);
- parts.put("mytime", UTF8.StringBody(my_SHORT_SECOND_FORMATTER.format()));
- parts.put("myUTC", UTF8.StringBody(Long.toString(System.currentTimeMillis())));
-
- // network identification
- parts.put(SwitchboardConstants.NETWORK_NAME, UTF8.StringBody(networkName));
- }
-
- return parts;
- }
-
+// yacyClient.java
+// -------------------------------------
+// (C) by Michael Peter Christen; [email protected]
+// first published on http://www.anomic.de
+// Frankfurt, Germany, 2004
+//
+// $LastChangedDate$
+// $LastChangedRevision$
+// $LastChangedBy$
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// Using this software in any meaning (reading, learning, copying, compiling,
+// running) means that you agree that the Author(s) is (are) not responsible
+// for cost, loss of data or any harm that may be caused directly or indirectly
+// by usage of this softare or this documentation. The usage of this software
+// is on your own risk. The installation and usage (starting/running) of this
+// software may allow other people or application to access your computer and
+// any attached devices and is highly dependent on the configuration of the
+// software which must be done by the user of the software; the author(s) is
+// (are) also not responsible for proper configuration and usage of the
+// software, even if provoked by documentation provided together with
+// the software.
+//
+// Any changes to this file according to the GPL as documented in the file
+// gpl.txt aside this file in the shipment you received can be done to the
+// lines that follows this copyright notice here, but changes must not be
+// done inside the copyright notice above. A re-distribution must contain
+// the intact and unchanged copyright notice.
+// Contributions and changes to the program code must be marked as such.
+
+package net.yacy.peers;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import net.yacy.migration;
+import net.yacy.cora.date.GenericFormatter;
+import net.yacy.cora.document.ASCII;
+import net.yacy.cora.document.JSONArray;
+import net.yacy.cora.document.JSONException;
+import net.yacy.cora.document.JSONObject;
+import net.yacy.cora.document.JSONTokener;
+import net.yacy.cora.document.MultiProtocolURI;
+import net.yacy.cora.document.RSSFeed;
+import net.yacy.cora.document.RSSMessage;
+import net.yacy.cora.document.RSSReader;
+import net.yacy.cora.document.UTF8;
+import net.yacy.cora.federate.opensearch.SRURSSConnector;
+import net.yacy.cora.federate.solr.connector.RemoteSolrConnector;
+import net.yacy.cora.federate.solr.connector.SolrConnector;
+import net.yacy.cora.federate.solr.instance.RemoteInstance;
+import net.yacy.cora.federate.yacy.CacheStrategy;
+import net.yacy.cora.order.Base64Order;
+import net.yacy.cora.order.Digest;
+import net.yacy.cora.protocol.ClientIdentification;
+import net.yacy.cora.protocol.Domains;
+import net.yacy.cora.protocol.http.HTTPClient;
+import net.yacy.cora.sorting.ClusteredScoreMap;
+import net.yacy.cora.sorting.ReversibleScoreMap;
+import net.yacy.cora.storage.HandleSet;
+import net.yacy.cora.util.SpaceExceededException;
+import net.yacy.crawler.data.ResultURLs;
+import net.yacy.crawler.data.ResultURLs.EventOrigin;
+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.WordReferenceFactory;
+import net.yacy.kelondro.logging.Log;
+import net.yacy.kelondro.rwi.Reference;
+import net.yacy.kelondro.rwi.ReferenceContainer;
+import net.yacy.kelondro.rwi.ReferenceContainerCache;
+import net.yacy.kelondro.util.ByteBuffer;
+import net.yacy.kelondro.util.FileUtils;
+import net.yacy.peers.graphics.ProfilingGraph;
+import net.yacy.peers.graphics.WebStructureGraph;
+import net.yacy.peers.graphics.WebStructureGraph.HostReference;
+import net.yacy.peers.operation.yacyVersion;
+import net.yacy.repository.Blacklist;
+import net.yacy.repository.Blacklist.BlacklistType;
+import net.yacy.search.EventTracker;
+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.schema.CollectionSchema;
+import net.yacy.search.snippet.TextSnippet;
+import net.yacy.server.serverCore;
+import net.yacy.server.serverObjects;
+import net.yacy.server.serverSwitch;
+import net.yacy.utils.crypt;
+
+import org.apache.http.entity.mime.content.ContentBody;
+import org.apache.solr.client.solrj.SolrQuery;
+import org.apache.solr.client.solrj.response.FacetField;
+import org.apache.solr.client.solrj.response.QueryResponse;
+import org.apache.solr.client.solrj.response.FacetField.Count;
+import org.apache.solr.common.SolrDocument;
+import org.apache.solr.common.SolrDocumentList;
+import org.apache.solr.common.params.FacetParams;
+
+
+public final class Protocol {
+
+ private static byte[] postToFile(
+ final Seed target,
+ final String filename,
+ final Map<String, ContentBody> parts,
+ final int timeout) throws IOException {
+ return postToFile(target.getClusterAddress(), target.hash, filename, parts, timeout);
+ }
+
+ private static byte[] postToFile(
+ final SeedDB seedDB,
+ final String targetHash,
+ final String filename,
+ final Map<String, ContentBody> parts,
+ final int timeout) throws IOException {
+ return postToFile(seedDB.targetAddress(targetHash), targetHash, filename, parts, timeout);
+ }
+
+ private static byte[] postToFile(
+ final String targetAddress,
+ final String targetPeerHash,
+ final String filename,
+ final Map<String, ContentBody> parts,
+ final int timeout) throws IOException {
+ final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
+ return httpClient.POSTbytes(
+ new MultiProtocolURI("http://" + targetAddress + "/yacy/" + filename),
+ Seed.b64Hash2hexHash(targetPeerHash) + ".yacyh",
+ parts,
+ false);
+ }
+
+ /**
+ * this is called to enrich the seed information by - own address (if peer is behind a nat/router) - check
+ * peer type (virgin/junior/senior/principal) to do this, we send a 'Hello' to another peer this carries
+ * the following information: 'iam' - own hash 'youare' - remote hash, to verify that we are correct 'key'
+ * - a session key that the remote peer may use to answer and the own seed string we expect the following
+ * information to be send back: - 'yourip' the ip of the connection peer (we) - 'yourtype' the type of
+ * this peer that the other peer checked by asking for a specific word and the remote seed string one
+ * exceptional failure case is when we know the other's peers hash, the other peers responds correctly but
+ * they appear to be another peer by comparisment of the other peer's hash this works of course only if we
+ * know the other peer's hash.
+ *
+ * @return the number of new seeds
+ */
+ public static int hello(
+ final Seed mySeed,
+ final PeerActions peerActions,
+ final String address,
+ final String otherHash,
+ final String otherName) {
+
+ Map<String, String> result = null;
+ final String salt = crypt.randomSalt();
+ long responseTime = Long.MAX_VALUE;
+ byte[] content = null;
+ try {
+ // generate request
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), null, salt);
+ parts.put("count", UTF8.StringBody("20"));
+ parts.put("magic", UTF8.StringBody(Long.toString(Network.magic)));
+ parts.put("seed", UTF8.StringBody(mySeed.genSeedStr(salt)));
+ // send request
+ final long start = System.currentTimeMillis();
+ // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/hello.html"), 30000, yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", parts);
+ final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 30000);
+ content =
+ httpClient.POSTbytes(
+ new MultiProtocolURI("http://" + address + "/yacy/hello.html"),
+ Seed.b64Hash2hexHash(otherHash) + ".yacyh",
+ parts,
+ false);
+ responseTime = System.currentTimeMillis() - start;
+ result = FileUtils.table(content);
+ } catch ( final Exception e ) {
+ if ( Thread.currentThread().isInterrupted() ) {
+ Network.log.logInfo("yacyClient.hello thread '"
+ + Thread.currentThread().getName()
+ + "' interrupted.");
+ return -1;
+ }
+ Network.log.logInfo("yacyClient.hello thread '"
+ + Thread.currentThread().getName()
+ + "', peer "
+ + address
+ + "; exception: "
+ + e.getMessage());
+ // try again (go into loop)
+ result = null;
+ }
+
+ if (result == null || result.size() == 0) {
+ Network.log.logInfo("yacyClient.hello result error: "
+ + ((result == null) ? "result null" : ("result=" + result.toString())));
+ return -1;
+ }
+ Network.log.logInfo("yacyClient.hello thread '"
+ + Thread.currentThread().getName()
+ + "' contacted peer at "
+ + address
+ + ", received "
+ + ((content == null) ? "null" : content.length)
+ + " bytes, time = "
+ + responseTime
+ + " milliseconds");
+
+ // check consistency with expectation
+ Seed otherPeer = null;
+ String seed;
+ if ( (otherHash != null) && (otherHash.length() > 0) && ((seed = result.get("seed0")) != null) ) {
+ if ( seed.length() > Seed.maxsize ) {
+ Network.log.logInfo("hello/client 0: rejected contacting seed; too large ("
+ + seed.length()
+ + " > "
+ + Seed.maxsize
+ + ")");
+ } else {
+ try {
+ final int p = address.indexOf(':');
+ if ( p < 0 ) {
+ return -1;
+ }
+ String h = address.substring(0, p);
+ InetAddress ie = Domains.dnsResolve(h);
+ final String host = ie == null ? h : ie.getHostAddress(); // hack to prevent NPEs
+ otherPeer = Seed.genRemoteSeed(seed, false, host);
+ if ( !otherPeer.hash.equals(otherHash) ) {
+ Network.log.logInfo("yacyClient.hello: consistency error: otherPeer.hash = "
+ + otherPeer.hash
+ + ", otherHash = "
+ + otherHash);
+ return -1; // no success
+ }
+ } catch ( final IOException e ) {
+ Network.log.logInfo("yacyClient.hello: consistency error: other seed bad:"
+ + e.getMessage()
+ + ", seed="
+ + seed);
+ return -1; // no success
+ }
+ }
+ }
+
+ // get access type response
+ String mytype = result.get(Seed.YOURTYPE);
+ if ( mytype == null ) {
+ mytype = "";
+ }
+
+ // set my own seed according to new information
+ // we overwrite our own IP number only
+ if ( serverCore.useStaticIP ) {
+ mySeed.setIP(Switchboard.getSwitchboard().myPublicIP());
+ } else {
+ final String myIP = result.get("yourip");
+ final String properIP = Seed.isProperIP(myIP);
+ mySeed.setFlagRootNode((mytype.equals(Seed.PEERTYPE_SENIOR) || mytype.equals(Seed.PEERTYPE_PRINCIPAL)) && responseTime < 1000 && Domains.isThisHostIP(myIP));
+ if ( properIP == null ) {
+ mySeed.setIP(myIP);
+ }
+ }
+
+ // change our seed-type
+ final Accessible accessible = new Accessible();
+ if ( mytype.equals(Seed.PEERTYPE_SENIOR) || mytype.equals(Seed.PEERTYPE_PRINCIPAL) ) {
+ accessible.IWasAccessed = true;
+ if ( mySeed.isPrincipal() ) {
+ mytype = Seed.PEERTYPE_PRINCIPAL;
+ }
+ } else {
+ accessible.IWasAccessed = false;
+ }
+ accessible.lastUpdated = System.currentTimeMillis();
+ Network.amIAccessibleDB.put(otherHash, accessible);
+
+ /*
+ * If we were reported as junior we have to check if your port forwarding channel is broken
+ * If this is true we try to reconnect the sch channel to the remote server now.
+ */
+ if ( mytype.equalsIgnoreCase(Seed.PEERTYPE_JUNIOR) ) {
+ Network.log.logInfo("yacyClient.hello: Peer '"
+ + ((otherPeer == null) ? "unknown" : otherPeer.getName())
+ + "' reported us as junior.");
+ } else if ( (mytype.equalsIgnoreCase(Seed.PEERTYPE_SENIOR))
+ || (mytype.equalsIgnoreCase(Seed.PEERTYPE_PRINCIPAL)) ) {
+ if ( Network.log.isFine() ) {
+ Network.log.logFine("yacyClient.hello: Peer '"
+ + ((otherPeer == null) ? "unknown" : otherPeer.getName())
+ + "' reported us as "
+ + mytype
+ + ", accepted other peer.");
+ }
+ } else {
+ // wrong type report
+ if ( Network.log.isFine() ) {
+ Network.log.logFine("yacyClient.hello: Peer '"
+ + ((otherPeer == null) ? "unknown" : otherPeer.getName())
+ + "' reported us as "
+ + mytype
+ + ", rejecting other peer.");
+ }
+ return -1;
+ }
+ if ( mySeed.orVirgin().equals(Seed.PEERTYPE_VIRGIN) ) {
+ mySeed.put(Seed.PEERTYPE, mytype);
+ }
+
+ final String error = mySeed.isProper(true);
+ if ( error != null ) {
+ Network.log.logWarning("yacyClient.hello mySeed error - not proper: " + error);
+ return -1;
+ }
+
+ //final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time
+
+ // read the seeds that the peer returned and integrate them into own database
+ int i = 0;
+ int count = 0;
+ String seedStr;
+ Seed s;
+ final int connectedBefore = peerActions.sizeConnected();
+ while ( (seedStr = result.get("seed" + i++)) != null ) {
+ // integrate new seed into own database
+ // the first seed, "seed0" is the seed of the responding peer
+ if ( seedStr.length() > Seed.maxsize ) {
+ Network.log.logInfo("hello/client: rejected contacting seed; too large ("
+ + seedStr.length()
+ + " > "
+ + Seed.maxsize
+ + ")");
+ } else {
+ try {
+ if ( i == 1 ) {
+ final int p = address.indexOf(':');
+ if ( p < 0 ) {
+ return -1;
+ }
+ InetAddress ia = Domains.dnsResolve(address.substring(0, p));
+ if (ia == null) continue;
+ final String host = ia.getHostAddress();
+ s = Seed.genRemoteSeed(seedStr, false, host);
+ } else {
+ s = Seed.genRemoteSeed(seedStr, false, null);
+ }
+ if ( peerActions.peerArrival(s, (i == 1)) ) {
+ count++;
+ }
+ } catch ( final IOException e ) {
+ Network.log.logInfo("hello/client: rejected contacting seed; bad ("
+ + e.getMessage()
+ + ")");
+ }
+ }
+ }
+ final int connectedAfter = peerActions.sizeConnected();
+
+ // update event tracker
+ EventTracker.update(EventTracker.EClass.PEERPING, new ProfilingGraph.EventPing(
+ mySeed.getName(),
+ otherName,
+ true,
+ connectedAfter - connectedBefore), false);
+
+ return count;
+ }
+
+ public static Seed querySeed(final Seed target, final String seedHash) {
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // send request
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
+ parts.put("object", UTF8.StringBody("seed"));
+ parts.put("env", UTF8.StringBody(seedHash));
+ final byte[] content = postToFile(target, "query.html", parts, 10000);
+ final Map<String, String> result = FileUtils.table(content);
+
+ if ( result == null || result.isEmpty() ) {
+ return null;
+ }
+ //final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time
+ return Seed.genRemoteSeed(result.get("response"), false, target.getIP());
+ } catch ( final Exception e ) {
+ Network.log.logWarning("yacyClient.querySeed error:" + e.getMessage());
+ return null;
+ }
+ }
+
+ public static int queryRWICount(final Seed target, final String wordHash) {
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // send request
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
+ parts.put("object", UTF8.StringBody("rwicount"));
+ parts.put("ttl", UTF8.StringBody("0"));
+ parts.put("env", UTF8.StringBody(wordHash));
+ final byte[] content = postToFile(target, "query.html", parts, 6000);
+ final Map<String, String> result = FileUtils.table(content);
+
+ if ( result == null || result.isEmpty() ) {
+ return -1;
+ }
+ return Integer.parseInt(result.get("response"));
+ } catch ( final Exception e ) {
+ Network.log.logWarning("yacyClient.queryRWICount error:" + e.getMessage());
+ return -1;
+ }
+ }
+
+ /**
+ * check the status of a remote peer
+ *
+ * @param target
+ * @return an array of two long: [0] is the count of urls, [1] is a magic
+ */
+ public static long[] queryUrlCount(final Seed target) {
+ if ( target == null ) {
+ return new long[] {
+ -1, -1
+ };
+ }
+
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // send request
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
+ parts.put("object", UTF8.StringBody("lurlcount"));
+ parts.put("ttl", UTF8.StringBody("0"));
+ parts.put("env", UTF8.StringBody(""));
+ final byte[] content = postToFile(target, "query.html", parts, 6000);
+ final Map<String, String> result = FileUtils.table(content);
+
+ if ( result == null || result.isEmpty() ) {
+ return new long[] {
+ -1, -1
+ };
+ }
+ final String resp = result.get("response");
+ if ( resp == null ) {
+ return new long[] {
+ -1, -1
+ };
+ }
+ String magic = result.get("magic");
+ if ( magic == null ) {
+ magic = "0";
+ }
+ try {
+ return new long[] {
+ Long.parseLong(resp), Long.parseLong(magic)
+ };
+ } catch ( final NumberFormatException e ) {
+ return new long[] {
+ -1, -1
+ };
+ }
+ } catch ( final IOException e ) {
+ if ( Network.log.isFine() ) {
+ Network.log.logFine("yacyClient.queryUrlCount error asking peer '"
+ + target.getName()
+ + "':"
+ + e.toString());
+ }
+ return new long[] {
+ -1, -1
+ };
+ }
+ }
+
+ public static RSSFeed queryRemoteCrawlURLs(
+ final SeedDB seedDB,
+ final Seed target,
+ final int maxCount,
+ final long maxTime) {
+ // returns a list of
+ if ( target == null ) {
+ return null;
+ }
+ final int targetCount = Integer.parseInt(target.get(Seed.RCOUNT, "0"));
+ if ( targetCount <= 0 ) {
+ Network.log.logWarning("yacyClient.queryRemoteCrawlURLs wrong peer '"
+ + target.getName()
+ + "' selected: not enough links available");
+ return null;
+ }
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // send request
+ try {
+ /* a long time-out is needed */
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
+ parts.put("call", UTF8.StringBody("remotecrawl"));
+ parts.put("count", UTF8.StringBody(Integer.toString(maxCount)));
+ parts.put("time", UTF8.StringBody(Long.toString(maxTime)));
+ // final byte[] result = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/urls.xml"), (int) maxTime, target.getHexHash() + ".yacyh", parts);
+ final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), (int) maxTime);
+ final byte[] result =
+ httpClient.POSTbytes(new MultiProtocolURI("http://"
+ + target.getClusterAddress()
+ + "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false);
+ final RSSReader reader = RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, result);
+ if ( reader == null ) {
+ Network.log.logWarning("yacyClient.queryRemoteCrawlURLs failed asking peer '"
+ + target.getName()
+ + "': probably bad response from remote peer (1), reader == null");
+ target.put(Seed.RCOUNT, "0");
+ seedDB.update(target.hash, target); // overwrite number of remote-available number to avoid that this peer is called again (until update is done by peer ping)
+ //Log.logException(e);
+ return null;
+ }
+ final RSSFeed feed = reader.getFeed();
+ if ( feed == null ) {
+ // case where the rss reader does not understand the content
+ Network.log.logWarning("yacyClient.queryRemoteCrawlURLs failed asking peer '"
+ + target.getName()
+ + "': probably bad response from remote peer (2)");
+ //System.out.println("***DEBUG*** rss input = " + UTF8.String(result));
+ target.put(Seed.RCOUNT, "0");
+ seedDB.update(target.hash, target); // overwrite number of remote-available number to avoid that this peer is called again (until update is done by peer ping)
+ //Log.logException(e);
+ return null;
+ }
+ // update number of remotely available links in seed
+ target.put(Seed.RCOUNT, Integer.toString(Math.max(0, targetCount - feed.size())));
+ seedDB.update(target.hash, target);
+ return feed;
+ } catch ( final IOException e ) {
+ Network.log.logWarning("yacyClient.queryRemoteCrawlURLs error asking peer '"
+ + target.getName()
+ + "':"
+ + e.toString());
+ return null;
+ }
+ }
+
+ public static RSSFeed search(
+ final Seed targetSeed,
+ final String query,
+ final CacheStrategy verify,
+ final boolean global,
+ final long timeout,
+ final int startRecord,
+ final int maximumRecords) throws IOException {
+ final String address =
+ (targetSeed == null || targetSeed == Switchboard.getSwitchboard().peers.mySeed()) ? "localhost:"
+ + Switchboard.getSwitchboard().getConfig("port", "8090") : targetSeed.getClusterAddress();
+ final String urlBase = "http://" + address + "/yacysearch.rss";
+ return SRURSSConnector.loadSRURSS(
+ urlBase,
+ query,
+ timeout,
+ startRecord,
+ maximumRecords,
+ verify,
+ global,
+ null);
+ }
+
+ protected static int primarySearch(
+ final SearchEvent event,
+ final String wordhashes,
+ final String excludehashes,
+ final String language,
+ final String contentdom,
+ final int count,
+ final long time,
+ final int maxDistance,
+ final int partitions,
+ final Seed target,
+ final SecondarySearchSuperviser secondarySearchSuperviser,
+ final Blacklist blacklist) {
+ // send a search request to peer with remote Hash
+
+ // INPUT:
+ // iam : complete seed of the requesting peer
+ // youare : seed hash of the target peer, used for testing network stability
+ // key : transmission key for response
+ // search : a list of search words
+ // hsearch : a string of word hashes
+ // fwdep : forward depth. if "0" then peer may NOT ask another peer for more results
+ // fwden : forward deny, a list of seed hashes. They may NOT be target of forward hopping
+ // count : maximum number of wanted results
+ // global : if "true", then result may consist of answers from other peers
+ // partitions : number of remote peers that are asked (for evaluation of QPM)
+ // duetime : maximum time that a peer should spent to create a result
+
+ final long timestamp = System.currentTimeMillis();
+ event.addExpectedRemoteReferences(count);
+ SearchResult result;
+ try {
+ result =
+ new SearchResult(
+ event,
+ basicRequestParts(Switchboard.getSwitchboard(), target.hash, crypt.randomSalt()),
+ wordhashes,
+ excludehashes,
+ "",
+ language,
+ contentdom,
+ count,
+ time,
+ maxDistance,
+ partitions,
+ target.getHexHash() + ".yacyh",
+ target.getClusterAddress(),
+ secondarySearchSuperviser
+ );
+ } catch ( final IOException e ) {
+ Network.log.logInfo("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + ")");
+ event.peers.peerActions.peerDeparture(target, "search request to peer created io exception: " + e.getMessage());
+ return -1;
+ }
+ // computation time
+ final long totalrequesttime = System.currentTimeMillis() - timestamp;
+
+ try {
+ remoteSearchProcess(event, count, totalrequesttime, wordhashes, target, blacklist, result);
+ } catch (SpaceExceededException e) {
+ Log.logException(e);
+ return -1;
+ }
+
+ // read index abstract
+ if ( secondarySearchSuperviser != null ) {
+ String wordhash;
+ String whacc = "";
+ ByteBuffer ci;
+ int ac = 0;
+ for ( final Map.Entry<byte[], String> abstractEntry : result.indexabstract.entrySet() ) {
+ try {
+ ci = new ByteBuffer(abstractEntry.getValue());
+ wordhash = ASCII.String(abstractEntry.getKey());
+ } catch ( final OutOfMemoryError e ) {
+ Log.logException(e);
+ continue;
+ }
+ whacc += wordhash;
+ secondarySearchSuperviser.addAbstract(
+ wordhash,
+ WordReferenceFactory.decompressIndex(ci, target.hash));
+ ac++;
+
+ }
+ if ( ac > 0 ) {
+ secondarySearchSuperviser.commitAbstract();
+ Network.log.logInfo("remote search: peer " + target.getName() + " sent " + ac + " index abstracts for words " + whacc);
+ }
+ }
+ return result.urlcount;
+ }
+
+ protected static int secondarySearch(
+ final SearchEvent event,
+ final String wordhashes,
+ final String urlhashes,
+ final String contentdom,
+ final int count,
+ final long time,
+ final int maxDistance,
+ final int partitions,
+ final Seed target,
+ final Blacklist blacklist) {
+
+ final long timestamp = System.currentTimeMillis();
+ event.addExpectedRemoteReferences(count);
+ SearchResult result;
+ try {
+ result =
+ new SearchResult(
+ event,
+ basicRequestParts(Switchboard.getSwitchboard(), target.hash, crypt.randomSalt()),
+ wordhashes,
+ "",
+ urlhashes,
+ "",
+ contentdom,
+ count,
+ time,
+ maxDistance,
+ partitions,
+ target.getHexHash() + ".yacyh",
+ target.getClusterAddress(),
+ null
+ );
+ } catch ( final IOException e ) {
+ Network.log.logInfo("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + ")");
+ event.peers.peerActions.peerDeparture(target, "search request to peer created io exception: " + e.getMessage());
+ return -1;
+ }
+ // computation time
+ final long totalrequesttime = System.currentTimeMillis() - timestamp;
+
+ try {
+ remoteSearchProcess(event, count, totalrequesttime, wordhashes, target, blacklist, result);
+ } catch (SpaceExceededException e) {
+ Log.logException(e);
+ return -1;
+ }
+ return result.urlcount;
+ }
+
+ private static void remoteSearchProcess(
+ final SearchEvent event,
+ final int count,
+ final long time,
+ final String wordhashes,
+ final Seed target,
+ final Blacklist blacklist,
+ final SearchResult result
+ ) throws SpaceExceededException {
+
+ // create containers
+ final int words = wordhashes.length() / Word.commonHashLength;
+ assert words > 0 : "wordhashes = " + wordhashes;
+ final List<ReferenceContainer<WordReference>> container = new ArrayList<ReferenceContainer<WordReference>>(words);
+ for ( int i = 0; i < words; i++ ) {
+ container.add(ReferenceContainer.emptyContainer(
+ Segment.wordReferenceFactory,
+ ASCII.getBytes(wordhashes.substring(i * Word.commonHashLength, (i + 1) * Word.commonHashLength)),
+ count)); // throws SpaceExceededException
+ }
+
+ // insert results to containers
+ int term = count;
+ for ( final URIMetadataRow urlEntry : result.links ) {
+ if ( term-- <= 0 ) {
+ break; // do not process more that requested (in case that evil peers fill us up with rubbish)
+ }
+ // get one single search result
+ if ( urlEntry == null ) {
+ continue;
+ }
+ assert (urlEntry.hash().length == 12) : "urlEntry.hash() = " + ASCII.String(urlEntry.hash());
+ if ( urlEntry.hash().length != 12 ) {
+ continue; // bad url hash
+ }
+ if ( blacklist.isListed(BlacklistType.SEARCH, urlEntry) ) {
+ if ( Network.log.isInfo() ) {
+ Network.log.logInfo("remote search: filtered blacklisted url " + urlEntry.url() + " from peer " + target.getName());
+ }
+ continue; // block with backlist
+ }
+
+ final String urlRejectReason =
+ Switchboard.getSwitchboard().crawlStacker.urlInAcceptedDomain(urlEntry.url());
+ if ( urlRejectReason != null ) {
+ if ( Network.log.isInfo() ) {
+ Network.log.logInfo("remote search: rejected url '" + urlEntry.url() + "' (" + urlRejectReason + ") from peer " + target.getName());
+ }
+ continue; // reject url outside of our domain
+ }
+
+ // save the url entry
+ final Reference entry = urlEntry.word();
+ if ( entry == null ) {
+ if ( Network.log.isWarning() ) {
+ Network.log.logWarning("remote search: no word attached from peer " + target.getName() + ", version " + target.getVersion());
+ }
+ continue; // no word attached
+ }
+
+ // the search-result-url transports all the attributes of word indexes
+ if ( !Base64Order.enhancedCoder.equal(entry.urlhash(), urlEntry.hash()) ) {
+ Network.log.logInfo("remote search: url-hash " + ASCII.String(urlEntry.hash()) + " does not belong to word-attached-hash " + ASCII.String(entry.urlhash()) + "; url = " + urlEntry.url() + " from peer " + target.getName());
+ continue; // spammed
+ }
+
+ // passed all checks, store url
+ try {
+ event.query.getSegment().fulltext().putMetadata(urlEntry);
+ ResultURLs.stack(
+ ASCII.String(urlEntry.url().hash()),
+ urlEntry.url().getHost(),
+ event.peers.mySeed().hash.getBytes(),
+ UTF8.getBytes(target.hash),
+ EventOrigin.QUERIES);
+ } catch ( final IOException e ) {
+ Network.log.logWarning("could not store search result", e);
+ continue; // db-error
+ }
+
+ if ( urlEntry.snippet() != null
+ && urlEntry.snippet().length() > 0
+ && !urlEntry.snippet().equals("null") ) {
+ // we don't store the snippets along the url entry,
+ // because they are search-specific.
+ // instead, they are placed in a snipped-search cache.
+ // System.out.println("--- RECEIVED SNIPPET '" + urlEntry.snippet() + "'");
+ TextSnippet.snippetsCache.put(wordhashes, ASCII.String(urlEntry.hash()), urlEntry.snippet());
+ }
+
+ // add the url entry to the word indexes
+ for ( final ReferenceContainer<WordReference> c : container ) {
+ try {
+ c.add(entry);
+ } catch ( final SpaceExceededException e ) {
+ Log.logException(e);
+ break;
+ }
+ }
+ }
+
+ // store remote result to local result container
+ // insert one container into the search result buffer
+ // one is enough, only the references are used, not the word
+ event.rankingProcess.add(container.get(0), false, target.getName() + "/" + target.hash, result.joincount, time);
+ event.rankingProcess.addFinalize();
+ event.addExpectedRemoteReferences(-count);
+
+ // insert the containers to the index
+ for ( final ReferenceContainer<WordReference> c : container ) {
+ try {
+ event.query.getSegment().storeRWI(c);
+ } catch ( final Exception e ) {
+ Log.logException(e);
+ }
+ }
+
+ // integrate remote top-words/topics
+ if ( result.references != null && result.references.length > 0 ) {
+ Network.log.logInfo("remote search: peer " + target.getName() + " sent " + result.references.length + " topics");
+ // add references twice, so they can be counted (must have at least 2 entries)
+ synchronized ( event.rankingProcess ) {
+ event.rankingProcess.addTopic(result.references);
+ event.rankingProcess.addTopic(result.references);
+ }
+ }
+ Network.log.logInfo("remote search: peer " + target.getName() + " sent " + container.get(0).size() + "/" + result.joincount + " references");
+ }
+
+ private static class SearchResult {
+ public int urlcount; // number of returned LURL's for this search
+ public int joincount; //
+ public Map<byte[], Integer> indexcount; //
+ public long searchtime; // time that the peer actually spent to create the result
+ public String[] references; // search hints, the top-words
+ public List<URIMetadataRow> links; // LURLs of search
+ public Map<byte[], String> indexabstract; // index abstracts, a collection of url-hashes per word
+
+ public SearchResult(
+ final SearchEvent event,
+ final Map<String, ContentBody> parts,
+ final String wordhashes,
+ final String excludehashes,
+ final String urlhashes,
+ final String language,
+ final String contentdom,
+ final int count,
+ final long time,
+ final int maxDistance,
+ final int partitions,
+ final String hostname,
+ final String hostaddress,
+ final SecondarySearchSuperviser secondarySearchSuperviser
+ ) throws IOException {
+ // send a search request to peer with remote Hash
+
+ //if (hostaddress.equals(mySeed.getClusterAddress())) hostaddress = "127.0.0.1:" + mySeed.getPort(); // for debugging
+
+ // INPUT:
+ // iam : complete seed of the requesting peer
+ // youare : seed hash of the target peer, used for testing network stability
+ // key : transmission key for response
+ // search : a list of search words
+ // hsearch : a string of word hashes
+ // fwdep : forward depth. if "0" then peer may NOT ask another peer for more results
+ // fwden : forward deny, a list of seed hashes. They may NOT be target of forward hopping
+ // count : maximum number of wanted results
+ // global : if "true", then result may consist of answers from other peers
+ // partitions : number of remote peers that are asked (for evaluation of QPM)
+ // duetime : maximum time that a peer should spent to create a result
+
+ // send request
+ Map<String, String> resultMap = null;
+ String key = "";
+ final ContentBody keyBody = parts.get("key");
+ if ( keyBody != null ) {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream(20);
+ keyBody.writeTo(baos);
+ key = baos.toString();
+ }
+
+ String filter = event.query.urlMask.pattern().toString();
+ if (event.query.tld != null) filter = ".*" + event.query.tld + ".*" + filter;
+ if (event.query.modifier.protocol != null) filter = ".*" + event.query.modifier.protocol + ".*" + filter;
+ if (event.query.modifier.filetype != null) filter = filter + ".*" + event.query.modifier.filetype + ".*";
+ parts.put("myseed", UTF8.StringBody((event.peers.mySeed() == null) ? "" : event.peers.mySeed().genSeedStr(key)));
+ parts.put("count", UTF8.StringBody(Integer.toString(Math.max(10, count))));
+ parts.put("time", UTF8.StringBody(Long.toString(Math.max(3000, time))));
+ parts.put("partitions", UTF8.StringBody(Integer.toString(partitions)));
+ parts.put("query", UTF8.StringBody(wordhashes));
+ parts.put("exclude", UTF8.StringBody(excludehashes));
+ parts.put("duetime", UTF8.StringBody("1000"));
+ parts.put("urls", UTF8.StringBody(urlhashes));
+ parts.put("prefer", UTF8.StringBody(event.query.prefer.pattern()));
+ parts.put("filter", UTF8.StringBody(filter));
+ parts.put("modifier", UTF8.StringBody(event.query.modifier.toString()));
+ parts.put("language", UTF8.StringBody(language));
+ parts.put("sitehash", UTF8.StringBody(event.query.modifier.sitehash));
+ parts.put("author", UTF8.StringBody(event.query.modifier.author));
+ parts.put("contentdom", UTF8.StringBody(contentdom));
+ parts.put("ttl", UTF8.StringBody("0"));
+ parts.put("maxdist", UTF8.StringBody(Integer.toString(maxDistance)));
+ parts.put("profile", UTF8.StringBody(crypt.simpleEncode(event.query.ranking.toExternalString())));
+ parts.put("constraint", UTF8.StringBody((event.query.constraint == null) ? "" : event.query.constraint.exportB64()));
+ if ( secondarySearchSuperviser != null ) {
+ parts.put("abstracts", UTF8.StringBody("auto"));
+ // resultMap = FileUtils.table(HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + hostaddress + "/yacy/search.html"), 60000, hostname, parts));
+ //resultMap = FileUtils.table(HTTPConnector.getConnector(MultiProtocolURI.crawlerUserAgent).post(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/search.html"), 60000, target.getHexHash() + ".yacyh", parts));
+ }
+
+ final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 8000);
+ byte[] a = httpClient.POSTbytes(new MultiProtocolURI("http://" + hostaddress + "/yacy/search.html"), hostname, parts, false);
+ if (a != null && a.length > 200000) {
+ // there is something wrong. This is too large, maybe a hack on the other side?
+ a = null;
+ }
+ resultMap = FileUtils.table(a);
+
+ // evaluate request result
+ if ( resultMap == null || resultMap.isEmpty() ) {
+ throw new IOException("resultMap is NULL");
+ }
+ try {
+ this.searchtime = Integer.parseInt(resultMap.get("searchtime"));
+ } catch ( final NumberFormatException e ) {
+ throw new IOException("wrong output format for searchtime: "
+ + e.getMessage()
+ + ", map = "
+ + resultMap.toString());
+ }
+ try {
+ this.joincount = Integer.parseInt(resultMap.get("joincount")); // the complete number of hits at remote site
+ } catch ( final NumberFormatException e ) {
+ throw new IOException("wrong output format for joincount: " + e.getMessage());
+ }
+ try {
+ this.urlcount = Integer.parseInt(resultMap.get("count")); // the number of hits that are returned in the result list
+ } catch ( final NumberFormatException e ) {
+ throw new IOException("wrong output format for count: " + e.getMessage());
+ }
+ // scan the result map for entries with special prefix
+ this.indexcount = new TreeMap<byte[], Integer>(Base64Order.enhancedCoder);
+ this.indexabstract = new TreeMap<byte[], String>(Base64Order.enhancedCoder);
+ for ( final Map.Entry<String, String> entry : resultMap.entrySet() ) {
+ if ( entry.getKey().startsWith("indexcount.") ) {
+ this.indexcount.put(
+ UTF8.getBytes(entry.getKey().substring(11)),
+ Integer.parseInt(entry.getValue()));
+ }
+ if ( entry.getKey().startsWith("indexabstract.") ) {
+ this.indexabstract.put(UTF8.getBytes(entry.getKey().substring(14)), entry.getValue());
+ }
+ }
+ this.references = resultMap.get("references").split(",");
+ this.links = new ArrayList<URIMetadataRow>(this.urlcount);
+ for ( int n = 0; n < this.urlcount; n++ ) {
+ // get one single search result
+ final String resultLine = resultMap.get("resource" + n);
+ if ( resultLine == null ) {
+ continue;
+ }
+ final URIMetadataRow urlEntry = URIMetadataRow.importEntry(resultLine);
+ if ( urlEntry == null ) {
+ continue;
+ }
+ this.links.add(urlEntry);
+ }
+ }
+ }
+
+ private final static CollectionSchema[] snippetFields = new CollectionSchema[]{CollectionSchema.h1_txt, CollectionSchema.h2_txt, CollectionSchema.text_t};
+
+ protected static int solrQuery(
+ final SearchEvent event,
+ final int offset,
+ final int count,
+ boolean getFacets,
+ final Seed target,
+ final Blacklist blacklist) {
+
+ if (event.query.getQueryGoal().getOriginalQueryString(false) == null || event.query.getQueryGoal().getOriginalQueryString(false).length() == 0) {
+ return -1; // we cannot query solr only with word hashes, there is no clear text string
+ }
+ event.addExpectedRemoteReferences(count);
+ final SolrQuery solrQuery = event.query.solrQuery();
+ solrQuery.setStart(offset);
+ solrQuery.setRows(count);
+
+ // set facet query attributes
+ if (getFacets && event.query.facetfields.size() > 0) {
+ solrQuery.setFacet(true);
+ solrQuery.setFacetLimit(event.query.maxfacets);
+ solrQuery.setFacetSort(FacetParams.FACET_SORT_COUNT);
+ for (String field: event.query.facetfields) solrQuery.addFacetField(field);
+ } else {
+ solrQuery.setFacet(false);
+ }
+
+ // set highlighting query attributes
+ solrQuery.setHighlight(true);
+ solrQuery.setHighlightFragsize(SearchEvent.SNIPPET_MAX_LENGTH);
+ //solrQuery.setHighlightRequireFieldMatch();
+ solrQuery.setHighlightSimplePost("</b>");
+ solrQuery.setHighlightSimplePre("<b>");
+ solrQuery.setHighlightSnippets(1);
+ for (CollectionSchema field: snippetFields) solrQuery.addHighlightField(field.getSolrFieldName());
+
+ boolean localsearch = target == null || target.equals(event.peers.mySeed());
+ SolrDocumentList docList = null;
+ QueryResponse rsp = null;
+ if (localsearch) {
+ // search the local index
+ try {
+ rsp = event.rankingProcess.getQuery().getSegment().fulltext().getDefaultConnector().query(solrQuery);
+ docList = rsp.getResults();
+ } catch (Throwable e) {
+ Network.log.logInfo("SEARCH failed (solr), localpeer (" + e.getMessage() + ")", e);
+ return -1;
+ }
+ } else {
+ try {
+ RemoteInstance instance = new RemoteInstance("http://" + target.getPublicAddress(), null, "solr"); // this is a 'patch configuration' which considers 'solr' as default collection
+ SolrConnector solrConnector = new RemoteSolrConnector(instance, "solr");
+ rsp = solrConnector.query(solrQuery);
+ docList = rsp.getResults();
+ solrConnector.close();
+ instance.close();
+ // no need to close this here because that sends a commit to remote solr which is not wanted here
+ } catch (Throwable e) {
+ Network.log.logInfo("SEARCH failed (solr), remote Peer: " +target.getName() + "/" + target.getPublicAddress() + " (" + e.getMessage() + ")", e);
+ return -1;
+ }
+ }
+
+ // evaluate facets
+ Map<String, ReversibleScoreMap<String>> facets = new HashMap<String, ReversibleScoreMap<String>>(event.query.facetfields.size());
+ for (String field: event.query.facetfields) {
+ FacetField facet = rsp.getFacetField(field);
+ ReversibleScoreMap<String> result = new ClusteredScoreMap<String>(UTF8.insensitiveUTF8Comparator);
+ List<Count> values = facet == null ? null : facet.getValues();
+ if (values == null) continue;
+ for (Count ff: values) {
+ int c = (int) ff.getCount();
+ if (c == 0) continue;
+ result.set(ff.getName(), c);
+ }
+ facets.put(field, result);
+ }
+
+ // evaluate snippets
+ Map<String, Map<String, List<String>>> rawsnippets = rsp.getHighlighting(); // a map from the urlhash to a map with key=field and value = list of snippets
+ Map<String, String> snippets = new HashMap<String, String>(); // this will be a list of urlhash-snippet entries
+ if (rawsnippets != null) {
+ nextsnippet: for (Map.Entry<String, Map<String, List<String>>> re: rawsnippets.entrySet()) {
+ Map<String, List<String>> rs = re.getValue();
+ for (CollectionSchema field: snippetFields) {
+ if (rs.containsKey(field.getSolrFieldName())) {
+ List<String> s = rs.get(field.getSolrFieldName());
+ if (s.size() > 0) {
+ snippets.put(re.getKey(), s.get(0));
+ continue nextsnippet;
+ }
+ }
+ }
+ // no snippet found :( --we don't assign a value here by default; that can be done as an evaluation outside this method
+ }
+ }
+
+ // evaluate result
+ List<URIMetadataNode> container = new ArrayList<URIMetadataNode>();
+ if (docList == null || docList.size() == 0) {
+ Network.log.logInfo("SEARCH (solr), returned 0 out of 0 documents from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())) + " query = " + solrQuery.toString()) ;
+ return 0;
+ }
+
+ Network.log.logInfo("SEARCH (solr), returned " + docList.size() + " out of " + docList.getNumFound() + " documents from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));
+ int term = count;
+ for (final SolrDocument doc: docList) {
+ if ( term-- <= 0 ) {
+ break; // do not process more that requested (in case that evil peers fill us up with rubbish)
+ }
+ // get one single search result
+ if ( doc == null ) {
+ continue;
+ }
+ URIMetadataNode urlEntry = new URIMetadataNode(doc);
+
+ if ( blacklist.isListed(BlacklistType.SEARCH, urlEntry) ) {
+ if ( Network.log.isInfo() ) {
+ if (localsearch) {
+ Network.log.logInfo("local search (solr): filtered blacklisted url " + urlEntry.url());
+ } else {
+ Network.log.logInfo("remote search (solr): filtered blacklisted url " + urlEntry.url() + " from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));
+ }
+ }
+ continue; // block with blacklist
+ }
+
+ final String urlRejectReason = Switchboard.getSwitchboard().crawlStacker.urlInAcceptedDomain(urlEntry.url());
+ if ( urlRejectReason != null ) {
+ if ( Network.log.isInfo() ) {
+ if (localsearch) {
+ Network.log.logInfo("local search (solr): rejected url '" + urlEntry.url() + "' (" + urlRejectReason + ")");
+ } else {
+ Network.log.logInfo("remote search (solr): rejected url '" + urlEntry.url() + "' (" + urlRejectReason + ") from peer " + target.getName());
+ }
+ }
+ continue; // reject url outside of our domain
+ }
+
+ // passed all checks, store url
+ if (!localsearch) {
+ try {
+ event.query.getSegment().fulltext().putDocument(event.query.getSegment().fulltext().getDefaultConfiguration().toSolrInputDocument(doc));
+ ResultURLs.stack(
+ ASCII.String(urlEntry.url().hash()),
+ urlEntry.url().getHost(),
+ event.peers.mySeed().hash.getBytes(),
+ UTF8.getBytes(target.hash),
+ EventOrigin.QUERIES);
+ } catch ( final IOException e ) {
+ Network.log.logWarning("could not store search result", e);
+ continue; // db-error
+ }
+ }
+
+ // add the url entry to the word indexes
+ container.add(urlEntry);
+ }
+
+ if (localsearch) {
+ event.add(container, facets, snippets, true, "localpeer", (int) docList.getNumFound());
+ event.rankingProcess.addFinalize();
+ event.addExpectedRemoteReferences(-count);
+ Network.log.logInfo("local search (solr): localpeer sent " + container.get(0).size() + "/" + docList.size() + " references");
+ } else {
+ event.add(container, facets, snippets, false, target.getName() + "/" + target.hash, (int) docList.getNumFound());
+ event.rankingProcess.addFinalize();
+ event.addExpectedRemoteReferences(-count);
+ Network.log.logInfo("remote search (solr): peer " + target.getName() + " sent " + container.get(0).size() + "/" + docList.size() + " references");
+ }
+ return docList.size();
+ }
+
+ public static Map<String, String> permissionMessage(final SeedDB seedDB, final String targetHash) {
+ // ask for allowed message size and attachement size
+ // if this replies null, the peer does not answer
+
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // send request
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), targetHash, salt);
+ parts.put("process", UTF8.StringBody("permission"));
+ final byte[] content = postToFile(seedDB, targetHash, "message.html", parts, 6000);
+ final Map<String, String> result = FileUtils.table(content);
+ return result;
+ } catch ( final Exception e ) {
+ // most probably a network time-out exception
+ Network.log.logWarning("yacyClient.permissionMessage error:" + e.getMessage());
+ return null;
+ }
+ }
+
+ public static Map<String, String> postMessage(
+ final SeedDB seedDB,
+ final String targetHash,
+ final String subject,
+ final byte[] message) {
+ // this post a message to the remote message board
+
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // send request
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), targetHash, salt);
+ parts.put("process", UTF8.StringBody("post"));
+ parts.put("myseed", UTF8.StringBody(seedDB.mySeed().genSeedStr(salt)));
+ parts.put("subject", UTF8.StringBody(subject));
+ parts.put("message", UTF8.StringBody(message));
+ final byte[] content = postToFile(seedDB, targetHash, "message.html", parts, 20000);
+ final Map<String, String> result = FileUtils.table(content);
+ return result;
+ } catch ( final Exception e ) {
+ Network.log.logWarning("yacyClient.postMessage error:" + e.getMessage());
+ return null;
+ }
+ }
+
+ public static Map<String, String> crawlReceipt(
+ final Seed mySeed,
+ final Seed target,
+ final String process,
+ final String result,
+ final String reason,
+ final URIMetadataNode entry,
+ final String wordhashes) {
+ assert (target != null);
+ assert (mySeed != null);
+ assert (mySeed != target);
+
+ /*
+ the result can have one of the following values:
+ negative cases, no retry
+ unavailable - the resource is not avaiable (a broken link); not found or interrupted
+ robot - a robot-file has denied to crawl that resource
+
+ negative cases, retry possible
+ rejected - the peer has rejected to load the resource
+ dequeue - peer too busy - rejected to crawl
+
+ positive cases with crawling
+ fill - the resource was loaded and processed
+ update - the resource was already in database but re-loaded and processed
+
+ positive cases without crawling
+ known - the resource is already in database, believed to be fresh and not reloaded
+ stale - the resource was reloaded but not processed because source had no changes
+
+ */
+
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // determining target address
+ final String address = target.getClusterAddress();
+ if ( address == null ) {
+ return null;
+ }
+
+ // send request
+ try {
+ // prepare request
+ final Map<String, ContentBody> parts = basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
+ parts.put("process", UTF8.StringBody(process));
+ parts.put("urlhash", UTF8.StringBody(((entry == null) ? "" : ASCII.String(entry.hash()))));
+ parts.put("result", UTF8.StringBody(result));
+ parts.put("reason", UTF8.StringBody(reason));
+ parts.put("wordh", UTF8.StringBody(wordhashes));
+ parts.put(
+ "lurlEntry",
+ UTF8.StringBody(((entry == null) ? "" : crypt.simpleEncode(entry.toString(), salt))));
+ // send request
+ // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/crawlReceipt.html"), 10000, target.getHexHash() + ".yacyh", parts);
+ final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 10000);
+ final byte[] content =
+ httpClient.POSTbytes(
+ new MultiProtocolURI("http://" + address + "/yacy/crawlReceipt.html"),
+ target.getHexHash() + ".yacyh",
+ parts,
+ false);
+ return FileUtils.table(content);
+ } catch ( final Exception e ) {
+ // most probably a network time-out exception
+ Network.log.logWarning("yacyClient.crawlReceipt error:" + e.getMessage());
+ return null;
+ }
+ }
+
+ /**
+ * transfer the index. If the transmission fails, return a string describing the cause. If everything is
+ * ok, return null.
+ *
+ * @param targetSeed
+ * @param indexes
+ * @param urlCache
+ * @param gzipBody
+ * @param timeout
+ * @return
+ */
+ public static String transferIndex(
+ final Seed targetSeed,
+ final ReferenceContainerCache<WordReference> indexes,
+ final HandleSet urlRefs,
+ final Segment segment,
+ final boolean gzipBody,
+ final int timeout) {
+
+ // check if we got all necessary urls in the urlCache (only for debugging)
+ Iterator<WordReference> eenum;
+ Reference entry;
+ for ( final ReferenceContainer<WordReference> ic : indexes ) {
+ eenum = ic.entries();
+ while ( eenum.hasNext() ) {
+ entry = eenum.next();
+ if ( !urlRefs.has(entry.urlhash()) ) {
+ if ( Network.log.isFine() ) {
+ Network.log.logFine("DEBUG transferIndex: to-send url hash '"
+ + ASCII.String(entry.urlhash())
+ + "' is not contained in urlCache");
+ }
+ }
+ }
+ }
+
+ // transfer the RWI without the URLs
+ Map<String, String> in = transferRWI(targetSeed, indexes, gzipBody, timeout);
+
+ if ( in == null ) {
+ return "no connection from transferRWI";
+ }
+
+ String result = in.get("result");
+ if ( result == null ) {
+ return "no result from transferRWI";
+ }
+
+ if ( !(result.equals("ok")) ) {
+ return result;
+ }
+
+ // in now contains a list of unknown hashes
+ String uhss = in.get("unknownURL");
+ if ( uhss == null ) {
+ return "no unknownURL tag in response";
+ }
+ EventChannel
+ .channels(EventChannel.DHTSEND)
+ .addMessage(
+ new RSSMessage(
+ "Sent " + indexes.size() + " RWIs to " + targetSeed.getName(),
+ "",
+ targetSeed.hash));
+
+ uhss = uhss.trim();
+ if ( uhss.isEmpty() || uhss.equals(",") ) {
+ return null;
+ } // all url's known, we are ready here
+
+ final String[] uhs = uhss.split(",");
+ if ( uhs.length == 0 ) {
+ return null;
+ } // all url's known
+
+ // extract the urlCache from the result
+ final URIMetadataNode[] urls = new URIMetadataNode[uhs.length];
+ byte[] key;
+ for ( int i = 0; i < uhs.length; i++ ) {
+ key = ASCII.getBytes(uhs[i]);
+ if ( urlRefs.has(key) ) urls[i] = segment.fulltext().getMetadata(key);
+ if ( urls[i] == null ) {
+ if ( Network.log.isFine() ) {
+ Network.log.logFine("DEBUG transferIndex: requested url hash '"
+ + uhs[i]
+ + "', unknownURL='"
+ + uhss
+ + "'");
+ }
+ }
+ }
+
+ in = transferURL(targetSeed, urls, gzipBody, timeout);
+
+ if ( in == null ) {
+ return "no connection from transferURL";
+ }
+
+ result = in.get("result");
+ if ( result == null ) {
+ return "no result from transferURL";
+ }
+
+ if ( !result.equals("ok") ) {
+ return result;
+ }
+ EventChannel.channels(EventChannel.DHTSEND).addMessage(
+ new RSSMessage(
+ "Sent " + uhs.length + " URLs to peer " + targetSeed.getName(),
+ "",
+ targetSeed.hash));
+
+ return null;
+ }
+
+ private static Map<String, String> transferRWI(
+ final Seed targetSeed,
+ final ReferenceContainerCache<WordReference> indexes,
+ boolean gzipBody,
+ final int timeout) {
+ final String address = targetSeed.getPublicAddress();
+ if ( address == null ) {
+ Network.log.logWarning("no address for transferRWI");
+ return null;
+ }
+
+ // prepare post values
+ final String salt = crypt.randomSalt();
+
+ // enabling gzip compression for post request body
+ if ( gzipBody && (targetSeed.getVersion() < yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS_CHUNKED) ) {
+ gzipBody = false;
+ }
+
+ int indexcount = 0;
+ final StringBuilder entrypost = new StringBuilder(indexes.size() * 73);
+ Iterator<WordReference> eenum;
+ Reference entry;
+ for ( final ReferenceContainer<WordReference> ic : indexes ) {
+ eenum = ic.entries();
+ while ( eenum.hasNext() ) {
+ entry = eenum.next();
+ entrypost
+ .append(ASCII.String(ic.getTermHash()))
+ .append(entry.toPropertyForm())
+ .append(serverCore.CRLF_STRING);
+ indexcount++;
+ }
+ }
+
+ if ( indexcount == 0 ) {
+ // nothing to do but everything ok
+ final Map<String, String> result = new HashMap<String, String>(2);
+ result.put("result", "ok");
+ result.put("unknownURL", "");
+ return result;
+ }
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), targetSeed.hash, salt);
+ parts.put("wordc", UTF8.StringBody(Integer.toString(indexes.size())));
+ parts.put("entryc", UTF8.StringBody(Integer.toString(indexcount)));
+ parts.put("indexes", UTF8.StringBody(entrypost.toString()));
+ // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/transferRWI.html"), timeout, targetSeed.getHexHash() + ".yacyh", parts, gzipBody);
+ final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
+ final byte[] content =
+ httpClient.POSTbytes(
+ new MultiProtocolURI("http://" + address + "/yacy/transferRWI.html"),
+ targetSeed.getHexHash() + ".yacyh",
+ parts,
+ gzipBody);
+ final Iterator<String> v = FileUtils.strings(content);
+ // this should return a list of urlhashes that are unknown
+
+ final Map<String, String> result = FileUtils.table(v);
+ // return the transfered index data in bytes (for debugging only)
+ result.put("indexPayloadSize", Integer.toString(entrypost.length()));
+ return result;
+ } catch ( final Exception e ) {
+ Network.log.logInfo("yacyClient.transferRWI to " + address + " error: " + e.getMessage());
+ return null;
+ }
+ }
+
+ private static Map<String, String> transferURL(
+ final Seed targetSeed,
+ final URIMetadataNode[] urls,
+ boolean gzipBody,
+ final int timeout) {
+ // this post a message to the remote message board
+ final String address = targetSeed.getPublicAddress();
+ if ( address == null ) {
+ return null;
+ }
+
+ // prepare post values
+ final String salt = crypt.randomSalt();
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), targetSeed.hash, salt);
+
+ // enabling gzip compression for post request body
+ if ( gzipBody && (targetSeed.getVersion() < yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS_CHUNKED) ) {
+ gzipBody = false;
+ }
+
+ String resource;
+ int urlc = 0;
+ int urlPayloadSize = 0;
+ for ( final URIMetadataNode url : urls ) {
+ if ( url != null ) {
+ resource = url.toString();
+ //System.out.println("*** DEBUG resource = " + resource);
+ if ( resource != null && resource.indexOf(0) == -1 ) {
+ parts.put("url" + urlc, UTF8.StringBody(resource));
+ urlPayloadSize += resource.length();
+ urlc++;
+ }
+ }
+ }
+ try {
+ parts.put("urlc", UTF8.StringBody(Integer.toString(urlc)));
+ // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/transferURL.html"), timeout, targetSeed.getHexHash() + ".yacyh", parts, gzipBody);
+ final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
+ final byte[] content =
+ httpClient.POSTbytes(
+ new MultiProtocolURI("http://" + address + "/yacy/transferURL.html"),
+ targetSeed.getHexHash() + ".yacyh",
+ parts,
+ gzipBody);
+ final Iterator<String> v = FileUtils.strings(content);
+
+ final Map<String, String> result = FileUtils.table(v);
+ // return the transfered url data in bytes (for debugging only)
+ result.put("urlPayloadSize", Integer.toString(urlPayloadSize));
+ return result;
+ } catch ( final Exception e ) {
+ Network.log.logWarning("yacyClient.transferURL to " + address + " error: " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static Map<String, String> getProfile(final Seed targetSeed) {
+ // ReferenceContainerCache<HostReference> ref = loadIDXHosts(targetSeed);
+
+ // this post a message to the remote message board
+ final String salt = crypt.randomSalt();
+
+ String address = targetSeed.getClusterAddress();
+ if ( address == null ) {
+ address = "localhost:8090";
+ }
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), targetSeed.hash, salt);
+ // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/profile.html"), 5000, targetSeed.getHexHash() + ".yacyh", parts);
+ final HTTPClient httpclient = new HTTPClient(ClientIdentification.getUserAgent(), 15000);
+ final byte[] content =
+ httpclient.POSTbytes(
+ new MultiProtocolURI("http://" + address + "/yacy/profile.html"),
+ targetSeed.getHexHash() + ".yacyh",
+ parts,
+ false);
+ return FileUtils.table(content);
+ } catch ( final Exception e ) {
+ Network.log.logWarning("yacyClient.getProfile error:" + e.getMessage());
+ return null;
+ }
+ }
+
+ public static ReferenceContainerCache<HostReference> loadIDXHosts(final Seed target) {
+ final ReferenceContainerCache<HostReference> index =
+ new ReferenceContainerCache<HostReference>(
+ WebStructureGraph.hostReferenceFactory,
+ Base64Order.enhancedCoder,
+ 6);
+ // check if the host supports this protocol
+ if ( target.getRevision() < migration.IDX_HOST ) {
+ // if the protocol is not supported then we just return an empty host reference container
+ return index;
+ }
+
+ // prepare request
+ final String salt = crypt.randomSalt();
+
+ // send request
+ try {
+ final Map<String, ContentBody> parts =
+ basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
+ parts.put("object", UTF8.StringBody("host"));
+ final byte[] content = postToFile(target, "idx.json", parts, 30000);
+ if ( content == null || content.length == 0 ) {
+ Network.log.logWarning("yacyClient.loadIDXHosts error: empty result");
+ return null;
+ }
+ final JSONObject json =
+ new JSONObject(new JSONTokener(new InputStreamReader(new ByteArrayInputStream(content))));
+ /* the json has the following form:
+ {
+ "version":"#[version]#",
+ "uptime":"#[uptime]#",
+ "name":"#[name]#",
+ "rowdef":"#[rowdef]#",
+ "idx":{
+ #{list}#"#[term]#":[#[references]#]#(comma)#::,#(/comma)#
+ #{/list}#
+ }
+ }
+ */
+ final JSONObject idx = json.getJSONObject("idx");
+ // iterate over all references
+ final Iterator<String> termIterator = idx.keys();
+ String term;
+ while ( termIterator.hasNext() ) {
+ term = termIterator.next();
+ final JSONArray references = idx.getJSONArray(term);
+ // iterate until we get an exception or null
+ int c = 0;
+ String reference;
+ final ReferenceContainer<HostReference> referenceContainer =
+ new ReferenceContainer<HostReference>(
+ WebStructureGraph.hostReferenceFactory,
+ UTF8.getBytes(term));
+ try {
+ while ( (reference = references.getString(c++)) != null ) {
+ //System.out.println("REFERENCE: " + reference);
+ referenceContainer.add(new HostReference(reference));
+ }
+ } catch ( final JSONException e ) {
+ } // this finishes the iteration
+ index.add(referenceContainer);
+ }
+ return index;
+ } catch ( final Exception e ) {
+ Network.log.logWarning("yacyClient.loadIDXHosts error:" + e.getMessage());
+ return index;
+ }
+ }
+
+ public static final boolean authentifyRequest(final serverObjects post, final serverSwitch env) {
+ if ( post == null || env == null ) {
+ return false;
+ }
+
+ // identify network
+ final String unitName = post.get(SwitchboardConstants.NETWORK_NAME, Seed.DFLT_NETWORK_UNIT); // the network unit
+ if ( !unitName.equals(env.getConfig(SwitchboardConstants.NETWORK_NAME, Seed.DFLT_NETWORK_UNIT)) ) {
+ return false;
+ }
+
+ // check authentication method
+ final String authenticationControl = env.getConfig("network.unit.protocol.control", "uncontrolled");
+ if ( authenticationControl.equals("uncontrolled") ) {
+ return true;
+ }
+ final String authenticationMethod =
+ env.getConfig("network.unit.protocol.request.authentication.method", "");
+ if ( authenticationMethod.isEmpty() ) {
+ return false;
+ }
+ if ( authenticationMethod.equals("salted-magic-sim") ) {
+ // authorize the peer using the md5-magic
+ final String salt = post.get("key", "");
+ final String iam = post.get("iam", "");
+ final String magic = env.getConfig("network.unit.protocol.request.authentication.essentials", "");
+ final String md5 = Digest.encodeMD5Hex(salt + iam + magic);
+ return post.get("magicmd5", "").equals(md5);
+ }
+
+ // unknown authentication method
+ return false;
+ }
+
+ private static final LinkedHashMap<String, ContentBody> basicRequestParts(
+ final Switchboard sb,
+ final String targetHash,
+ final String salt) {
+ // put in all the essentials for routing and network authentication
+ // generate a session key
+ final LinkedHashMap<String, ContentBody> parts =
+ basicRequestParts(
+ sb.peers.mySeed().hash,
+ targetHash,
+ Switchboard.getSwitchboard().getConfig(
+ SwitchboardConstants.NETWORK_NAME,
+ Seed.DFLT_NETWORK_UNIT));
+ parts.put("key", UTF8.StringBody(salt));
+
+ // authentication essentials
+ final String authenticationControl = sb.getConfig("network.unit.protocol.control", "uncontrolled");
+ final String authenticationMethod =
+ sb.getConfig("network.unit.protocol.request.authentication.method", "");
+ if ( (authenticationControl.equals("controlled")) && (authenticationMethod.length() > 0) ) {
+ if ( authenticationMethod.equals("salted-magic-sim") ) {
+ // generate an authentication essential using the salt, the iam-hash and the network magic
+ final String magic =
+ sb.getConfig("network.unit.protocol.request.authentication.essentials", "");
+ final String md5 = Digest.encodeMD5Hex(salt + sb.peers.mySeed().hash + magic);
+ parts.put("magicmd5", UTF8.StringBody(md5));
+ }
+ }
+
+ return parts;
+ }
+
+ private static final LinkedHashMap<String, ContentBody> basicRequestParts(
+ final String myHash,
+ final String targetHash,
+ final String networkName) {
+ // put in all the essentials for routing and network authentication
+ // generate a session key
+ final LinkedHashMap<String, ContentBody> parts = new LinkedHashMap<String, ContentBody>();
+
+ // just standard identification essentials
+ if ( myHash != null ) {
+ parts.put("iam", UTF8.StringBody(myHash));
+ if ( targetHash != null ) {
+ parts.put("youare", UTF8.StringBody(targetHash));
+ }
+
+ // time information for synchronization
+ // use our own formatter to prevent concurrency locks with other processes
+ final GenericFormatter my_SHORT_SECOND_FORMATTER =
+ new GenericFormatter(GenericFormatter.FORMAT_SHORT_SECOND, GenericFormatter.time_second);
+ parts.put("mytime", UTF8.StringBody(my_SHORT_SECOND_FORMATTER.format()));
+ parts.put("myUTC", UTF8.StringBody(Long.toString(System.currentTimeMillis())));
+
+ // network identification
+ parts.put(SwitchboardConstants.NETWORK_NAME, UTF8.StringBody(networkName));
+ }
+
+ return parts;
+ }
+
- }
+ }
diff --cc source/net/yacy/search/schema/CollectionConfiguration.java
index 37860b6b0,000000000..d56ecd1c0
mode 100644,000000..100644
--- a/source/net/yacy/search/schema/CollectionConfiguration.java
+++ b/source/net/yacy/search/schema/CollectionConfiguration.java
@@@ -1,901 -1,0 +1,903 @@@
+/**
+ * CollectionConfiguration
+ * Copyright 2011 by Michael Peter Christen
+ * First released 14.04.2011 at http://yacy.net
+ *
+ * $LastChangedDate: 2011-04-14 22:05:04 +0200 (Do, 14 Apr 2011) $
+ * $LastChangedRevision: 7654 $
+ * $LastChangedBy: orbiter $
+ *
+ * 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.schema;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import net.yacy.cora.document.ASCII;
+import net.yacy.cora.document.MultiProtocolURI;
+import net.yacy.cora.document.UTF8;
+import net.yacy.cora.federate.solr.SchemaConfiguration;
+import net.yacy.cora.federate.solr.FailType;
+import net.yacy.cora.federate.solr.ProcessType;
+import net.yacy.cora.federate.solr.SchemaDeclaration;
+import net.yacy.cora.protocol.Domains;
+import net.yacy.cora.protocol.HeaderFramework;
+import net.yacy.cora.protocol.ResponseHeader;
+import net.yacy.cora.util.CommonPattern;
+import net.yacy.cora.util.SpaceExceededException;
+import net.yacy.crawler.data.CrawlProfile;
+import net.yacy.crawler.retrieval.Response;
+import net.yacy.document.Condenser;
+import net.yacy.document.Document;
+import net.yacy.document.parser.html.ContentScraper;
+import net.yacy.document.parser.html.ImageEntry;
+import net.yacy.kelondro.data.citation.CitationReference;
+import net.yacy.kelondro.data.meta.DigestURI;
+import net.yacy.kelondro.data.meta.URIMetadataRow;
+import net.yacy.kelondro.index.RowHandleSet;
+import net.yacy.kelondro.logging.Log;
+import net.yacy.kelondro.rwi.IndexCell;
+import net.yacy.kelondro.rwi.ReferenceContainer;
+import net.yacy.kelondro.util.Bitfield;
+import net.yacy.kelondro.util.ByteBuffer;
+
+import org.apache.solr.common.SolrDocument;
+import org.apache.solr.common.SolrInputDocument;
+
+
+public class CollectionConfiguration extends SchemaConfiguration implements Serializable {
+
+ private static final long serialVersionUID=-499100932212840385L;
+
+
+ /**
+ * initialize with an empty ConfigurationSet which will cause that all the index
+ * attributes are used
+ */
+ public CollectionConfiguration() {
+ super();
+ }
+
+ /**
+ * initialize the schema with a given configuration file
+ * the configuration file simply contains a list of lines with keywords
+ * or keyword = value lines (while value is a custom Solr field name
+ * @param configurationFile
+ */
+ public CollectionConfiguration(final File configurationFile, boolean lazy) {
+ super(configurationFile);
+ super.lazy = lazy;
+ // check consistency: compare with YaCyField enum
+ if (this.isEmpty()) return;
+ Iterator<Entry> it = this.entryIterator();
+ for (SchemaConfiguration.Entry etr = it.next(); it.hasNext(); etr = it.next()) {
+ try {
+ CollectionSchema f = CollectionSchema.valueOf(etr.key());
+ f.setSolrFieldName(etr.getValue());
+ } catch (IllegalArgumentException e) {
+ Log.logFine("SolrCollectionWriter", "solr schema file " + configurationFile.getAbsolutePath() + " defines unknown attribute '" + etr.toString() + "'");
+ it.remove();
+ }
+ }
+ // check consistency the other way: look if all enum constants in SolrField appear in the configuration file
+ for (CollectionSchema field: CollectionSchema.values()) {
+ if (this.get(field.name()) == null) {
+ Log.logWarning("SolrCollectionWriter", " solr schema file " + configurationFile.getAbsolutePath() + " is missing declaration for '" + field.name() + "'");
+ }
+ }
+ }
+
+ /**
+ * save configuration to file and update enum SolrFields
+ * @throws IOException
+ */
+ public void commit() throws IOException {
+ try {
+ super.commit();
+ // make sure the enum SolrField.SolrFieldName is current
+ Iterator<Entry> it = this.entryIterator();
+ for (SchemaConfiguration.Entry etr = it.next(); it.hasNext(); etr = it.next()) {
+ try {
+ SchemaDeclaration f = CollectionSchema.valueOf(etr.key());
+ f.setSolrFieldName(etr.getValue());
+ } catch (IllegalArgumentException e) {
+ continue;
+ }
+ }
+ } catch (final IOException e) {}
+ }
+
+ /**
+ * Convert a SolrDocument to a SolrInputDocument.
+ * This is useful if a document from the search index shall be modified and indexed again.
+ * This shall be used as replacement of ClientUtils.toSolrInputDocument because we remove some fields
+ * which are created automatically during the indexing process.
+ * @param doc the solr document
+ * @return a solr input document
+ */
+ public SolrInputDocument toSolrInputDocument(SolrDocument doc) {
+ SolrInputDocument sid = new SolrInputDocument();
- Set<String> omitFields = new HashSet<String>();
++ Set<String> omitFields = new HashSet<String>(3);
++ omitFields.add(CollectionSchema.author_sxt.getSolrFieldName());
+ omitFields.add(CollectionSchema.coordinate_p.getSolrFieldName() + "_0_coordinate");
+ omitFields.add(CollectionSchema.coordinate_p.getSolrFieldName() + "_1_coordinate");
- omitFields.add(CollectionSchema.author_sxt.getSolrFieldName());
+ for (String name: doc.getFieldNames()) {
- if (this.contains(name) && !omitFields.contains(name)) sid.addField(name, doc.getFieldValue(name), 1.0f);
++ if (this.contains(name) && !omitFields.contains(name)) { // check each field if enabled in local Solr schema
++ sid.addField(name, doc.getFieldValue(name), 1.0f);
++ }
+ }
+ return sid;
+ }
+
+ public SolrInputDocument metadata2solr(final URIMetadataRow md) {
+
+ final SolrInputDocument doc = new SolrInputDocument();
+ final DigestURI digestURI = md.url();
+ boolean allAttr = this.isEmpty();
+
+ if (allAttr || contains(CollectionSchema.failreason_t)) add(doc, CollectionSchema.failreason_t, "");
+ add(doc, CollectionSchema.id, ASCII.String(md.hash()));
+ String us = digestURI.toNormalform(true);
+ add(doc, CollectionSchema.sku, us);
+ if (allAttr || contains(CollectionSchema.ip_s)) {
+ final InetAddress address = digestURI.getInetAddress();
+ if (address != null) add(doc, CollectionSchema.ip_s, address.getHostAddress());
+ }
+ if (allAttr || contains(CollectionSchema.url_protocol_s)) add(doc, CollectionSchema.url_protocol_s, digestURI.getProtocol());
+ Map<String, String> searchpart = digestURI.getSearchpartMap();
+ if (searchpart == null) {
+ if (allAttr || contains(CollectionSchema.url_parameter_i)) add(doc, CollectionSchema.url_parameter_i, 0);
+ } else {
+ if (allAttr || contains(CollectionSchema.url_parameter_i)) add(doc, CollectionSchema.url_parameter_i, searchpart.size());
+ if (allAttr || contains(CollectionSchema.url_parameter_key_sxt)) add(doc, CollectionSchema.url_parameter_key_sxt, searchpart.keySet().toArray(new String[searchpart.size()]));
+ if (allAttr || contains(CollectionSchema.url_parameter_value_sxt)) add(doc, CollectionSchema.url_parameter_value_sxt, searchpart.values().toArray(new String[searchpart.size()]));
+ }
+ if (allAttr || contains(CollectionSchema.url_chars_i)) add(doc, CollectionSchema.url_chars_i, us.length());
+ String host = null;
+ if ((host = digestURI.getHost()) != null) {
+ String dnc = Domains.getDNC(host);
+ String subdomOrga = host.length() - dnc.length() <= 0 ? "" : host.substring(0, host.length() - dnc.length() - 1);
+ int p = subdomOrga.lastIndexOf('.');
+ String subdom = (p < 0) ? "" : subdomOrga.substring(0, p);
+ String orga = (p < 0) ? subdomOrga : subdomOrga.substring(p + 1);
+ if (allAttr || contains(CollectionSchema.host_s)) add(doc, CollectionSchema.host_s, host);
+ if (allAttr || contains(CollectionSchema.host_dnc_s)) add(doc, CollectionSchema.host_dnc_s, dnc);
+ if (allAttr || contains(CollectionSchema.host_organization_s)) add(doc, CollectionSchema.host_organization_s, orga);
+ if (allAttr || contains(CollectionSchema.host_organizationdnc_s)) add(doc, CollectionSchema.host_organizationdnc_s, orga + '.' + dnc);
+ if (allAttr || contains(CollectionSchema.host_subdomain_s)) add(doc, CollectionSchema.host_subdomain_s, subdom);
+ }
+
+ String title = md.dc_title();
+ if (allAttr || contains(CollectionSchema.title)) add(doc, CollectionSchema.title, new String[]{title});
+ if (allAttr || contains(CollectionSchema.title_count_i)) add(doc, CollectionSchema.title_count_i, 1);
+ if (allAttr || contains(CollectionSchema.title_chars_val)) {
+ Integer[] cv = new Integer[]{new Integer(title.length())};
+ add(doc, CollectionSchema.title_chars_val, cv);
+ }
+ if (allAttr || contains(CollectionSchema.title_words_val)) {
+ Integer[] cv = new Integer[]{new Integer(CommonPattern.SPACE.split(title).length)};
+ add(doc, CollectionSchema.title_words_val, cv);
+ }
+
+ String description = md.snippet(); if (description == null) description = "";
+ if (allAttr || contains(CollectionSchema.description)) add(doc, CollectionSchema.description, description);
+ if (allAttr || contains(CollectionSchema.description_count_i)) add(doc, CollectionSchema.description_count_i, 1);
+ if (allAttr || contains(CollectionSchema.description_chars_val)) {
+ Integer[] cv = new Integer[]{new Integer(description.length())};
+ add(doc, CollectionSchema.description_chars_val, cv);
+ }
+ if (allAttr || contains(CollectionSchema.description_words_val)) {
+ Integer[] cv = new Integer[]{new Integer(CommonPattern.SPACE.split(description).length)};
+ add(doc, CollectionSchema.description_words_val, cv);
+ }
+
+ if (allAttr || contains(CollectionSchema.author)) add(doc, CollectionSchema.author, md.dc_creator());
+ if (allAttr || contains(CollectionSchema.content_type)) add(doc, CollectionSchema.content_type, Response.doctype2mime(digestURI.getFileExtension(), md.doctype()));
+ if (allAttr || contains(CollectionSchema.last_modified)) add(doc, CollectionSchema.last_modified, md.moddate());
+ if (allAttr || contains(CollectionSchema.wordcount_i)) add(doc, CollectionSchema.wordcount_i, md.wordCount());
+
+ String keywords = md.dc_subject();
+ Bitfield flags = md.flags();
+ if (flags.get(Condenser.flag_cat_indexof)) {
+ if (keywords == null || keywords.isEmpty()) keywords = "indexof"; else {
+ if (keywords.indexOf(',') > 0) keywords += ", indexof"; else keywords += " indexof";
+ }
+ }
+ if (allAttr || contains(CollectionSchema.keywords)) {
+ add(doc, CollectionSchema.keywords, keywords);
+ }
+
+ // path elements of link
+ if (allAttr || contains(CollectionSchema.url_paths_sxt)) add(doc, CollectionSchema.url_paths_sxt, digestURI.getPaths());
+ if (allAttr || contains(CollectionSchema.url_file_ext_s)) add(doc, CollectionSchema.url_file_ext_s, digestURI.getFileExtension());
+
+ if (allAttr || contains(CollectionSchema.imagescount_i)) add(doc, CollectionSchema.imagescount_i, md.limage());
+ if (allAttr || contains(CollectionSchema.inboundlinkscount_i)) add(doc, CollectionSchema.inboundlinkscount_i, md.llocal());
+ if (allAttr || contains(CollectionSchema.outboundlinkscount_i)) add(doc, CollectionSchema.outboundlinkscount_i, md.lother());
+ if (allAttr || contains(CollectionSchema.charset_s)) add(doc, CollectionSchema.charset_s, "UTF8");
+
+ // coordinates
+ if (md.lat() != 0.0 && md.lon() != 0.0) {
+ if (allAttr || contains(CollectionSchema.coordinate_p)) add(doc, CollectionSchema.coordinate_p, Double.toString(md.lat()) + "," + Double.toString(md.lon()));
+ }
+ if (allAttr || contains(CollectionSchema.httpstatus_i)) add(doc, CollectionSchema.httpstatus_i, 200);
+
+ // fields that are in URIMetadataRow additional to yacy2solr basic requirement
+ if (allAttr || contains(CollectionSchema.load_date_dt)) add(doc, CollectionSchema.load_date_dt, md.loaddate());
+ if (allAttr || contains(CollectionSchema.fresh_date_dt)) add(doc, CollectionSchema.fresh_date_dt, md.freshdate());
+ if (allAttr || contains(CollectionSchema.host_id_s)) add(doc, CollectionSchema.host_id_s, md.hosthash());
+ if ((allAttr || contains(CollectionSchema.referrer_id_txt)) && md.referrerHash() != null) add(doc, CollectionSchema.referrer_id_txt, new String[]{ASCII.String(md.referrerHash())});
+ if (allAttr || contains(CollectionSchema.md5_s)) add(doc, CollectionSchema.md5_s, md.md5());
+ if (allAttr || contains(CollectionSchema.publisher_t)) add(doc, CollectionSchema.publisher_t, md.dc_publisher());
+ if ((allAttr || contains(CollectionSchema.language_s)) && md.language() != null) add(doc, CollectionSchema.language_s, UTF8.String(md.language()));
+ if (allAttr || contains(CollectionSchema.size_i)) add(doc, CollectionSchema.size_i, md.size());
+ if (allAttr || contains(CollectionSchema.audiolinkscount_i)) add(doc, CollectionSchema.audiolinkscount_i, md.laudio());
+ if (allAttr || contains(CollectionSchema.videolinkscount_i)) add(doc, CollectionSchema.videolinkscount_i, md.lvideo());
+ if (allAttr || contains(CollectionSchema.applinkscount_i)) add(doc, CollectionSchema.applinkscount_i, md.lapp());
+ if (allAttr || contains(CollectionSchema.text_t)) {
+ // construct the text from other metadata parts.
+ // This is necessary here since that is used to search the link when no other data (parsed text body) is available
+ StringBuilder sb = new StringBuilder(120);
+ accText(sb, md.dc_title());
+ accText(sb, md.dc_creator());
+ accText(sb, md.dc_publisher());
+ accText(sb, md.snippet());
+ accText(sb, digestURI.toTokens());
+ accText(sb, keywords);
+ add(doc, CollectionSchema.text_t, sb.toString());
+ }
+
+ return doc;
+ }
+
+ private static void accText(final StringBuilder sb, String text) {
+ if (text == null || text.length() == 0) return;
+ if (sb.length() != 0) sb.append(' ');
+ text = text.trim();
+ if (!text.isEmpty() && text.charAt(text.length() - 1) == '.') sb.append(text); else sb.append(text).append('.');
+ }
+
+ public static class SolrVector extends SolrInputDocument {
+ private static final long serialVersionUID = -210901881471714939L;
+ private List<SolrInputDocument> webgraphDocuments;
+ public SolrVector() {
+ super();
+ this.webgraphDocuments = new ArrayList<SolrInputDocument>();
+ }
+ public void addWebgraphDocument(SolrInputDocument webgraphDocument) {
+ this.webgraphDocuments.add(webgraphDocument);
+ }
+ public List<SolrInputDocument> getWebgraphDocuments() {
+ return this.webgraphDocuments;
+ }
+ }
+
+ public SolrVector yacy2solr(
+ final String id, final CrawlProfile profile, final ResponseHeader responseHeader,
+ final Document document, Condenser condenser, DigestURI referrerURL, String language,
+ IndexCell<CitationReference> citations,
+ WebgraphConfiguration webgraph) {
+ // we use the SolrCell design as index schema
+ SolrVector doc = new SolrVector();
+ final DigestURI digestURI = document.dc_source();
+ boolean allAttr = this.isEmpty();
+
+ Set<ProcessType> processTypes = new LinkedHashSet<ProcessType>();
+
+ add(doc, CollectionSchema.id, id);
+ if (allAttr || contains(CollectionSchema.failreason_t)) add(doc, CollectionSchema.failreason_t, ""); // overwrite a possible fail reason (in case that there was a fail reason before)
+ String docurl = digestURI.toNormalform(true);
+ add(doc, CollectionSchema.sku, docurl);
+
+ int clickdepth = -1;
+ if ((allAttr || contains(CollectionSchema.clickdepth_i)) && citations != null) {
+ if (digestURI.probablyRootURL()) {
+ boolean lc = this.lazy; this.lazy = false;
+ clickdepth = 0;
+ this.lazy = lc;
+ } else {
+ // search the citations for references
+ try {
+ clickdepth = getClickDepth(citations, digestURI);
+ } catch (IOException e) {
+ add(doc, CollectionSchema.clickdepth_i, -1);
+ }
+ if (clickdepth < 0 || clickdepth > 1) {
+ processTypes.add(ProcessType.CLICKDEPTH); // postprocessing needed; this is also needed if the depth is positive; there could be a shortcut
+ }
+ }
+ add(doc, CollectionSchema.clickdepth_i, clickdepth);
+ }
+
+ if (allAttr || contains(CollectionSchema.ip_s)) {
+ final InetAddress address = digestURI.getInetAddress();
+ if (address != null) add(doc, CollectionSchema.ip_s, address.getHostAddress());
+ }
+ if (allAttr || contains(CollectionSchema.collection_sxt) && profile != null) add(doc, CollectionSchema.collection_sxt, profile.collections());
+ if (allAttr || contains(CollectionSchema.url_protocol_s)) add(doc, CollectionSchema.url_protocol_s, digestURI.getProtocol());
+ Map<String, String> searchpart = digestURI.getSearchpartMap();
+ if (searchpart == null) {
+ if (allAttr || contains(CollectionSchema.url_parameter_i)) add(doc, CollectionSchema.url_parameter_i, 0);
+ } else {
+ if (allAttr || contains(CollectionSchema.url_parameter_i)) add(doc, CollectionSchema.url_parameter_i, searchpart.size());
+ if (allAttr || contains(CollectionSchema.url_parameter_key_sxt)) add(doc, CollectionSchema.url_parameter_key_sxt, searchpart.keySet().toArray(new String[searchpart.size()]));
+ if (allAttr || contains(CollectionSchema.url_parameter_value_sxt)) add(doc, CollectionSchema.url_parameter_value_sxt, searchpart.values().toArray(new String[searchpart.size()]));
+ }
+ if (allAttr || contains(CollectionSchema.url_chars_i)) add(doc, CollectionSchema.url_chars_i, docurl.length());
+ String host = null;
+ if ((host = digestURI.getHost()) != null) {
+ String dnc = Domains.getDNC(host);
+ String subdomOrga = host.length() - dnc.length() <= 0 ? "" : host.substring(0, host.length() - dnc.length() - 1);
+ int p = subdomOrga.lastIndexOf('.');
+ String subdom = (p < 0) ? "" : subdomOrga.substring(0, p);
+ String orga = (p < 0) ? subdomOrga : subdomOrga.substring(p + 1);
+ if (allAttr || contains(CollectionSchema.host_s)) add(doc, CollectionSchema.host_s, host);
+ if (allAttr || contains(CollectionSchema.host_dnc_s)) add(doc, CollectionSchema.host_dnc_s, dnc);
+ if (allAttr || contains(CollectionSchema.host_organization_s)) add(doc, CollectionSchema.host_organization_s, orga);
+ if (allAttr || contains(CollectionSchema.host_organizationdnc_s)) add(doc, CollectionSchema.host_organizationdnc_s, orga + '.' + dnc);
+ if (allAttr || contains(CollectionSchema.host_subdomain_s)) add(doc, CollectionSchema.host_subdomain_s, subdom);
+ }
+
+ List<String> titles = document.titles();
+ if (allAttr || contains(CollectionSchema.title)) add(doc, CollectionSchema.title, titles);
+ if (allAttr || contains(CollectionSchema.title_count_i)) add(doc, CollectionSchema.title_count_i, titles.size());
+ if (allAttr || contains(CollectionSchema.title_chars_val)) {
+ ArrayList<Integer> cv = new ArrayList<Integer>(titles.size());
+ for (String s: titles) cv.add(new Integer(s.length()));
+ add(doc, CollectionSchema.title_chars_val, cv);
+ }
+ if (allAttr || contains(CollectionSchema.title_words_val)) {
+ ArrayList<Integer> cv = new ArrayList<Integer>(titles.size());
+ for (String s: titles) cv.add(new Integer(CommonPattern.SPACE.split(s).length));
+ add(doc, CollectionSchema.title_words_val, cv);
+ }
+
+ String description = document.dc_description();
+ List<String> descriptions = new ArrayList<String>();
+ for (String s: CommonPattern.NEWLINE.split(description)) descriptions.add(s);
+ if (allAttr || contains(CollectionSchema.description)) add(doc, CollectionSchema.description, description);
+ if (allAttr || contains(CollectionSchema.description_count_i)) add(doc, CollectionSchema.description_count_i, descriptions.size());
+ if (allAttr || contains(CollectionSchema.description_chars_val)) {
+ ArrayList<Integer> cv = new ArrayList<Integer>(descriptions.size());
+ for (String s: descriptions) cv.add(new Integer(s.length()));
+ add(doc, CollectionSchema.description_chars_val, cv);
+ }
+ if (allAttr || contains(CollectionSchema.description_words_val)) {
+ ArrayList<Integer> cv = new ArrayList<Integer>(descriptions.size());
+ for (String s: descriptions) cv.add(new Integer(CommonPattern.SPACE.split(s).length));
+ add(doc, CollectionSchema.description_words_val, cv);
+ }
+
+ if (allAttr || contains(CollectionSchema.author)) {
+ String author = document.dc_creator();
+ if (author == null || author.length() == 0) author = document.dc_publisher();
+ add(doc, CollectionSchema.author, author);
+ }
+ if (allAttr || contains(CollectionSchema.content_type)) add(doc, CollectionSchema.content_type, new String[]{document.dc_format()});
+ if (allAttr || contains(CollectionSchema.last_modified)) add(doc, CollectionSchema.last_modified, responseHeader == null ? new Date() : responseHeader.lastModified());
+ if (allAttr || contains(CollectionSchema.keywords)) add(doc, CollectionSchema.keywords, document.dc_subject(' '));
+ String content = document.getTextString();
+ if (content == null || content.length() == 0) {
+ content = digestURI.toTokens();
+ }
+ if (allAttr || contains(CollectionSchema.text_t)) add(doc, CollectionSchema.text_t, content);
+ if (allAttr || contains(CollectionSchema.wordcount_i)) {
+ if (content.length() == 0) {
+ add(doc, CollectionSchema.wordcount_i, 0);
+ } else {
+ int contentwc = 1;
+ for (int i = content.length() - 1; i >= 0; i--) if (content.charAt(i) == ' ') contentwc++;
+ add(doc, CollectionSchema.wordcount_i, contentwc);
+ }
+ }
+ if (allAttr || contains(CollectionSchema.synonyms_sxt)) {
+ List<String> synonyms = condenser.synonyms();
+ add(doc, CollectionSchema.synonyms_sxt, synonyms);
+ }
+ add(doc, CollectionSchema.exact_signature_l, condenser.exactSignature());
+ add(doc, CollectionSchema.exact_signature_unique_b, true); // this must be corrected afterwards!
+ add(doc, CollectionSchema.fuzzy_signature_l, condenser.fuzzySignature());
+ add(doc, CollectionSchema.fuzzy_signature_text_t, condenser.fuzzySignatureText());
+ add(doc, CollectionSchema.fuzzy_signature_unique_b, true); // this must be corrected afterwards!
+
+ // path elements of link
+ if (allAttr || contains(CollectionSchema.url_paths_sxt)) add(doc, CollectionSchema.url_paths_sxt, digestURI.getPaths());
+ if (allAttr || contains(CollectionSchema.url_file_ext_s)) add(doc, CollectionSchema.url_file_ext_s, digestURI.getFileExtension());
+
+ // get list of all links; they will be shrinked by urls that appear in other fields of the solr schema
+ Set<DigestURI> inboundLinks = document.inboundLinks();
+ Set<DigestURI> outboundLinks = document.outboundLinks();
+
+ int c = 0;
+ final Object parser = document.getParserObject();
+ Map<DigestURI, ImageEntry> images = new HashMap<DigestURI, ImageEntry>();
+ if (parser instanceof ContentScraper) {
+ final ContentScraper html = (ContentScraper) parser;
+ images = html.getImages();
+
+ // header tags
+ int h = 0;
+ int f = 1;
+ String[] hs;
+
+ hs = html.getHeadlines(1); h = h | (hs.length > 0 ? f : 0); f = f * 2; add(doc, CollectionSchema.h1_txt, hs); add(doc, CollectionSchema.h1_i, hs.length);
+ hs = html.getHeadlines(2); h = h | (hs.length > 0 ? f : 0); f = f * 2; add(doc, CollectionSchema.h2_txt, hs); add(doc, CollectionSchema.h2_i, hs.length);
+ hs = html.getHeadlines(3); h = h | (hs.length > 0 ? f : 0); f = f * 2; add(doc, CollectionSchema.h3_txt, hs); add(doc, CollectionSchema.h3_i, hs.length);
+ hs = html.getHeadlines(4); h = h | (hs.length > 0 ? f : 0); f = f * 2; add(doc, CollectionSchema.h4_txt, hs); add(doc, CollectionSchema.h4_i, hs.length);
+ hs = html.getHeadlines(5); h = h | (hs.length > 0 ? f : 0); f = f * 2; add(doc, CollectionSchema.h5_txt, hs); add(doc, CollectionSchema.h5_i, hs.length);
+ hs = html.getHeadlines(6); h = h | (hs.length > 0 ? f : 0); f = f * 2; add(doc, CollectionSchema.h6_txt, hs); add(doc, CollectionSchema.h6_i, hs.length);
+
+ add(doc, CollectionSchema.htags_i, h);
+ add(doc, CollectionSchema.schema_org_breadcrumb_i, html.breadcrumbCount());
+
+ // meta tags: Open Graph properties
+ String og;
+ og = html.getMetas().get("og:title"); if (og != null) add(doc, CollectionSchema.opengraph_title_t, og);
+ og = html.getMetas().get("og:type"); if (og != null) add(doc, CollectionSchema.opengraph_type_s, og);
+ og = html.getMetas().get("og:url"); if (og != null) add(doc, CollectionSchema.opengraph_url_s, og);
+ og = html.getMetas().get("og:image"); if (og != null) add(doc, CollectionSchema.opengraph_image_s, og);
+
+ // noindex and nofollow attributes
+ // from HTML (meta-tag in HTML header: robots)
+ // and HTTP header (x-robots property)
+ // coded as binary value:
+ // bit 0: "all" contained in html header meta
+ // bit 1: "index" contained in html header meta
+ // bit 2: "noindex" contained in html header meta
+ // bit 3: "nofollow" contained in html header meta
+ // bit 8: "noarchive" contained in http header properties
+ // bit 9: "nosnippet" contained in http header properties
+ // bit 10: "noindex" contained in http header properties
+ // bit 11: "nofollow" contained in http header properties
+ // bit 12: "unavailable_after" contained in http header properties
+ int b = 0;
+ final String robots_meta = html.getMetas().get("robots");
+ // this tag may have values: all, index, noindex, nofollow
+ if (robots_meta != null) {
+ if (robots_meta.indexOf("all",0) >= 0) b += 1; // set bit 0
+ if (robots_meta.indexOf("index",0) == 0 || robots_meta.indexOf(" index",0) >= 0 || robots_meta.indexOf(",index",0) >= 0 ) b += 2; // set bit 1
+ if (robots_meta.indexOf("noindex",0) >= 0) b += 4; // set bit 2
+ if (robots_meta.indexOf("nofollow",0) >= 0) b += 8; // set bit 3
+ }
+ String x_robots_tag = "";
+ if (responseHeader != null) {
+ x_robots_tag = responseHeader.get(HeaderFramework.X_ROBOTS_TAG, "");
+ if (x_robots_tag.isEmpty()) {
+ x_robots_tag = responseHeader.get(HeaderFramework.X_ROBOTS, "");
+ }
+ }
+ if (!x_robots_tag.isEmpty()) {
+ // this tag may have values: noarchive, nosnippet, noindex, unavailable_after
+ if (x_robots_tag.indexOf("noarchive",0) >= 0) b += 256; // set bit 8
+ if (x_robots_tag.indexOf("nosnippet",0) >= 0) b += 512; // set bit 9
+ if (x_robots_tag.indexOf("noindex",0) >= 0) b += 1024; // set bit 10
+ if (x_robots_tag.indexOf("nofollow",0) >= 0) b += 2048; // set bit 11
+ if (x_robots_tag.indexOf("unavailable_after",0) >=0) b += 4096; // set bit 12
+ }
+ add(doc, CollectionSchema.robots_i, b);
+
+ // meta tags: generator
+ final String generator = html.getMetas().get("generator");
+ if (generator != null) add(doc, CollectionSchema.metagenerator_t, generator);
+
+ // bold, italic
+ final String[] bold = html.getBold();
+ add(doc, CollectionSchema.boldcount_i, bold.length);
+ if (bold.length > 0) {
+ add(doc, CollectionSchema.bold_txt, bold);
+ if (allAttr || contains(CollectionSchema.bold_val)) {
+ add(doc, CollectionSchema.bold_val, html.getBoldCount(bold));
+ }
+ }
+ final String[] italic = html.getItalic();
+ add(doc, CollectionSchema.italiccount_i, italic.length);
+ if (italic.length > 0) {
+ add(doc, CollectionSchema.italic_txt, italic);
+ if (allAttr || contains(CollectionSchema.italic_val)) {
+ add(doc, CollectionSchema.italic_val, html.getItalicCount(italic));
+ }
+ }
+ final String[] underline = html.getUnderline();
+ add(doc, CollectionSchema.underlinecount_i, underline.length);
+ if (underline.length > 0) {
+ add(doc, CollectionSchema.underline_txt, underline);
+ if (allAttr || contains(CollectionSchema.underline_val)) {
+ add(doc, CollectionSchema.underline_val, html.getUnderlineCount(underline));
+ }
+ }
+ final String[] li = html.getLi();
+ add(doc, CollectionSchema.licount_i, li.length);
+ if (li.length > 0) add(doc, CollectionSchema.li_txt, li);
+
+ // images
+ final Collection<ImageEntry> imagesc = images.values();
+ final List<String> imgtags = new ArrayList<String>(imagesc.size());
+ final List<String> imgprots = new ArrayList<String>(imagesc.size());
+ final List<String> imgstubs = new ArrayList<String>(imagesc.size());
+ final List<String> imgalts = new ArrayList<String>(imagesc.size());
+ int withalt = 0;
+ for (final ImageEntry ie: imagesc) {
+ final MultiProtocolURI uri = ie.url();
+ inboundLinks.remove(uri);
+ outboundLinks.remove(uri);
+ imgtags.add(ie.toString());
+ String protocol = uri.getProtocol();
+ imgprots.add(protocol);
+ imgstubs.add(uri.toString().substring(protocol.length() + 3));
+ imgalts.add(ie.alt());
+ if (ie.alt() != null && ie.alt().length() > 0) withalt++;
+ }
+ if (allAttr || contains(CollectionSchema.imagescount_i)) add(doc, CollectionSchema.imagescount_i, imgtags.size());
+ if (allAttr || contains(CollectionSchema.images_tag_txt)) add(doc, CollectionSchema.images_tag_txt, imgtags);
+ if (allAttr || contains(CollectionSchema.images_protocol_sxt)) add(doc, CollectionSchema.images_protocol_sxt, protocolList2indexedList(imgprots));
+ if (allAttr || contains(CollectionSchema.images_urlstub_txt)) add(doc, CollectionSchema.images_urlstub_txt, imgstubs);
+ if (allAttr || contains(CollectionSchema.images_alt_txt)) add(doc, CollectionSchema.images_alt_txt, imgalts);
+ if (allAttr || contains(CollectionSchema.images_withalt_i)) add(doc, CollectionSchema.images_withalt_i, withalt);
+
+ // style sheets
+ if (allAttr || contains(CollectionSchema.css_tag_txt)) {
+ final Map<DigestURI, String> csss = html.getCSS();
+ final String[] css_tag = new String[csss.size()];
+ final String[] css_url = new String[csss.size()];
+ c = 0;
+ for (final Map.Entry<DigestURI, String> entry: csss.entrySet()) {
+ final String cssurl = entry.getKey().toNormalform(false);
+ inboundLinks.remove(cssurl);
+ outboundLinks.remove(cssurl);
+ css_tag[c] =
+ "<link rel=\"stylesheet\" type=\"text/css\" media=\"" + entry.getValue() + "\"" +
+ " href=\""+ cssurl + "\" />";
+ css_url[c] = cssurl;
+ c++;
+ }
+ add(doc, CollectionSchema.csscount_i, css_tag.length);
+ if (css_tag.length > 0) add(doc, CollectionSchema.css_tag_txt, css_tag);
+ if (css_url.length > 0) add(doc, CollectionSchema.css_url_txt, css_url);
+ }
+
+ // Scripts
+ if (allAttr || contains(CollectionSchema.scripts_txt)) {
+ final Set<DigestURI> scriptss = html.getScript();
+ final String[] scripts = new String[scriptss.size()];
+ c = 0;
+ for (final DigestURI u: scriptss) {
+ inboundLinks.remove(u);
+ outboundLinks.remove(u);
+ scripts[c++] = u.toNormalform(false);
+ }
+ add(doc, CollectionSchema.scriptscount_i, scripts.length);
+ if (scripts.length > 0) add(doc, CollectionSchema.scripts_txt, scripts);
+ }
+
+ // Frames
+ if (allAttr || contains(CollectionSchema.frames_txt)) {
+ final Set<DigestURI> framess = html.getFrames();
+ final String[] frames = new String[framess.size()];
+ c = 0;
+ for (final DigestURI u: framess) {
+ inboundLinks.remove(u);
+ outboundLinks.remove(u);
+ frames[c++] = u.toNormalform(false);
+ }
+ add(doc, CollectionSchema.framesscount_i, frames.length);
+ if (frames.length > 0) add(doc, CollectionSchema.frames_txt, frames);
+ }
+
+ // IFrames
+ if (allAttr || contains(CollectionSchema.iframes_txt)) {
+ final Set<DigestURI> iframess = html.getIFrames();
+ final String[] iframes = new String[iframess.size()];
+ c = 0;
+ for (final DigestURI u: iframess) {
+ inboundLinks.remove(u);
+ outboundLinks.remove(u);
+ iframes[c++] = u.toNormalform(false);
+ }
+ add(doc, CollectionSchema.iframesscount_i, iframes.length);
+ if (iframes.length > 0) add(doc, CollectionSchema.iframes_txt, iframes);
+ }
+
+ // canonical tag
+ if (allAttr || contains(CollectionSchema.canonical_t)) {
+ final DigestURI canonical = html.getCanonical();
+ if (canonical != null) {
+ inboundLinks.remove(canonical);
+ outboundLinks.remove(canonical);
+ add(doc, CollectionSchema.canonical_t, canonical.toNormalform(false));
+ // set a flag if this is equal to sku
+ if (contains(CollectionSchema.canonical_equal_sku_b) && canonical.equals(docurl)) {
+ add(doc, CollectionSchema.canonical_equal_sku_b, true);
+ }
+ }
+ }
+
+ // meta refresh tag
+ if (allAttr || contains(CollectionSchema.refresh_s)) {
+ String refresh = html.getRefreshPath();
+ if (refresh != null && refresh.length() > 0) {
+ MultiProtocolURI refreshURL;
+ try {
+ refreshURL = refresh.startsWith("http") ? new MultiProtocolURI(html.getRefreshPath()) : new MultiProtocolURI(digestURI, html.getRefreshPath());
+ if (refreshURL != null) {
+ inboundLinks.remove(refreshURL);
+ outboundLinks.remove(refreshURL);
+ add(doc, CollectionSchema.refresh_s, refreshURL.toNormalform(false));
+ }
+ } catch (MalformedURLException e) {
+ add(doc, CollectionSchema.refresh_s, refresh);
+ }
+ }
+ }
+
+ // flash embedded
+ if (allAttr || contains(CollectionSchema.flash_b)) {
+ MultiProtocolURI[] flashURLs = html.getFlash();
+ for (MultiProtocolURI u: flashURLs) {
+ // remove all flash links from ibound/outbound links
+ inboundLinks.remove(u);
+ outboundLinks.remove(u);
+ }
+ add(doc, CollectionSchema.flash_b, flashURLs.length > 0);
+ }
+
+ // generic evaluation pattern
+ for (final String model: html.getEvaluationModelNames()) {
+ if (allAttr || contains("ext_" + model + "_txt")) {
+ final String[] scorenames = html.getEvaluationModelScoreNames(model);
+ if (scorenames.length > 0) {
+ add(doc, CollectionSchema.valueOf("ext_" + model + "_txt"), scorenames);
+ add(doc, CollectionSchema.valueOf("ext_" + model + "_val"), html.getEvaluationModelScoreCounts(model, scorenames));
+ }
+ }
+ }
+
+ // response time
+ add(doc, CollectionSchema.responsetime_i, responseHeader == null ? 0 : Integer.parseInt(responseHeader.get(HeaderFramework.RESPONSE_TIME_MILLIS, "0")));
+ }
+
+ // statistics about the links
+ if (allAttr || contains(CollectionSchema.inboundlinkscount_i)) add(doc, CollectionSchema.inboundlinkscount_i, inboundLinks.size());
+ if (allAttr || contains(CollectionSchema.inboundlinksnofollowcount_i)) add(doc, CollectionSchema.inboundlinksnofollowcount_i, document.inboundLinkNofollowCount());
+ if (allAttr || contains(CollectionSchema.outboundlinkscount_i)) add(doc, CollectionSchema.outboundlinkscount_i, outboundLinks.size());
+ if (allAttr || contains(CollectionSchema.outboundlinksnofollowcount_i)) add(doc, CollectionSchema.outboundlinksnofollowcount_i, document.outboundLinkNofollowCount());
+
+ // list all links
+ WebgraphConfiguration.Subgraph subgraph = webgraph.edges(digestURI, responseHeader, profile.collections(), clickdepth, document.getAnchors(), images, inboundLinks, outboundLinks);
+ doc.webgraphDocuments.addAll(subgraph.edges);
+ if (allAttr || contains(CollectionSchema.inboundlinks_tag_txt)) add(doc, CollectionSchema.inboundlinks_tag_txt, subgraph.tags[0]);
+ if (allAttr || contains(CollectionSchema.inboundlinks_protocol_sxt)) add(doc, CollectionSchema.inboundlinks_protocol_sxt, protocolList2indexedList(subgraph.urlProtocols[0]));
+ if (allAttr || contains(CollectionSchema.inboundlinks_urlstub_txt)) add(doc, CollectionSchema.inboundlinks_urlstub_txt, subgraph.urlStubs[0]);
+ if (allAttr || contains(CollectionSchema.outboundlinks_tag_txt)) add(doc, CollectionSchema.outboundlinks_tag_txt, subgraph.tags[1]);
+ if (allAttr || contains(CollectionSchema.outboundlinks_protocol_sxt)) add(doc, CollectionSchema.outboundlinks_protocol_sxt, protocolList2indexedList(subgraph.urlProtocols[1]));
+ if (allAttr || contains(CollectionSchema.outboundlinks_urlstub_txt)) add(doc, CollectionSchema.outboundlinks_urlstub_txt, subgraph.urlStubs[1]);
+
+ // charset
+ if (allAttr || contains(CollectionSchema.charset_s)) add(doc, CollectionSchema.charset_s, document.getCharset());
+
+ // coordinates
+ if (document.lat() != 0.0 && document.lon() != 0.0) {
+ if (allAttr || contains(CollectionSchema.coordinate_p)) add(doc, CollectionSchema.coordinate_p, Double.toString(document.lat()) + "," + Double.toString(document.lon()));
+ }
+ if (allAttr || contains(CollectionSchema.httpstatus_i)) add(doc, CollectionSchema.httpstatus_i, responseHeader == null ? 200 : responseHeader.getStatusCode());
+
+ // fields that were additionally in URIMetadataRow
+ Date loadDate = new Date();
+ Date modDate = responseHeader == null ? new Date() : responseHeader.lastModified();
+ if (modDate.getTime() > loadDate.getTime()) modDate = loadDate;
+ int size = (int) Math.max(document.dc_source().length(), responseHeader == null ? 0 : responseHeader.getContentLength());
+ if (allAttr || contains(CollectionSchema.load_date_dt)) add(doc, CollectionSchema.load_date_dt, loadDate);
+ if (allAttr || contains(CollectionSchema.fresh_date_dt)) add(doc, CollectionSchema.fresh_date_dt, new Date(loadDate.getTime() + Math.max(0, loadDate.getTime() - modDate.getTime()) / 2)); // freshdate, computed with Proxy-TTL formula
+ if (allAttr || contains(CollectionSchema.host_id_s)) add(doc, CollectionSchema.host_id_s, document.dc_source().hosthash());
+ if ((allAttr || contains(CollectionSchema.referrer_id_txt)) && referrerURL != null) add(doc, CollectionSchema.referrer_id_txt, new String[]{ASCII.String(referrerURL.hash())});
+ //if (allAttr || contains(SolrField.md5_s)) add(solrdoc, SolrField.md5_s, new byte[0]);
+ if (allAttr || contains(CollectionSchema.publisher_t)) add(doc, CollectionSchema.publisher_t, document.dc_publisher());
+ if ((allAttr || contains(CollectionSchema.language_s)) && language != null) add(doc, CollectionSchema.language_s, language);
+ if (allAttr || contains(CollectionSchema.size_i)) add(doc, CollectionSchema.size_i, size);
+ if (allAttr || contains(CollectionSchema.audiolinkscount_i)) add(doc, CollectionSchema.audiolinkscount_i, document.getAudiolinks().size());
+ if (allAttr || contains(CollectionSchema.videolinkscount_i)) add(doc, CollectionSchema.videolinkscount_i, document.getVideolinks().size());
+ if (allAttr || contains(CollectionSchema.applinkscount_i)) add(doc, CollectionSchema.applinkscount_i, document.getApplinks().size());
+
+ // write generic navigation
+ // there are no pre-defined solr fields for navigation because the vocabulary is generic
+ // we use dynamically allocated solr fields for this.
+ // It must be a multi-value string/token field, therefore we use _sxt extensions for the field names
+ for (Map.Entry<String, Set<String>> facet: document.getGenericFacets().entrySet()) {
+ String facetName = facet.getKey();
+ Set<String> facetValues = facet.getValue();
+ doc.setField(CollectionSchema.VOCABULARY_PREFIX + facetName + CollectionSchema.VOCABULARY_SUFFIX, facetValues.toArray(new String[facetValues.size()]));
+ }
+
+ if (allAttr || contains(CollectionSchema.process_sxt)) {
+ List<String> p = new ArrayList<String>();
+ for (ProcessType t: processTypes) p.add(t.name());
+ add(doc, CollectionSchema.process_sxt, p);
+ }
+ return doc;
+ }
+
+ /**
+ * compute the click level using the citation reference database
+ * @param citations the citation database
+ * @param searchhash the hash of the url to be checked
+ * @return the clickdepth level or -1 if the root url cannot be found or a recursion limit is reached
+ * @throws IOException
+ */
+ public static int getClickDepth(final IndexCell<CitationReference> citations, final DigestURI url) throws IOException {
+
+ final byte[] searchhash = url.hash();
+ RowHandleSet rootCandidates = url.getPossibleRootHashes();
+
+ RowHandleSet ignore = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100); // a set of urlhashes to be ignored. This is generated from all hashes that are seen during recursion to prevent enless loops
+ RowHandleSet levelhashes = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 1); // all hashes of a clickdepth. The first call contains the target hash only and therefore just one entry
+ try {levelhashes.put(searchhash);} catch (SpaceExceededException e) {throw new IOException(e);}
+ int leveldepth = 0; // the recursion depth and therefore the result depth-1. Shall be 0 for the first call
+ final byte[] hosthash = new byte[6]; // the host of the url to be checked
+ System.arraycopy(searchhash, 6, hosthash, 0, 6);
+
+ long timeout = System.currentTimeMillis() + 10000;
+ for (int maxdepth = 0; maxdepth < 10 && System.currentTimeMillis() < timeout; maxdepth++) {
+
+ RowHandleSet checknext = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100);
+
+ // loop over all hashes at this clickdepth; the first call to this loop should contain only one hash and a leveldepth = 0
+ checkloop: for (byte[] urlhash: levelhashes) {
+
+ // get all the citations for this url and iterate
+ ReferenceContainer<CitationReference> references = citations.get(urlhash, null);
+ if (references == null || references.size() == 0) continue checkloop; // don't know
+ Iterator<CitationReference> i = references.entries();
+ nextloop: while (i.hasNext()) {
+ CitationReference ref = i.next();
+ if (ref == null) continue nextloop;
+ byte[] u = ref.urlhash();
+
+ // check ignore
+ if (ignore.has(u)) continue nextloop;
+
+ // check if this is from the same host
+ if (!ByteBuffer.equals(u, 6, hosthash, 0, 6)) continue nextloop;
+
+ // check if the url is a root url
+ if (rootCandidates.has(u)) {
+ return leveldepth + 1;
+ }
+
+ // step to next depth level
+ try {checknext.put(u);} catch (SpaceExceededException e) {}
+ try {ignore.put(u);} catch (SpaceExceededException e) {}
+ }
+ }
+ leveldepth++;
+ levelhashes = checknext;
+
+ }
+ return -1;
+ }
+
+ /**
+ * this method compresses a list of protocol names to an indexed list.
+ * To do this, all 'http' entries are removed and considered as default.
+ * The remaining entries are indexed as follows: a list of <i>-<p> entries is produced, where
+ * <i> is an index pointing to the original index of the protocol entry and <p> is the protocol entry itself.
+ * The <i> entry is formatted as a 3-digit decimal number with leading zero digits.
+ * @param protocol
+ * @return a list of indexed protocol entries
+ */
+ private static List<String> protocolList2indexedList(List<String> protocol) {
+ List<String> a = new ArrayList<String>();
+ String p;
+ for (int i = 0; i < protocol.size(); i++) {
+ p = protocol.get(i);
+ if (!p.equals("http")) {
+ String c = Integer.toString(i);
+ while (c.length() < 3) c = "0" + c;
+ a.add(c + "-" + p);
+ }
+ }
+ return a;
+ }
+
+ /**
+ * encode a string containing attributes from anchor rel properties binary:
+ * bit 0: "me" contained in rel
+ * bit 1: "nofollow" contained in rel
+ * @param rel
+ * @return binary encoded information about rel
+ */
+ /*
+ private static List<Integer> relEval(final List<String> rel) {
+ List<Integer> il = new ArrayList<Integer>(rel.size());
+ for (final String s: rel) {
+ int i = 0;
+ final String s0 = s.toLowerCase().trim();
+ if ("me".equals(s0)) i += 1;
+ if ("nofollow".equals(s0)) i += 2;
+ il.add(i);
+ }
+ return il;
+ }
+ */
+
+ /**
+ * register an entry as error document
+ * @param digestURI
+ * @param failReason
+ * @param httpstatus
+ * @throws IOException
+ */
+ public SolrInputDocument err(final DigestURI digestURI, final String failReason, final FailType failType, final int httpstatus) throws IOException {
+ final SolrInputDocument solrdoc = new SolrInputDocument();
+ add(solrdoc, CollectionSchema.id, ASCII.String(digestURI.hash()));
+ add(solrdoc, CollectionSchema.sku, digestURI.toNormalform(true));
+ final InetAddress address = digestURI.getInetAddress();
+ if (contains(CollectionSchema.ip_s) && address != null) add(solrdoc, CollectionSchema.ip_s, address.getHostAddress());
+ if (contains(CollectionSchema.host_s) && digestURI.getHost() != null) add(solrdoc, CollectionSchema.host_s, digestURI.getHost());
+
+ // path elements of link
+ if (contains(CollectionSchema.url_paths_sxt)) add(solrdoc, CollectionSchema.url_paths_sxt, digestURI.getPaths());
+ if (contains(CollectionSchema.url_file_ext_s)) add(solrdoc, CollectionSchema.url_file_ext_s, digestURI.getFileExtension());
+
+ // fail reason and status
+ if (contains(CollectionSchema.failreason_t)) add(solrdoc, CollectionSchema.failreason_t, failReason);
+ if (contains(CollectionSchema.failtype_s)) add(solrdoc, CollectionSchema.failtype_s, failType.name());
+ if (contains(CollectionSchema.httpstatus_i)) add(solrdoc, CollectionSchema.httpstatus_i, httpstatus);
+ return solrdoc;
+ }
+
+
+ /*
+ standard solr schema
+
+ <field name="name" type="textgen" indexed="true" stored="true"/>
+ <field name="cat" type="string" indexed="true" stored="true" multiValued="true"/>
+ <field name="features" type="text" indexed="true" stored="true" multiValued="true"/>
+ <field name="includes" type="text" indexed="true" stored="true" termVectors="true" termPositions="true" termOffsets="true" />
+
+ <field name="weight" type="float" indexed="true" stored="true"/>
+ <field name="price" type="float" indexed="true" stored="true"/>
+ <field name="popularity" type="int" indexed="true" stored="true" />
+
+ <!-- Common metadata fields, named specifically to match up with
+ SolrCell metadata when parsing rich documents such as Word, PDF.
+ Some fields are multiValued only because Tika currently may return
+ multiple values for them.
+ -->
+ <field name="title" type="text" indexed="true" stored="true" multiValued="true"/>
+ <field name="subject" type="text" indexed="true" stored="true"/>
+ <field name="description" type="text" indexed="true" stored="true"/>
+ <field name="comments" type="text" indexed="true" stored="true"/>
+ <field name="author" type="textgen" indexed="true" stored="true"/>
+ <field name="keywords" type="textgen" indexed="true" stored="true"/>
+ <field name="category" type="textgen" indexed="true" stored="true"/>
+ <field name="content_type" type="string" indexed="true" stored="true" multiValued="true"/>
+ <field name="last_modified" type="date" indexed="true" stored="true"/>
+ <field name="links" type="string" indexed="true" stored="true" multiValued="true"/>
+ */
+}
diff --cc source/net/yacy/search/schema/WebgraphConfiguration.java
index 573034785,000000000..8b3bdeadc
mode 100644,000000..100644
--- a/source/net/yacy/search/schema/WebgraphConfiguration.java
+++ b/source/net/yacy/search/schema/WebgraphConfiguration.java
@@@ -1,284 -1,0 +1,305 @@@
+/**
+ * WebgraphConfiguration
+ * Copyright 2011 by Michael Peter Christen
+ * First released 14.04.2011 at http://yacy.net
+ *
+ * $LastChangedDate: 2011-04-14 22:05:04 +0200 (Do, 14 Apr 2011) $
+ * $LastChangedRevision: 7654 $
+ * $LastChangedBy: orbiter $
+ *
+ * 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.schema;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
++import org.apache.solr.common.SolrDocument;
+import org.apache.solr.common.SolrInputDocument;
+
+import net.yacy.cora.document.ASCII;
+import net.yacy.cora.federate.solr.SchemaConfiguration;
+import net.yacy.cora.federate.solr.SchemaDeclaration;
+import net.yacy.cora.protocol.Domains;
+import net.yacy.cora.protocol.ResponseHeader;
+import net.yacy.cora.util.CommonPattern;
+import net.yacy.document.parser.html.ImageEntry;
+import net.yacy.kelondro.data.meta.DigestURI;
+import net.yacy.kelondro.logging.Log;
+
+public class WebgraphConfiguration extends SchemaConfiguration implements Serializable {
+
+ private static final long serialVersionUID=-499100932212840385L;
+
+ /**
+ * initialize with an empty ConfigurationSet which will cause that all the index
+ * attributes are used
+ */
+ public WebgraphConfiguration() {
+ super();
+ this.lazy = false;
+ }
+
+ /**
+ * initialize the schema with a given configuration file
+ * the configuration file simply contains a list of lines with keywords
+ * or keyword = value lines (while value is a custom Solr field name
+ * @param configurationFile
+ */
+ public WebgraphConfiguration(final File configurationFile, boolean lazy) {
+ super(configurationFile);
+ this.lazy = lazy;
+ // check consistency: compare with YaCyField enum
+ if (this.isEmpty()) return;
+ Iterator<Entry> it = this.entryIterator();
+ for (SchemaConfiguration.Entry etr = it.next(); it.hasNext(); etr = it.next()) {
+ try {
+ WebgraphSchema f = WebgraphSchema.valueOf(etr.key());
+ f.setSolrFieldName(etr.getValue());
+ } catch (IllegalArgumentException e) {
+ Log.logFine("SolrWebgraphWriter", "solr schema file " + configurationFile.getAbsolutePath() + " defines unknown attribute '" + etr.toString() + "'");
+ it.remove();
+ }
+ }
+ // check consistency the other way: look if all enum constants in SolrField appear in the configuration file
+ for (SchemaDeclaration field: WebgraphSchema.values()) {
+ if (this.get(field.name()) == null) {
+ Log.logWarning("SolrWebgraphWriter", " solr schema file " + configurationFile.getAbsolutePath() + " is missing declaration for '" + field.name() + "'");
+ }
+ }
+ }
+
+ public static class Subgraph {
+ public final ArrayList<String>[] tags, urlProtocols, urlStubs;
+ public final ArrayList<SolrInputDocument> edges;
+ @SuppressWarnings("unchecked")
+ public Subgraph(int inboundSize, int outboundSize) {
+ this.tags = new ArrayList[]{new ArrayList<String>(inboundSize), new ArrayList<String>(outboundSize)};
+ this.urlProtocols = new ArrayList[]{new ArrayList<String>(inboundSize), new ArrayList<String>(outboundSize)};
+ this.urlStubs = new ArrayList[]{new ArrayList<String>(inboundSize), new ArrayList<String>(outboundSize)};
+ this.edges = new ArrayList<SolrInputDocument>(inboundSize + outboundSize);
+ }
+ }
+
+ public Subgraph edges(
+ final DigestURI source, final ResponseHeader responseHeader, String[] collections, int clickdepth,
+ final Map<DigestURI, Properties> alllinks,
+ final Map<DigestURI, ImageEntry> images,
+ final Set<DigestURI> inboundLinks,
+ final Set<DigestURI> outboundLinks
+ ) {
+ boolean allAttr = this.isEmpty();
+ Subgraph subgraph = new Subgraph(inboundLinks.size(), outboundLinks.size());
+ addEdges(subgraph, source, responseHeader, collections, clickdepth, allAttr, alllinks, images, true, inboundLinks);
+ addEdges(subgraph, source, responseHeader, collections, clickdepth, allAttr, alllinks, images, false, outboundLinks);
+ return subgraph;
+ }
+
+ private void addEdges(
+ final Subgraph subgraph,
+ final DigestURI source, final ResponseHeader responseHeader, String[] collections, int clickdepth,
+ final boolean allAttr, final Map<DigestURI, Properties> alllinks, final Map<DigestURI, ImageEntry> images,
+ final boolean inbound, final Set<DigestURI> links) {
+ for (final DigestURI target_url: links) {
+ final Properties p = alllinks.get(target_url);
+ if (p == null) continue;
+ final String name = p.getProperty("name", ""); // the name attribute
+ final String text = p.getProperty("text", ""); // the text between the <a></a> tag
+ final String rel = p.getProperty("rel", ""); // the rel-attribute
+ int ioidx = inbound ? 0 : 1;
+
+ // index organization
+ StringBuilder idi = new StringBuilder(8);
+ idi.append(Integer.toHexString((name + text + rel).hashCode()).toLowerCase());
+ while (idi.length() < 8) idi.insert(0, '0');
+ String source_id = ASCII.String(source.hash());
+ String target_id = ASCII.String(target_url.hash());
+ StringBuilder id = new StringBuilder(source_id).append(target_id).append(idi);
+ SolrInputDocument edge = new SolrInputDocument();
+ add(edge, WebgraphSchema.id, id.toString());
+ if (allAttr || contains(WebgraphSchema.load_date_dt)) {
+ Date loadDate = new Date();
+ Date modDate = responseHeader == null ? new Date() : responseHeader.lastModified();
+ if (modDate.getTime() > loadDate.getTime()) modDate = loadDate;
+ add(edge, WebgraphSchema.load_date_dt, loadDate);
+ }
+ if (allAttr || contains(WebgraphSchema.last_modified)) add(edge, WebgraphSchema.last_modified, responseHeader == null ? new Date() : responseHeader.lastModified());
+ add(edge, WebgraphSchema.collection_sxt, collections);
+
+ // add the source attributes
+ add(edge, WebgraphSchema.source_id_s, source_id);
+ final String source_url_string = source.toNormalform(false);
+ int pr_source = source_url_string.indexOf("://",0);
+ if (allAttr || contains(WebgraphSchema.source_protocol_s)) add(edge, WebgraphSchema.source_protocol_s, source_url_string.substring(0, pr_source));
+ if (allAttr || contains(WebgraphSchema.source_urlstub_s)) add(edge, WebgraphSchema.source_urlstub_s, source_url_string.substring(pr_source + 3));
+ Map<String, String> source_searchpart = source.getSearchpartMap();
+ if (source_searchpart == null) {
+ if (allAttr || contains(WebgraphSchema.source_parameter_count_i)) add(edge, WebgraphSchema.source_parameter_count_i, 0);
+ } else {
+ if (allAttr || contains(WebgraphSchema.source_parameter_count_i)) add(edge, WebgraphSchema.source_parameter_count_i, source_searchpart.size());
+ if (allAttr || contains(WebgraphSchema.source_parameter_key_sxt)) add(edge, WebgraphSchema.source_parameter_key_sxt, source_searchpart.keySet().toArray(new String[source_searchpart.size()]));
+ if (allAttr || contains(WebgraphSchema.source_parameter_value_sxt)) add(edge, WebgraphSchema.source_parameter_value_sxt, source_searchpart.values().toArray(new String[source_searchpart.size()]));
+ }
+ if (allAttr || contains(WebgraphSchema.source_chars_i)) add(edge, WebgraphSchema.source_chars_i, source_url_string.length());
+ String source_host = null;
+ if ((source_host = source.getHost()) != null) {
+ String dnc = Domains.getDNC(source_host);
+ String subdomOrga = source_host.length() - dnc.length() <= 0 ? "" : source_host.substring(0, source_host.length() - dnc.length() - 1);
+ int pp = subdomOrga.lastIndexOf('.');
+ String subdom = (pp < 0) ? "" : subdomOrga.substring(0, pp);
+ String orga = (pp < 0) ? subdomOrga : subdomOrga.substring(pp + 1);
+ if (allAttr || contains(WebgraphSchema.source_host_s)) add(edge, WebgraphSchema.source_host_s, source_host);
+ if (allAttr || contains(WebgraphSchema.source_host_id_s)) add(edge, WebgraphSchema.source_host_id_s, source.hosthash());
+ if (allAttr || contains(WebgraphSchema.source_host_dnc_s)) add(edge, WebgraphSchema.source_host_dnc_s, dnc);
+ if (allAttr || contains(WebgraphSchema.source_host_organization_s)) add(edge, WebgraphSchema.source_host_organization_s, orga);
+ if (allAttr || contains(WebgraphSchema.source_host_organizationdnc_s)) add(edge, WebgraphSchema.source_host_organizationdnc_s, orga + '.' + dnc);
+ if (allAttr || contains(WebgraphSchema.source_host_subdomain_s)) add(edge, WebgraphSchema.source_host_subdomain_s, subdom);
+ }
+ if (allAttr || contains(WebgraphSchema.source_file_ext_s)) add(edge, WebgraphSchema.source_file_ext_s, source.getFileExtension());
+ if (allAttr || contains(WebgraphSchema.source_path_s)) add(edge, WebgraphSchema.source_path_s, source.getPath());
+ if (allAttr || contains(WebgraphSchema.source_path_folders_count_i) || contains(WebgraphSchema.source_path_folders_sxt)) {
+ String[] paths = source.getPaths();
+ add(edge, WebgraphSchema.source_path_folders_count_i, paths.length);
+ add(edge, WebgraphSchema.source_path_folders_sxt, paths);
+ }
+ add(edge, WebgraphSchema.source_clickdepth_i, clickdepth);
+
+ // add the source attributes about the target
+ if (allAttr || contains(WebgraphSchema.target_inbound_b)) add(edge, WebgraphSchema.target_inbound_b, inbound);
+ if (allAttr || contains(WebgraphSchema.target_name_t)) add(edge, WebgraphSchema.target_name_t, name.length() > 0 ? name : "");
+ if (allAttr || contains(WebgraphSchema.target_rel_s)) add(edge, WebgraphSchema.target_rel_s, rel.length() > 0 ? rel : "");
+ if (allAttr || contains(WebgraphSchema.target_relflags_i)) add(edge, WebgraphSchema.target_relflags_i, relEval(rel.length() > 0 ? rel : ""));
+ if (allAttr || contains(WebgraphSchema.target_linktext_t)) add(edge, WebgraphSchema.target_linktext_t, text.length() > 0 ? text : "");
+ if (allAttr || contains(WebgraphSchema.target_linktext_charcount_i)) add(edge, WebgraphSchema.target_linktext_charcount_i, text.length());
+ if (allAttr || contains(WebgraphSchema.target_linktext_wordcount_i)) add(edge, WebgraphSchema.target_linktext_wordcount_i, text.length() > 0 ? CommonPattern.SPACE.split(text).length : 0);
+ String tag = "<a href=\"" + target_url.toNormalform(false) + "\"" + (rel.length() > 0 ? " rel=\"" + rel + "\"" : "") + (name.length() > 0 ? " name=\"" + name + "\"" : "") + ">" + ((text.length() > 0) ? text : "") + "</a>";
+ subgraph.tags[ioidx].add(tag);
+ if (allAttr || contains(WebgraphSchema.target_tag_s)) add(edge, WebgraphSchema.target_tag_s, tag);
+ ImageEntry ientry = images.get(target_url);
+ String alttext = ientry == null ? "" : ientry.alt();
+ if (allAttr || contains(WebgraphSchema.target_alt_t)) add(edge, WebgraphSchema.target_alt_t, alttext);
+ if (allAttr || contains(WebgraphSchema.target_alt_charcount_i)) add(edge, WebgraphSchema.target_alt_charcount_i, alttext.length());
+ if (allAttr || contains(WebgraphSchema.target_alt_wordcount_i)) add(edge, WebgraphSchema.target_alt_wordcount_i, alttext.length() > 0 ? CommonPattern.SPACE.split(alttext).length : 0);
+
+ // add the target attributes
+ add(edge, WebgraphSchema.target_id_s, target_id);
+ final String target_url_string = target_url.toNormalform(false);
+ int pr_target = target_url_string.indexOf("://",0);
+ subgraph.urlProtocols[ioidx].add(target_url_string.substring(0, pr_target));
+ if (allAttr || contains(WebgraphSchema.target_protocol_s)) add(edge, WebgraphSchema.target_protocol_s, target_url_string.substring(0, pr_target));
+ subgraph.urlStubs[ioidx].add(target_url_string.substring(pr_target + 3));
+ if (allAttr || contains(WebgraphSchema.target_urlstub_s)) add(edge, WebgraphSchema.target_urlstub_s, target_url_string.substring(pr_target + 3));
+ Map<String, String> target_searchpart = target_url.getSearchpartMap();
+ if (target_searchpart == null) {
+ if (allAttr || contains(WebgraphSchema.target_parameter_count_i)) add(edge, WebgraphSchema.target_parameter_count_i, 0);
+ } else {
+ if (allAttr || contains(WebgraphSchema.target_parameter_count_i)) add(edge, WebgraphSchema.target_parameter_count_i, target_searchpart.size());
+ if (allAttr || contains(WebgraphSchema.target_parameter_key_sxt)) add(edge, WebgraphSchema.target_parameter_key_sxt, target_searchpart.keySet().toArray(new String[target_searchpart.size()]));
+ if (allAttr || contains(WebgraphSchema.target_parameter_value_sxt)) add(edge, WebgraphSchema.target_parameter_value_sxt, target_searchpart.values().toArray(new String[target_searchpart.size()]));
+ }
+ if (allAttr || contains(WebgraphSchema.target_chars_i)) add(edge, WebgraphSchema.target_chars_i, target_url_string.length());
+ String target_host = null;
+ if ((target_host = target_url.getHost()) != null) {
+ String dnc = Domains.getDNC(target_host);
+ String subdomOrga = target_host.length() - dnc.length() <= 0 ? "" : target_host.substring(0, target_host.length() - dnc.length() - 1);
+ int pp = subdomOrga.lastIndexOf('.');
+ String subdom = (pp < 0) ? "" : subdomOrga.substring(0, pp);
+ String orga = (pp < 0) ? subdomOrga : subdomOrga.substring(pp + 1);
+ if (allAttr || contains(WebgraphSchema.target_host_s)) add(edge, WebgraphSchema.target_host_s, target_host);
+ if (allAttr || contains(WebgraphSchema.target_host_id_s)) add(edge, WebgraphSchema.target_host_id_s, target_url.hosthash());
+ if (allAttr || contains(WebgraphSchema.target_host_dnc_s)) add(edge, WebgraphSchema.target_host_dnc_s, dnc);
+ if (allAttr || contains(WebgraphSchema.target_host_organization_s)) add(edge, WebgraphSchema.target_host_organization_s, orga);
+ if (allAttr || contains(WebgraphSchema.target_host_organizationdnc_s)) add(edge, WebgraphSchema.target_host_organizationdnc_s, orga + '.' + dnc);
+ if (allAttr || contains(WebgraphSchema.target_host_subdomain_s)) add(edge, WebgraphSchema.target_host_subdomain_s, subdom);
+ }
+ if (allAttr || contains(WebgraphSchema.target_file_ext_s)) add(edge, WebgraphSchema.target_file_ext_s, target_url.getFileExtension());
+ if (allAttr || contains(WebgraphSchema.target_path_s)) add(edge, WebgraphSchema.target_path_s, target_url.getPath());
+ if (allAttr || contains(WebgraphSchema.target_path_folders_count_i) || contains(WebgraphSchema.target_path_folders_sxt)) {
+ String[] paths = target_url.getPaths();
+ add(edge, WebgraphSchema.target_path_folders_count_i, paths.length);
+ add(edge, WebgraphSchema.target_path_folders_sxt, paths);
+ }
+ add(edge, WebgraphSchema.target_clickdepth_i, clickdepth);
+
+ // add the edge to the subgraph
+ subgraph.edges.add(edge);
+ }
+ }
+
+ /**
+ * encode a string containing attributes from anchor rel properties binary:
+ * bit 0: "me" contained in rel
+ * bit 1: "nofollow" contained in rel
+ * @param rel
+ * @return binary encoded information about rel
+ */
+ private static int relEval(final String rels) {
+ int i = 0;
+ final String s0 = rels.toLowerCase().trim();
+ if ("me".equals(s0)) i += 1;
+ if ("nofollow".equals(s0)) i += 2;
+ return i;
+ }
+
+ /**
+ * save configuration to file and update enum SolrFields
+ * @throws IOException
+ */
+ @Override
+ public void commit() throws IOException {
+ try {
+ super.commit();
+ // make sure the enum SolrField.SolrFieldName is current
+ Iterator<Entry> it = this.entryIterator();
+ for (SchemaConfiguration.Entry etr = it.next(); it.hasNext(); etr = it.next()) {
+ try {
+ SchemaDeclaration f = WebgraphSchema.valueOf(etr.key());
+ f.setSolrFieldName(etr.getValue());
+ } catch (IllegalArgumentException e) {
+ continue;
+ }
+ }
+ } catch (final IOException e) {}
+ }
++
++
++
++ /**
++ * Convert a SolrDocument to a SolrInputDocument.
++ * This is useful if a document from the search index shall be modified and indexed again.
++ * This shall be used as replacement of ClientUtils.toSolrInputDocument because we remove some fields
++ * which are created automatically during the indexing process.
++ * @param doc the solr document
++ * @return a solr input document
++ */
++ public SolrInputDocument toSolrInputDocument(SolrDocument doc) {
++ SolrInputDocument sid = new SolrInputDocument();
++ for (String name: doc.getFieldNames()) {
++ if (this.contains(name)) { // check each field if enabled in local Solr schema
++ sid.addField(name, doc.getFieldValue(name), 1.0f);
++ }
++ }
++ return sid;
++ }
+
+}