Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
Added analysis optional setting to compute statistics on text snippets
lucciomana3ec7a7a5f7c
diff --git a/defaults/yacy.init b/defaults/yacy.initindex 9c9fa5f61..ece7ba1cc 100644--- a/defaults/yacy.init+++ b/defaults/yacy.init@@ -500,6 +500,8 @@ debug.search.remote.dht.off=falsedebug.search.remote.dht.testlocal=falsedebug.search.remote.solr.off=falsedebug.search.remote.solr.testlocal=false+# Set to true to enable computation of statistics on text snippets processing+debug.snippets.statistics.enabled=false#staticIP if you have a static IP, you can use this settingstaticIP=diff --git a/htroot/ConfigPortal_p.html b/htroot/ConfigPortal_p.htmlindex 5b6520fe8..67538a9a9 100644--- a/htroot/ConfigPortal_p.html+++ b/htroot/ConfigPortal_p.html@@ -87,6 +87,23 @@<dt>Snippet Fetch Strategy & Link Verification</dt><dd><img src="env/grafics/idea.png" width="32" height="32" alt="idea" align="center"/>Speed up search results with this option! (use CACHEONLY or FALSE to switch off verification)<br/>+ #(debug.snippets.statistics.enabled)#<i>Statistics on text snippets generation can be enabled in the <a href="Settings_p.html?page=debug">Debug/Analysis Settings</a> page.</i>+ ::<div class="info" style="float:left; margin-right : 0.1em;">+ <img src="env/grafics/i16.gif" width="16" height="16" alt="Detailed statistics"/>+ <div class="infobox">+ Counts by origin :+ <ul>+ <li>#[totalFromCache]# provided by Solr</li>+ <li>#[totalFromCache]# from cache</li>+ <li>#[totalFromMetadata]# computed from indexed metadata</li>+ <li>#[totalFromWeb]# from original documents fetched and parsed</li>+ <li>#[totalFailures]# failures</li>+ </ul>+ </div>+ </div>+ <i>#[totalSnippets]# text snippets were generated since last server startup, in a mean time of #[snippetsMeanTime]# and a maximum of #[snippetsMaxTime]#.</i>+ #(/debug.snippets.statistics.enabled)#+ <br/><input type="radio" name="search.verify" value="nocache" #(search.verify.nocache)#::checked="checked"#(/search.verify.nocache)# onclick="document.getElementById('search_verify_delete').disabled=false;document.getElementById('search_verify_delete').checked=true;"/> NOCACHE: no use of web cache, load all snippets online<br/><input type="radio" name="search.verify" value="iffresh" #(search.verify.iffresh)#::checked="checked"#(/search.verify.iffresh)# onclick="document.getElementById('search_verify_delete').disabled=false;document.getElementById('search_verify_delete').checked=true;"/> IFFRESH: use the cache if the cache exists and is fresh otherwise load online<br/><input type="radio" name="search.verify" value="ifexist" #(search.verify.ifexist)#::checked="checked"#(/search.verify.ifexist)# onclick="document.getElementById('search_verify_delete').disabled=false;document.getElementById('search_verify_delete').checked=true;"/> IFEXIST: use the cache if the cache exist or load online<br/>diff --git a/htroot/ConfigPortal_p.java b/htroot/ConfigPortal_p.javaindex 4387cac1e..b69ab3c3c 100644--- a/htroot/ConfigPortal_p.java+++ b/htroot/ConfigPortal_p.java@@ -30,6 +30,7 @@ import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.net.MalformedURLException;+import java.time.Duration;import java.util.Properties;import net.yacy.cora.document.id.DigestURL;@@ -41,6 +42,7 @@ import net.yacy.http.servlets.YaCyDefaultServlet;import net.yacy.search.Switchboard;import net.yacy.search.SwitchboardConstants;import net.yacy.search.query.SearchEventCache;+import net.yacy.search.snippet.TextSnippet;import net.yacy.server.serverObjects;import net.yacy.server.serverSwitch;import net.yacy.server.http.HTTPDFileHandler;@@ -218,6 +220,11 @@ public class ConfigPortal_p {prop.put(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,sb.getConfigBool(SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT) ? 1 : 0);++ final boolean textSnippetsStatisticsEnabled = sb.getConfigBool(+ SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED,+ SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED_DEFAULT);+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED, textSnippetsStatisticsEnabled);prop.put(SwitchboardConstants.GREEDYLEARNING_ACTIVE, sb.getConfigBool(SwitchboardConstants.GREEDYLEARNING_ACTIVE, false) ? 1 : 0);prop.put(SwitchboardConstants.GREEDYLEARNING_LIMIT_DOCCOUNT, sb.getConfig(SwitchboardConstants.GREEDYLEARNING_LIMIT_DOCCOUNT, "0"));@@ -229,6 +236,28 @@ public class ConfigPortal_p {} else {prop.put(SwitchboardConstants.REMOTESEARCH_RESULT_STORE_MAXSIZE, "");}++ /* Provide some basic stats about text snippets generation time to help choosing snippet options */+ if(textSnippetsStatisticsEnabled) {+ final long totalSnippets = TextSnippet.statistics.getTotalSnippets();+ final long totalSnippetsInitTime = TextSnippet.statistics.getTotalInitTime();+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_totalSnippets", totalSnippets);+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_totalFromSolr",+ TextSnippet.statistics.getTotalFromSolr());+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_totalFromCache",+ TextSnippet.statistics.getTotalFromCache());+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_totalFromMetadata",+ TextSnippet.statistics.getTotalFromMetadata());+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_totalFromWeb",+ TextSnippet.statistics.getTotalFromWeb());+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_totalFailures",+ TextSnippet.statistics.getTotalFailures());+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_snippetsMeanTime",+ formatDuration(totalSnippets > 0 ? totalSnippetsInitTime / totalSnippets : 0));++ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED + "_snippetsMaxTime",+ formatDuration(TextSnippet.statistics.getMaxInitTime()));+ }prop.put("search.verify.nocache", sb.getConfig("search.verify", "").equals("nocache") ? 1 : 0);prop.put("search.verify.iffresh", sb.getConfig("search.verify", "").equals("iffresh") ? 1 : 0);@@ -279,4 +308,20 @@ public class ConfigPortal_p {return prop;}+ /**+ * @param durationValue a duration in milliseconds+ * @return the duration value formatted for display with its time unit+ */+ private static String formatDuration(final long durationValue) {+ final Duration duration = Duration.ofMillis(durationValue);++ final String formattedDuration;+ if(duration.getSeconds() > 0) {+ formattedDuration = duration.getSeconds() + "s";+ } else {+ formattedDuration = duration.toMillis() + "ms";+ }+ return formattedDuration;+ }+}diff --git a/htroot/SettingsAck_p.java b/htroot/SettingsAck_p.javaindex 0e07b8014..aecc0e4ad 100644--- a/htroot/SettingsAck_p.java+++ b/htroot/SettingsAck_p.java@@ -43,6 +43,7 @@ import net.yacy.peers.operation.yacySeedUploader;import net.yacy.search.Switchboard;import net.yacy.search.SwitchboardConstants;import net.yacy.search.query.SearchEventCache;+import net.yacy.search.snippet.TextSnippet;import net.yacy.server.serverCore;import net.yacy.server.serverObjects;import net.yacy.server.serverSwitch;@@ -580,6 +581,10 @@ public class SettingsAck_p {tickedCheckbox = post.containsKey("searchShowRanking");env.setConfig(SwitchboardConstants.SEARCH_RESULT_SHOW_RANKING, tickedCheckbox);+ tickedCheckbox = post.containsKey(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED);+ sb.setConfig(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED, tickedCheckbox);+ TextSnippet.statistics.setEnabled(tickedCheckbox);+/* For easier user understanding, the following flags controlling data sources selection* are rendered in the UI as checkboxes corresponding to enabled value when ticked */tickedCheckbox = post.containsKey("searchLocalDHT");diff --git a/htroot/Settings_Debug.inc b/htroot/Settings_Debug.incindex 7e5f840e0..750c7bf3f 100644--- a/htroot/Settings_Debug.inc+++ b/htroot/Settings_Debug.inc@@ -138,6 +138,26 @@</div></fieldset>+ <fieldset>+ <legend>Text snippets statistics</legend>++ <div class="form-group">+ <div class="col-sm-4">+ <div class="checkbox">+ <label>+ <input name="debug.snippets.statistics.enabled" id="snippetsStatsEnabled"+ type="checkbox" #(debug.snippets.statistics.enabled)#::checked#(/debug.snippets.statistics.enabled)#+ aria-describedby="snippetStatisticsInfo"/>+ Enable text snippets statistics+ </label>+ </div>+ </div>+ <div class="col-sm-8" id="snippetStatisticsInfo">+ When checked, statistics are collected on text snippets generation for search results. The are resumed in the <a href="ConfigPortal_p.html">Portal Configuration</a> page.+ </div>+ </div>+ </fieldset>+<div class="col-sm-6"><input type="submit" class="btn btn-primary" name="debugAnalysisSettings" value="Submit" aria-describedby="submitInfo"/><em id="submitInfo">Changes will take effect immediately.</em>diff --git a/htroot/Settings_p.java b/htroot/Settings_p.javaindex 773cf71c4..e2b6f2d2b 100644--- a/htroot/Settings_p.java+++ b/htroot/Settings_p.java@@ -241,6 +241,10 @@ public final class Settings_p {prop.put("searchShowRankingChecked", env.getConfigBool(SwitchboardConstants.SEARCH_RESULT_SHOW_RANKING, SwitchboardConstants.SEARCH_RESULT_SHOW_RANKING_DEFAULT) ? 1 : 0);+ prop.put(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED,+ sb.getConfigBool(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED,+ SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED_DEFAULT));+// return rewrite propertiesreturn prop;}diff --git a/source/net/yacy/search/Switchboard.java b/source/net/yacy/search/Switchboard.javaindex 3cd616cac..5134bcb45 100644--- a/source/net/yacy/search/Switchboard.java+++ b/source/net/yacy/search/Switchboard.java@@ -225,6 +225,7 @@ import net.yacy.search.ranking.RankingProfile;import net.yacy.search.schema.CollectionConfiguration;import net.yacy.search.schema.CollectionSchema;import net.yacy.search.schema.WebgraphConfiguration;+import net.yacy.search.snippet.TextSnippet;import net.yacy.server.serverCore;import net.yacy.server.serverSwitch;import net.yacy.server.http.RobotsTxtConfig;@@ -959,6 +960,9 @@ public final class Switchboard extends serverSwitch {// generate snippets cachethis.log.config("Initializing Snippet Cache");++ TextSnippet.statistics.setEnabled(getConfigBool(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED,+ SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED_DEFAULT));// init the wikiwikiParser = new WikiCode();diff --git a/source/net/yacy/search/SwitchboardConstants.java b/source/net/yacy/search/SwitchboardConstants.javaindex 5f150fee6..f74d204cb 100644--- a/source/net/yacy/search/SwitchboardConstants.java+++ b/source/net/yacy/search/SwitchboardConstants.java@@ -374,6 +374,12 @@ public final class SwitchboardConstants {/** when set to true : do not use dht, search local peer in a shortcut to the own server */public static final String DEBUG_SEARCH_REMOTE_SOLR_TESTLOCAL= "debug.search.remote.solr.testlocal";+ /** Key of the setting controlling whether text snippets statistics should be computed */+ public static final String DEBUG_SNIPPETS_STATISTICS_ENABLED = "debug.snippets.statistics.enabled";++ /** Default value for the setting controlling whether text snippets statistics should be computed */+ public static final boolean DEBUG_SNIPPETS_STATISTICS_ENABLED_DEFAULT = false;+/*** <p><code>public static final String <strong>WORDCACHE_MAX_COUNT</strong> = "wordCacheMaxCount"</code></p>* <p>Name of the setting how many words the word-cache (or DHT-Out cache) shall contain maximal. Indexing pages if thediff --git a/source/net/yacy/search/query/SearchEvent.java b/source/net/yacy/search/query/SearchEvent.javaindex 186bce696..0acdfd823 100644--- a/source/net/yacy/search/query/SearchEvent.java+++ b/source/net/yacy/search/query/SearchEvent.java@@ -1874,7 +1874,7 @@ public final class SearchEvent implements ScoreMapUpdatesListener {LinkedHashSet<String> solrsnippetlines = this.snippets.remove(ASCII.String(node.hash())); // we can remove this because it's used only onceif (solrsnippetlines != null && solrsnippetlines.size() > 0) {OpensearchResponseWriter.removeSubsumedTitle(solrsnippetlines, node.dc_title());- final TextSnippet solrsnippet = new TextSnippet(node.hash(), OpensearchResponseWriter.getLargestSnippet(solrsnippetlines), true, ResultClass.SOURCE_CACHE, "");+ final TextSnippet solrsnippet = new TextSnippet(node.hash(), OpensearchResponseWriter.getLargestSnippet(solrsnippetlines), true, ResultClass.SOURCE_SOLR, "");final TextSnippet yacysnippet = new TextSnippet(this.loader,node,this.query.getQueryGoal().getIncludeHashes(),diff --git a/source/net/yacy/search/snippet/TextSnippet.java b/source/net/yacy/search/snippet/TextSnippet.javaindex c04d73958..5da937dce 100644--- a/source/net/yacy/search/snippet/TextSnippet.java+++ b/source/net/yacy/search/snippet/TextSnippet.java@@ -60,6 +60,7 @@ import net.yacy.search.query.QueryGoal;public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnippet> {+ /** The maximum number of sinppet entries in the cache */private static final int MAX_CACHE = 1000;@@ -111,11 +112,19 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip}public static final Cache snippetsCache = new Cache();++ /** Handle statistics on TextSnippet processing */+ public static final TextSnippetStatistics statistics = new TextSnippetStatistics();public static enum ResultClass {+ /** Snippet provided by Solr */+ SOURCE_SOLR(false),+ /** Snippet retrieved from snippets cache or computed from cached document */SOURCE_CACHE(false),SOURCE_FILE(false),+ /** Snippet computed from the original document fetched and parsed */SOURCE_WEB(false),+ /** Snippet computed by YaCy from document metadata */SOURCE_METADATA(false),ERROR_NO_HASH_GIVEN(true),ERROR_SOURCE_LOADING(true),@@ -150,7 +159,8 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnipfinal boolean isMarked,final ResultClass errorCode,final String errortext) {- init(urlhash, line, isMarked, errorCode, errortext);+ long beginTime = System.currentTimeMillis();+ init(urlhash, line, isMarked, errorCode, errortext, beginTime);}public TextSnippet(@@ -161,23 +171,24 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnipfinal boolean pre,final int snippetMaxLength,final boolean reindexing) {+ long beginTime = System.currentTimeMillis();// heise = "0OQUNU3JSs05"final DigestURL url = row.url();if (queryhashes.isEmpty()) {//System.out.println("found no queryhashes for URL retrieve " + url);- init(url.hash(), null, false, ResultClass.ERROR_NO_HASH_GIVEN, "no query hashes given");+ init(url.hash(), null, false, ResultClass.ERROR_NO_HASH_GIVEN, "no query hashes given", beginTime);return;}// try to get snippet from snippetCache- final ResultClass source = ResultClass.SOURCE_CACHE;+ ResultClass source = ResultClass.SOURCE_CACHE;final String wordhashes = RemoteSearch.set2string(queryhashes);final String urls = ASCII.String(url.hash());final String snippetLine = snippetsCache.get(wordhashes, urls);if (snippetLine != null) {// found the snippet- init(url.hash(), snippetLine, false, source, null);+ init(url.hash(), snippetLine, false, source, null, beginTime);return;}@@ -228,7 +239,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip}if (sentences == null) {// not found the snippet- init(url.hash(), null, false, ResultClass.SOURCE_METADATA, null);+ init(url.hash(), null, false, ResultClass.SOURCE_METADATA, null, beginTime);return;}@@ -238,7 +249,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSniptextline = tsr.getSnippet();remainingHashes = tsr.getRemainingWords();} catch (final UnsupportedOperationException e) {- init(url.hash(), null, false, ResultClass.ERROR_NO_MATCH, "snippet extractor failed:" + e.getMessage());+ init(url.hash(), null, false, ResultClass.ERROR_NO_MATCH, "snippet extractor failed:" + e.getMessage(), beginTime);return;}}@@ -282,7 +293,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip}}}- init(url.hash(), textline.length() > 0 ? textline : this.line, false, ResultClass.SOURCE_METADATA, null);+ init(url.hash(), textline.length() > 0 ? textline : this.line, false, ResultClass.SOURCE_METADATA, null, beginTime);return;}sentences = null; // we don't need this here any more@@ -298,19 +309,19 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnipif (response == null) {// in case that we did not get any result we can still return a success when we are not allowed to go onlineif (cacheStrategy == null || cacheStrategy.mustBeOffline()) {- init(url.hash(), null, false, ResultClass.ERROR_SOURCE_LOADING, "omitted network load (not allowed), no cache entry");+ init(url.hash(), null, false, ResultClass.ERROR_SOURCE_LOADING, "omitted network load (not allowed), no cache entry", beginTime);return;}// if it is still not available, report an error- init(url.hash(), null, false, ResultClass.ERROR_RESOURCE_LOADING, "error loading resource from net, no cache entry");+ init(url.hash(), null, false, ResultClass.ERROR_RESOURCE_LOADING, "error loading resource from net, no cache entry", beginTime);return;}if (!response.fromCache()) {// place entry on indexing queueSwitchboard.getSwitchboard().toIndexer(response);- this.resultStatus = ResultClass.SOURCE_WEB;+ source = ResultClass.SOURCE_WEB;}// parse the document to get all sentenced; available for snippet computation@@ -318,11 +329,11 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSniptry {document = Document.mergeDocuments(response.url(), response.getMimeType(), response.parse());} catch (final Parser.Failure e) {- init(url.hash(), null, false, ResultClass.ERROR_PARSER_FAILED, e.getMessage()); // cannot be parsed+ init(url.hash(), null, false, ResultClass.ERROR_PARSER_FAILED, e.getMessage(), beginTime); // cannot be parsedreturn;}if (document == null) {- init(url.hash(), null, false, ResultClass.ERROR_PARSER_FAILED, "parser error/failed"); // cannot be parsed+ init(url.hash(), null, false, ResultClass.ERROR_PARSER_FAILED, "parser error/failed", beginTime); // cannot be parsedreturn;}@@ -331,7 +342,7 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnipdocument.close();if (sentences == null) {- init(url.hash(), null, false, ResultClass.ERROR_PARSER_NO_LINES, "parser returned no sentences");+ init(url.hash(), null, false, ResultClass.ERROR_PARSER_NO_LINES, "parser returned no sentences", beginTime);return;}@@ -340,20 +351,20 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSniptextline = tsr.getSnippet();remainingHashes = tsr.getRemainingWords();} catch (final UnsupportedOperationException e) {- init(url.hash(), null, false, ResultClass.ERROR_NO_MATCH, "snippet extractor failed:" + e.getMessage());+ init(url.hash(), null, false, ResultClass.ERROR_NO_MATCH, "snippet extractor failed:" + e.getMessage(), beginTime);return;}sentences = null;if (textline == null || !remainingHashes.isEmpty()) {- init(url.hash(), null, false, ResultClass.ERROR_NO_MATCH, "no matching snippet found");+ init(url.hash(), null, false, ResultClass.ERROR_NO_MATCH, "no matching snippet found", beginTime);return;}if (textline.length() > snippetMaxLength) textline = textline.substring(0, snippetMaxLength);// finally store this snippet in our own cachesnippetsCache.put(wordhashes, urls, textline);- init(url.hash(), textline, false, source, null);+ init(url.hash(), textline, false, source, null, beginTime);}/**@@ -364,18 +375,21 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip* @param isMarked true if query words already marked in input text* @param errorCode* @param errortext+ * @param beginTime the time in milliseconds when TextSnippet creation started*/private void init(final byte[] urlhash,final String line,final boolean isMarked,final ResultClass errorCode,- final String errortext) {+ final String errortext,+ final long beginTime) {this.urlhash = urlhash;this.line = line;this.isMarked = isMarked;this.resultStatus = errorCode;this.error = errortext;+ TextSnippet.statistics.addTextSnippetStatistics(System.currentTimeMillis() - beginTime, this.resultStatus);}/**@@ -588,5 +602,4 @@ public class TextSnippet implements Comparable<TextSnippet>, Comparator<TextSnip}for (final byte[] b : o) queryhashes.remove(b);}-}diff --git a/source/net/yacy/search/snippet/TextSnippetStatistics.java b/source/net/yacy/search/snippet/TextSnippetStatistics.javanew file mode 100644index 000000000..9af6a5514--- /dev/null+++ b/source/net/yacy/search/snippet/TextSnippetStatistics.java@@ -0,0 +1,212 @@+// TextSnippetStatistics.java+// ---------------------------+// Copyright 2018 by luccioman; https://github.com/luccioman+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package net.yacy.search.snippet;++import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicLong;+import java.util.function.LongBinaryOperator;++import net.yacy.search.SwitchboardConstants;+import net.yacy.search.snippet.TextSnippet.ResultClass;++/**+ * Handle statistics on TextSnippet processing.+ */+public class TextSnippetStatistics {++ /** Total number of TextSnippet instances created since last JVM start */+ private AtomicLong totalSnippets = new AtomicLong(0);++ /**+ * Total number of TextSnippet instances with resultStatus of type fail created+ * since last JVM start+ */+ private AtomicLong totalFailures = new AtomicLong(0);++ /**+ * Total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_DOLR created since last JVM start+ */+ private AtomicLong totalFromSolr = new AtomicLong(0);++ /**+ * Total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_CACHE created since last JVM start+ */+ private AtomicLong totalFromCache = new AtomicLong(0);++ /**+ * Total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_WEB created since last JVM start+ */+ private AtomicLong totalFromWeb = new AtomicLong(0);++ /**+ * Total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_METADATA created since last JVM start+ */+ private AtomicLong totalFromMetadata = new AtomicLong(0);++ /**+ * Total time (in milliseconds) spent in TextSnippet initialization since last+ * JVM start+ */+ private AtomicLong totalInitTime = new AtomicLong(0);++ /**+ * Maximum time (in milliseconds) spent in a single TextSnippet initialization+ * since last JVM start+ */+ private AtomicLong maxInitTime = new AtomicLong(0);++ /**+ * Statistics are effectively computed and stored only when this boolean is true+ */+ private AtomicBoolean enabled = new AtomicBoolean(SwitchboardConstants.DEBUG_SNIPPETS_STATISTICS_ENABLED_DEFAULT);++ /**+ * @return the total number of TextSnippet instances created since last JVM+ * start+ */+ public long getTotalSnippets() {+ return this.totalSnippets.get();+ }++ /**+ * @return the total number of TextSnippet instances with resultStatus of type+ * fail created since last JVM start+ */+ public long getTotalFailures() {+ return this.totalFailures.get();+ }++ /**+ * @return the total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_SOLR created since last JVM start+ */+ public long getTotalFromSolr() {+ return this.totalFromSolr.get();+ }++ /**+ * @return the total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_CACHE created since last JVM start+ */+ public long getTotalFromCache() {+ return this.totalFromCache.get();+ }++ /**+ * @return the total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_METADATA created since last JVM start+ */+ public long getTotalFromMetadata() {+ return this.totalFromMetadata.get();+ }++ /**+ * @return the total number of TextSnippet instances with resultStatus of type+ * ResultClass.SOURCE_WEB created since last JVM start+ */+ public long getTotalFromWeb() {+ return this.totalFromWeb.get();+ }++ /**+ * Update statistics after a new TextSnippet instance has been initialized. Do+ * nothing when text snippet statistics are not enabled.+ *+ * @param initTime+ * the time in milliseconds used for the snippet initialization+ * @param resultStatus+ * the snippet result status.+ */+ public void addTextSnippetStatistics(final long initTime, final ResultClass resultStatus) {+ if (this.enabled.get() && resultStatus != null) {+ this.totalSnippets.incrementAndGet();+ this.totalInitTime.addAndGet(initTime);+ this.maxInitTime.accumulateAndGet(initTime, new LongBinaryOperator() {++ @Override+ public long applyAsLong(long currentValue, long updateValue) {+ return currentValue < updateValue ? updateValue : currentValue;+ }+ });++ if (resultStatus != null) {+ switch (resultStatus) {+ case SOURCE_SOLR:+ this.totalFromSolr.incrementAndGet();+ break;+ case SOURCE_CACHE:+ this.totalFromCache.incrementAndGet();+ break;+ case SOURCE_METADATA:+ this.totalFromMetadata.incrementAndGet();+ break;+ case SOURCE_WEB:+ this.totalFromWeb.incrementAndGet();+ break;+ default:+ if (resultStatus.fail()) {+ this.totalFailures.incrementAndGet();+ }+ break;+ }+ }+ }++ }++ /**+ * @return the total time (in milliseconds) spent in TextSnippet initialization+ * since last JVM start+ */+ public long getTotalInitTime() {+ return this.totalInitTime.get();+ }++ /**+ * @return the maximum time (in milliseconds) spent in a single TextSnippet+ * initialization since last JVM start+ */+ public long getMaxInitTime() {+ return this.totalInitTime.get();+ }++ /**+ * @return true when statistics are effectively computed and stored+ */+ public boolean isEnabled() {+ return this.enabled.get();+ }++ /**+ * @param newValue+ * set to true to effectively compute and store statistics+ */+ public void setEnabled(final boolean newValue) {+ this.enabled.set(newValue);+ }++}