Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

Apply patches from NUTCH-169 (remove static NutchConf).

Andrzej Bialecki329ff64e9d72
diff --git a/src/java/org/apache/nutch/analysis/AnalyzerFactory.java b/src/java/org/apache/nutch/analysis/AnalyzerFactory.java
index 078372e8f..3bda4c72f 100644
--- a/src/java/org/apache/nutch/analysis/AnalyzerFactory.java
+++ b/src/java/org/apache/nutch/analysis/AnalyzerFactory.java
@@ -26,6 +26,7 @@ import org.apache.nutch.plugin.ExtensionPoint;
import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.plugin.PluginRuntimeException;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/**
@@ -38,26 +39,22 @@ public class AnalyzerFactory {
public final static Logger LOG =
LogFormatter.getLogger(AnalyzerFactory.class.getName());
- private final static ExtensionPoint X_POINT =
- PluginRepository.getInstance()
- .getExtensionPoint(NutchAnalyzer.X_POINT_ID);
- private final static Map CACHE = new HashMap();
-
- private final static NutchAnalyzer DEFAULT_ANALYZER =
- new NutchDocumentAnalyzer();
-
+ private NutchAnalyzer DEFAULT_ANALYZER;
- static {
- if (X_POINT == null) {
- throw new RuntimeException("x point " + NutchAnalyzer.X_POINT_ID +
- " not found.");
- }
+ private ExtensionPoint extensionPoint;
+ private NutchConf nutchConf;
+
+ public AnalyzerFactory (NutchConf nutchConf) {
+ DEFAULT_ANALYZER = new NutchDocumentAnalyzer(nutchConf);
+ this.nutchConf = nutchConf;
+ this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(NutchAnalyzer.X_POINT_ID);
+ if(this.extensionPoint == null) {
+ throw new RuntimeException("x point " + NutchAnalyzer.X_POINT_ID +
+ " not found.");
+ }
}
-
- private AnalyzerFactory() {}
-
/**
* Returns the appropriate {@link NutchAnalyzer analyzer} implementation
@@ -67,7 +64,7 @@ public class AnalyzerFactory {
* plugin found whose "lang" attribute equals the specified lang parameter is
* used. If none match, then the {@link NutchDocumentAnalyzer} is used.
*/
- public static NutchAnalyzer get(String lang) {
+ public NutchAnalyzer get(String lang) {
NutchAnalyzer analyzer = DEFAULT_ANALYZER;
Extension extension = getExtension(lang);
@@ -81,20 +78,20 @@ public class AnalyzerFactory {
return analyzer;
}
- private static Extension getExtension(String lang) {
+ private Extension getExtension(String lang) {
- Extension extension = (Extension) CACHE.get(lang);
+ Extension extension = (Extension) this.nutchConf.getObject(lang);
if (extension == null) {
extension = findExtension(lang);
- CACHE.put(lang, extension);
+ this.nutchConf.setObject(lang, extension);
}
return extension;
}
- private static Extension findExtension(String lang) {
+ private Extension findExtension(String lang) {
if (lang != null) {
- Extension[] extensions = X_POINT.getExtentens();
+ Extension[] extensions = this.extensionPoint.getExtensions();
for (int i=0; i<extensions.length; i++) {
if (lang.equals(extensions[i].getAttribute("lang"))) {
return extensions[i];
diff --git a/src/java/org/apache/nutch/analysis/CommonGrams.java b/src/java/org/apache/nutch/analysis/CommonGrams.java
index 52aeeb5c7..f59e274dd 100644
--- a/src/java/org/apache/nutch/analysis/CommonGrams.java
+++ b/src/java/org/apache/nutch/analysis/CommonGrams.java
@@ -37,11 +37,15 @@ public class CommonGrams {
private static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.analysis.CommonGrams");
private static final char SEPARATOR = '-';
- private static final HashMap COMMON_TERMS = new HashMap();
-
- static { init(); }
-
- private CommonGrams() {} // no public ctor
+ private HashMap COMMON_TERMS = new HashMap();
+
+ /**
+ * The constructor.
+ * @param nutchConf
+ */
+ public CommonGrams(NutchConf nutchConf) {
+ init(nutchConf);
+ }
private static class Filter extends TokenFilter {
private HashSet common;
@@ -130,10 +134,10 @@ public class CommonGrams {
}
/** Construct using the provided config file. */
- private static void init() {
+ private void init(NutchConf nutchConf) {
try {
- Reader reader = NutchConf.get().getConfResourceAsReader
- (NutchConf.get().get("analysis.common.terms.file"));
+ Reader reader = nutchConf.getConfResourceAsReader
+ (nutchConf.get("analysis.common.terms.file"));
BufferedReader in = new BufferedReader(reader);
String line;
while ((line = in.readLine()) != null) {
@@ -170,7 +174,7 @@ public class CommonGrams {
/** Construct a token filter that inserts n-grams for common terms. For use
* while indexing documents. */
- public static TokenFilter getFilter(TokenStream ts, String field) {
+ public TokenFilter getFilter(TokenStream ts, String field) {
return new Filter(ts, (HashSet)COMMON_TERMS.get(field));
}
@@ -179,8 +183,10 @@ public class CommonGrams {
private Term[] terms;
private int index;
- public ArrayTokens(Phrase phrase) { this.terms = phrase.getTerms(); }
-
+ public ArrayTokens(Phrase phrase) {
+ this.terms = phrase.getTerms();
+ }
+
public Token next() {
if (index == terms.length)
return null;
@@ -190,7 +196,7 @@ public class CommonGrams {
}
/** Optimizes phrase queries to use n-grams when possible. */
- public static String[] optimizePhrase(Phrase phrase, String field) {
+ public String[] optimizePhrase(Phrase phrase, String field) {
//LOG.info("Optimizing " + phrase + " for " + field);
ArrayList result = new ArrayList();
TokenStream ts = getFilter(new ArrayTokens(phrase), field);
@@ -211,17 +217,10 @@ public class CommonGrams {
if (prev != null)
result.add(prev.termText());
-// LOG.info("Optimized: ");
-// for (int i = 0; i < result.size(); i++) {
-// LOG.info(result.get(i) + " ");
-// }
-
return (String[])result.toArray(new String[result.size()]);
-
-
}
- private static int arity(String gram) {
+ private int arity(String gram) {
int index = 0;
int arity = 0;
while ((index = gram.indexOf(SEPARATOR, index+1)) != -1) {
@@ -237,14 +236,14 @@ public class CommonGrams {
text.append(args[i]);
text.append(' ');
}
- TokenStream ts =
- new NutchDocumentTokenizer(new StringReader(text.toString()));
- ts = getFilter(ts, "url");
+ TokenStream ts = new NutchDocumentTokenizer(new StringReader(text.toString()));
+ CommonGrams commonGrams = new CommonGrams(new NutchConf());
+ ts = commonGrams.getFilter(ts, "url");
Token token;
while ((token = ts.next()) != null) {
System.out.println("Token: " + token);
}
- String[] optimized = optimizePhrase(new Phrase(args), "url");
+ String[] optimized = commonGrams.optimizePhrase(new Phrase(args), "url");
System.out.print("Optimized: ");
for (int i = 0; i < optimized.length; i++) {
System.out.print(optimized[i] + " ");
diff --git a/src/java/org/apache/nutch/analysis/NutchAnalysis.java b/src/java/org/apache/nutch/analysis/NutchAnalysis.java
index e1167b404..8b8217a81 100644
--- a/src/java/org/apache/nutch/analysis/NutchAnalysis.java
+++ b/src/java/org/apache/nutch/analysis/NutchAnalysis.java
@@ -4,7 +4,8 @@ package org.apache.nutch.analysis;
import org.apache.nutch.searcher.Query;
import org.apache.nutch.searcher.QueryFilters;
import org.apache.nutch.searcher.Query.Clause;
-
+import org.apache.nutch.searcher.Query.Clause;
+import org.apache.nutch.util.NutchConf;
import org.apache.lucene.analysis.StopFilter;
import java.io.*;
@@ -24,6 +25,8 @@ public class NutchAnalysis implements NutchAnalysisConstants {
private static final Set STOP_SET = StopFilter.makeStopSet(STOP_WORDS);
private String queryString;
+ private QueryFilters queryFilters;
+
/** True iff word is a stop word. Stop words are only removed from queries.
* Every word is indexed. */
@@ -32,11 +35,12 @@ public class NutchAnalysis implements NutchAnalysisConstants {
}
/** Construct a query parser for the text in a reader. */
- public static Query parseQuery(String queryString) throws IOException {
+ public static Query parseQuery(String queryString, NutchConf nutchConf) throws IOException {
NutchAnalysis parser =
new NutchAnalysis(new FastCharStream(new StringReader(queryString)));
parser.queryString = queryString;
- return parser.parse();
+ parser.queryFilters = new QueryFilters(nutchConf);
+ return parser.parse(nutchConf);
}
/** For debugging. */
@@ -45,13 +49,13 @@ public class NutchAnalysis implements NutchAnalysisConstants {
while (true) {
System.out.print("Query: ");
String line = in.readLine();
- System.out.println(parseQuery(line));
+ System.out.println(parseQuery(line, new NutchConf()));
}
}
/** Parse a query. */
- final public Query parse() throws ParseException {
- Query query = new Query();
+ final public Query parse(NutchConf nutchConf) throws ParseException {
+ Query query = new Query(nutchConf);
ArrayList terms;
Token token;
String field;
@@ -213,7 +217,7 @@ public class NutchAnalysis implements NutchAnalysisConstants {
jj_consume_token(-1);
throw new ParseException();
}
- if (QueryFilters.isRawField(field)) {
+ if (this.queryFilters.isRawField(field)) {
result.clear();
result.add(queryString.substring(start, end));
}
@@ -259,7 +263,7 @@ public class NutchAnalysis implements NutchAnalysisConstants {
term = term();
result.add(term);
}
- if (QueryFilters.isRawField(field)) {
+ if (this.queryFilters.isRawField(field)) {
result.clear();
result.add(queryString.substring(start, token.endColumn));
}
diff --git a/src/java/org/apache/nutch/analysis/NutchAnalysis.jj b/src/java/org/apache/nutch/analysis/NutchAnalysis.jj
index 4f5a31dc9..b69af04b5 100644
--- a/src/java/org/apache/nutch/analysis/NutchAnalysis.jj
+++ b/src/java/org/apache/nutch/analysis/NutchAnalysis.jj
@@ -31,7 +31,8 @@ package org.apache.nutch.analysis;
import org.apache.nutch.searcher.Query;
import org.apache.nutch.searcher.QueryFilters;
import org.apache.nutch.searcher.Query.Clause;
-
+import org.apache.nutch.searcher.Query.Clause;
+import org.apache.nutch.util.NutchConf;
import org.apache.lucene.analysis.StopFilter;
import java.io.*;
@@ -51,6 +52,8 @@ public class NutchAnalysis {
private static final Set STOP_SET = StopFilter.makeStopSet(STOP_WORDS);
private String queryString;
+ private QueryFilters queryFilters;
+
/** True iff word is a stop word. Stop words are only removed from queries.
* Every word is indexed. */
@@ -59,11 +62,12 @@ public class NutchAnalysis {
}
/** Construct a query parser for the text in a reader. */
- public static Query parseQuery(String queryString) throws IOException {
+ public static Query parseQuery(String queryString, NutchConf nutchConf) throws IOException {
NutchAnalysis parser =
new NutchAnalysis(new FastCharStream(new StringReader(queryString)));
parser.queryString = queryString;
- return parser.parse();
+ parser.queryFilters = new QueryFilters(nutchConf);
+ return parser.parse(nutchConf);
}
/** For debugging. */
@@ -72,7 +76,7 @@ public class NutchAnalysis {
while (true) {
System.out.print("Query: ");
String line = in.readLine();
- System.out.println(parseQuery(line));
+ System.out.println(parseQuery(line, new NutchConf()));
}
}
@@ -174,9 +178,9 @@ TOKEN : { // token regular expressions
/** Parse a query. */
-Query parse() :
+Query parse(NutchConf nutchConf) :
{
- Query query = new Query();
+ Query query = new Query(nutchConf);
ArrayList terms;
Token token;
String field;
@@ -245,7 +249,7 @@ ArrayList phrase(String field) :
(<QUOTE>|<EOF>)
{
- if (QueryFilters.isRawField(field)) {
+ if (this.queryFilters.isRawField(field)) {
result.clear();
result.add(queryString.substring(start, end));
}
@@ -272,7 +276,7 @@ ArrayList compound(String field) :
term = term() { result.add(term); })*
{
- if (QueryFilters.isRawField(field)) {
+ if (this.queryFilters.isRawField(field)) {
result.clear();
result.add(queryString.substring(start, token.endColumn));
}
diff --git a/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.java b/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.java
index 41369a5fe..f5b68e58b 100644
--- a/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.java
+++ b/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.java
@@ -3,6 +3,8 @@ package org.apache.nutch.analysis;
import org.apache.nutch.searcher.Query;
import org.apache.nutch.searcher.QueryFilters;
import org.apache.nutch.searcher.Query.Clause;
+import org.apache.nutch.searcher.Query.Clause;
+import org.apache.nutch.util.NutchConf;
import org.apache.lucene.analysis.StopFilter;
import java.io.*;
import java.util.*;
diff --git a/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java b/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java
index 812b79aa7..d8babcae8 100644
--- a/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java
+++ b/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java
@@ -24,40 +24,60 @@ import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Token;
-
+import org.apache.nutch.mapred.JobConf;
+import org.apache.nutch.util.NutchConf;
/**
- * The analyzer used for Nutch documents.
- * Uses the JavaCC-defined lexical analyzer {@link NutchDocumentTokenizer},
- * with no stop list. This keeps it consistent with query parsing.
+ * The analyzer used for Nutch documents. Uses the JavaCC-defined lexical
+ * analyzer {@link NutchDocumentTokenizer}, with no stop list. This keeps it
+ * consistent with query parsing.
*/
public class NutchDocumentAnalyzer extends NutchAnalyzer {
/** Analyzer used to index textual content. */
- private static class ContentAnalyzer extends Analyzer {
- /** Constructs a {@link NutchDocumentTokenizer}. */
- public TokenStream tokenStream(String field, Reader reader) {
- return CommonGrams.getFilter(new NutchDocumentTokenizer(reader), field);
- }
+ private static Analyzer CONTENT_ANALYZER;
+ // Anchor Analysis
+ // Like content analysis, but leave gap between anchors to inhibit
+ // cross-anchor phrase matching.
+ /**
+ * The number of unused term positions between anchors in the anchor field.
+ */
+ public static final int INTER_ANCHOR_GAP = 4;
+ /** Analyzer used to analyze anchors. */
+ private static Analyzer ANCHOR_ANALYZER;
+ private NutchConf nutchConf;
+
+ /**
+ * @param conf
+ */
+ public NutchDocumentAnalyzer(NutchConf conf) {
+ this.nutchConf = conf;
+ CONTENT_ANALYZER = new ContentAnalyzer(conf);
+ ANCHOR_ANALYZER = new AnchorAnalyzer();
}
/** Analyzer used to index textual content. */
- public static final Analyzer CONTENT_ANALYZER = new ContentAnalyzer();
+ private static class ContentAnalyzer extends Analyzer {
+ private CommonGrams commonGrams;
- // Anchor Analysis
- // Like content analysis, but leave gap between anchors to inhibit
- // cross-anchor phrase matching.
+ public ContentAnalyzer(NutchConf nutchConf) {
+ this.commonGrams = new CommonGrams(nutchConf);
+ }
- /** The number of unused term positions between anchors in the anchor
- * field. */
- public static final int INTER_ANCHOR_GAP = 4;
+ /** Constructs a {@link NutchDocumentTokenizer}. */
+ public TokenStream tokenStream(String field, Reader reader) {
+ return this.commonGrams.getFilter(new NutchDocumentTokenizer(reader),
+ field);
+ }
+ }
private static class AnchorFilter extends TokenFilter {
+ private boolean first = true;
+
public AnchorFilter(TokenStream input) {
super(input);
}
- private boolean first = true;
public final Token next() throws IOException {
Token result = input.next();
if (result == null)
@@ -76,9 +96,6 @@ public class NutchDocumentAnalyzer extends NutchAnalyzer {
}
}
- /** Analyzer used to analyze anchors. */
- public static final Analyzer ANCHOR_ANALYZER = new AnchorAnalyzer();
-
/** Returns a new token stream for text from the named field. */
public TokenStream tokenStream(String fieldName, Reader reader) {
Analyzer analyzer;
@@ -89,5 +106,4 @@ public class NutchDocumentAnalyzer extends NutchAnalyzer {
return analyzer.tokenStream(fieldName, reader);
}
-
}
diff --git a/src/java/org/apache/nutch/clustering/OnlineClustererFactory.java b/src/java/org/apache/nutch/clustering/OnlineClustererFactory.java
index 357e6c6fd..10ba23cfd 100644
--- a/src/java/org/apache/nutch/clustering/OnlineClustererFactory.java
+++ b/src/java/org/apache/nutch/clustering/OnlineClustererFactory.java
@@ -30,11 +30,13 @@ import org.apache.nutch.util.LogFormatter;
public class OnlineClustererFactory {
public static final Logger LOG = LogFormatter
.getLogger(OnlineClustererFactory.class.getName());
+ private ExtensionPoint extensionPoint;
+ private String extensionName;
- private final static ExtensionPoint X_POINT = PluginRepository.getInstance()
- .getExtensionPoint(OnlineClusterer.X_POINT_ID);
-
- private OnlineClustererFactory() {}
+ public OnlineClustererFactory(NutchConf nutchConf) {
+ this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(OnlineClusterer.X_POINT_ID);
+ this.extensionName = nutchConf.get("extension.clustering.extension-name");
+ }
/**
* @return Returns the online clustering extension specified
@@ -43,15 +45,14 @@ public class OnlineClustererFactory {
* empty (no preference), the first available clustering extension is
* returned.
*/
- public static OnlineClusterer getOnlineClusterer()
+ public OnlineClusterer getOnlineClusterer()
throws PluginRuntimeException {
- if (X_POINT == null) {
+ if (this.extensionPoint == null) {
// not even an extension point defined.
return null;
}
-
- String extensionName = NutchConf.get().get("extension.clustering.extension-name");
+
if (extensionName != null) {
Extension extension = findExtension(extensionName);
if (extension != null) {
@@ -63,7 +64,7 @@ public class OnlineClustererFactory {
// not found, fallback to the default, if available.
}
- Extension[] extensions = X_POINT.getExtensions();
+ Extension[] extensions = this.extensionPoint.getExtensions();
if (extensions.length > 0) {
LOG.info("Using the first clustering extension found: "
+ extensions[0].getId());
@@ -73,10 +74,10 @@ public class OnlineClustererFactory {
}
}
- private static Extension findExtension(String name)
+ private Extension findExtension(String name)
throws PluginRuntimeException {
- Extension[] extensions = X_POINT.getExtensions();
+ Extension[] extensions = this.extensionPoint.getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
diff --git a/src/java/org/apache/nutch/crawl/Crawl.java b/src/java/org/apache/nutch/crawl/Crawl.java
index 26bd582fd..d74f16a63 100644
--- a/src/java/org/apache/nutch/crawl/Crawl.java
+++ b/src/java/org/apache/nutch/crawl/Crawl.java
@@ -41,9 +41,6 @@ public class Crawl {
(new Date(System.currentTimeMillis()));
}
- static {
- NutchConf.get().addConfResource("crawl-tool.xml");
- }
/* Perform complete crawling and indexing given a set of root urls. */
public static void main(String args[]) throws Exception {
@@ -53,8 +50,9 @@ public class Crawl {
return;
}
- JobConf conf = new JobConf(NutchConf.get());
- //conf.addConfResource("crawl-tool.xml");
+ NutchConf nutchConf = new NutchConf();
+ nutchConf.addConfResource("crawl-tool.xml");
+ JobConf conf = new JobConf(nutchConf);
File rootUrlDir = null;
File dir = new File("crawl-" + getDate());
@@ -120,7 +118,7 @@ public class Crawl {
// index, dedup & merge
new Indexer(conf).index(indexes, crawlDb, linkDb, fs.listFiles(segments));
new DeleteDuplicates(conf).dedup(new File[] { indexes });
- new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir).merge();
+ new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir, nutchConf).merge();
LOG.info("crawl finished: " + dir);
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDb.java b/src/java/org/apache/nutch/crawl/CrawlDb.java
index d60663832..b599c8976 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDb.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDb.java
@@ -89,7 +89,7 @@ public class CrawlDb extends NutchConfigured {
}
public static void main(String[] args) throws Exception {
- CrawlDb crawlDb = new CrawlDb(NutchConf.get());
+ CrawlDb crawlDb = new CrawlDb(new NutchConf());
if (args.length < 2) {
System.err.println("Usage: <crawldb> <segment>");
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
index 58a13a62b..bcb0d3bd0 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReader.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
@@ -157,8 +157,8 @@ public class CrawlDbReader {
JobClient.runJob(job);
// reading the result
- NutchFileSystem fileSystem = NutchFileSystem.get();
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(fileSystem, tmpFolder);
+ NutchFileSystem fileSystem = NutchFileSystem.get(config);
+ SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(config, tmpFolder);
UTF8 key = new UTF8();
LongWritable value = new LongWritable();
@@ -210,7 +210,7 @@ public class CrawlDbReader {
NutchFileSystem fs = NutchFileSystem.get(config);
UTF8 key = new UTF8(url);
CrawlDatum val = new CrawlDatum();
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new File(crawlDb, CrawlDatum.DB_DIR_NAME));
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new File(crawlDb, CrawlDatum.DB_DIR_NAME), config);
Writable res = MapFileOutputFormat.getEntry(readers, new HashPartitioner(), key, val);
System.out.println("URL: " + url);
if (res != null) {
@@ -254,7 +254,7 @@ public class CrawlDbReader {
}
String param = null;
String crawlDb = args[0];
- NutchConf conf = NutchConf.get();
+ NutchConf conf = new NutchConf();
for (int i = 1; i < args.length; i++) {
if (args[i].equals("-stats")) {
dbr.processStatJob(crawlDb, conf);
diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.java
index d06f0b857..97d0a6bd7 100644
--- a/src/java/org/apache/nutch/crawl/Generator.java
+++ b/src/java/org/apache/nutch/crawl/Generator.java
@@ -259,7 +259,7 @@ public class Generator extends NutchConfigured {
if (topN != Long.MAX_VALUE)
LOG.info("topN: " + topN);
- Generator gen = new Generator(NutchConf.get());
+ Generator gen = new Generator(new NutchConf());
gen.generate(dbDir, segmentsDir, numFetchers, topN, curTime);
}
}
diff --git a/src/java/org/apache/nutch/crawl/Injector.java b/src/java/org/apache/nutch/crawl/Injector.java
index cfaff74f3..0705da331 100644
--- a/src/java/org/apache/nutch/crawl/Injector.java
+++ b/src/java/org/apache/nutch/crawl/Injector.java
@@ -35,11 +35,14 @@ public class Injector extends NutchConfigured {
/** Normalize and filter injected urls. */
public static class InjectMapper implements Mapper {
- private UrlNormalizer urlNormalizer = UrlNormalizerFactory.getNormalizer();
+ private UrlNormalizer urlNormalizer;
private float interval;
+ private JobConf jobConf;
public void configure(JobConf job) {
+ urlNormalizer = new UrlNormalizerFactory(job).getNormalizer();
interval = job.getFloat("db.default.fetch.interval", 30f);
+ this.jobConf = job;
}
public void map(WritableComparable key, Writable val,
@@ -47,9 +50,11 @@ public class Injector extends NutchConfigured {
throws IOException {
UTF8 value = (UTF8)val;
String url = value.toString(); // value is line of text
+ // System.out.println("url: " +url);
try {
url = urlNormalizer.normalize(url); // normalize the url
- url = URLFilters.filter(url); // filter the url
+ URLFilters filters = new URLFilters(this.jobConf);
+ url = filters.filter(url); // filter the url
} catch (Exception e) {
LOG.warning("Skipping " +url+":"+e);
url = null;
@@ -116,7 +121,7 @@ public class Injector extends NutchConfigured {
}
public static void main(String[] args) throws Exception {
- Injector injector = new Injector(NutchConf.get());
+ Injector injector = new Injector(new NutchConf());
if (args.length < 2) {
System.err.println("Usage: Injector <crawldb> <url_dir>");
diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.java
index 30ac152de..9db0d9f62 100644
--- a/src/java/org/apache/nutch/crawl/LinkDb.java
+++ b/src/java/org/apache/nutch/crawl/LinkDb.java
@@ -182,7 +182,7 @@ public class LinkDb extends NutchConfigured implements Mapper, Reducer {
}
public static void main(String[] args) throws Exception {
- LinkDb linkDb = new LinkDb(NutchConf.get());
+ LinkDb linkDb = new LinkDb(new NutchConf());
if (args.length < 2) {
System.err.println("Usage: <linkdb> <segments>");
diff --git a/src/java/org/apache/nutch/crawl/LinkDbReader.java b/src/java/org/apache/nutch/crawl/LinkDbReader.java
index 2d4cef1d7..18eec862b 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbReader.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbReader.java
@@ -37,10 +37,12 @@ public class LinkDbReader {
private NutchFileSystem fs;
private File directory;
private MapFile.Reader[] readers;
+ private NutchConf nutchConf;
- public LinkDbReader(NutchFileSystem fs, File directory) {
+ public LinkDbReader(NutchFileSystem fs, File directory, NutchConf nutchConf) {
this.fs = fs;
this.directory = directory;
+ this.nutchConf = nutchConf;
}
public String[] getAnchors(UTF8 url) throws IOException {
@@ -55,7 +57,7 @@ public class LinkDbReader {
synchronized (this) {
if (readers == null) {
readers = MapFileOutputFormat.getReaders
- (fs, new File(directory, LinkDb.CURRENT_NAME));
+ (fs, new File(directory, LinkDb.CURRENT_NAME), this.nutchConf);
}
}
@@ -90,11 +92,11 @@ public class LinkDbReader {
System.err.println("\t-url <url>\tprint information about <url> to System.out");
return;
}
-
+ NutchConf nutchConf = new NutchConf();
if (args[1].equals("-dump")) {
- LinkDbReader.processDumpJob(args[0], args[2], NutchConf.get());
+ LinkDbReader.processDumpJob(args[0], args[2], nutchConf);
} else if (args[1].equals("-url")) {
- LinkDbReader dbr = new LinkDbReader(NutchFileSystem.get(), new File(args[0]));
+ LinkDbReader dbr = new LinkDbReader(NutchFileSystem.get(new NutchConf()), new File(args[0]), nutchConf);
Inlinks links = dbr.getInlinks(new UTF8(args[2]));
if (links == null) {
System.out.println(" - no link information.");
diff --git a/src/java/org/apache/nutch/crawl/TextProfileSignature.java b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
index 7f8bbd820..b46f74a76 100644
--- a/src/java/org/apache/nutch/crawl/TextProfileSignature.java
+++ b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
@@ -157,7 +157,7 @@ public class TextProfileSignature extends Signature {
public static void main(String[] args) throws Exception {
TextProfileSignature sig = new TextProfileSignature();
- sig.setConf(NutchConf.get());
+ sig.setConf(new NutchConf());
HashMap res = new HashMap();
File[] files = new File(args[0]).listFiles();
for (int i = 0; i < files.length; i++) {
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index f1d6fcf6d..465c9d39d 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -73,9 +73,18 @@ public class Fetcher extends NutchConfigured implements MapRunnable {
private boolean parsing;
private class FetcherThread extends Thread {
- public FetcherThread() {
+ private NutchConf nutchConf;
+ private URLFilters urlFilters;
+ private ParseUtil parseUtil;
+ private ProtocolFactory protocolFactory;
+
+ public FetcherThread(NutchConf nutchConf) {
this.setDaemon(true); // don't hang JVM on exit
this.setName("FetcherThread"); // use an informative name
+ this.nutchConf = nutchConf;
+ this.urlFilters = new URLFilters(nutchConf);
+ this.parseUtil = new ParseUtil(nutchConf);
+ this.protocolFactory = new ProtocolFactory(nutchConf);
}
public void run() {
@@ -112,7 +121,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {
do {
redirecting = false;
LOG.fine("redirectCount=" + redirectCount);
- Protocol protocol = ProtocolFactory.getProtocol(url);
+ Protocol protocol = this.protocolFactory.getProtocol(url);
ProtocolOutput output = protocol.getProtocolOutput(key, datum);
ProtocolStatus status = output.getStatus();
Content content = output.getContent();
@@ -127,7 +136,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {
case ProtocolStatus.MOVED: // redirect
case ProtocolStatus.TEMP_MOVED:
String newUrl = status.getMessage();
- newUrl = URLFilters.filter(newUrl);
+ newUrl = this.urlFilters.filter(newUrl);
if (newUrl != null && !newUrl.equals(url)) {
url = newUrl;
redirecting = true;
@@ -196,7 +205,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {
if (content == null) {
String url = key.toString();
- content = new Content(url, url, new byte[0], "", new ContentProperties());
+ content = new Content(url, url, new byte[0], "", new ContentProperties(), this.nutchConf);
}
content.getMetadata().setProperty // add segment to metadata
@@ -208,14 +217,14 @@ public class Fetcher extends NutchConfigured implements MapRunnable {
if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {
ParseStatus parseStatus;
try {
- parse = ParseUtil.parse(content);
+ parse = this.parseUtil.parse(content);
parseStatus = parse.getData().getStatus();
} catch (Exception e) {
parseStatus = new ParseStatus(e);
}
if (!parseStatus.isSuccess()) {
LOG.warning("Error parsing: " + key + ": " + parseStatus);
- parse = parseStatus.getEmptyParse();
+ parse = parseStatus.getEmptyParse(getConf());
}
// Calculate page signature. For non-parsing fetchers this will
// be done in ParseSegment
@@ -295,7 +304,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {
LOG.info("Fetcher: threads: " + threadCount);
for (int i = 0; i < threadCount; i++) { // spawn threads
- new FetcherThread().start();
+ new FetcherThread(getConf()).start();
}
// select a timeout that avoids a task timeout
@@ -361,7 +370,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {
File segment = new File(args[0]);
- NutchConf conf = NutchConf.get();
+ NutchConf conf = new NutchConf();
int threads = conf.getInt("fetcher.threads.fetch", 10);
boolean parsing = true;
diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutput.java b/src/java/org/apache/nutch/fetcher/FetcherOutput.java
index 82a54abd1..efdc54f58 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherOutput.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherOutput.java
@@ -22,12 +22,15 @@ import org.apache.nutch.io.*;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.parse.*;
+import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
/* An entry in the fetcher's output. */
-public final class FetcherOutput implements Writable {
+public final class FetcherOutput implements Writable, NutchConfigurable {
private CrawlDatum crawlDatum;
private Content content;
private ParseImpl parse;
+ private NutchConf nutchConf;
public FetcherOutput() {}
@@ -41,7 +44,7 @@ public final class FetcherOutput implements Writable {
public final void readFields(DataInput in) throws IOException {
this.crawlDatum = CrawlDatum.read(in);
this.content = in.readBoolean() ? Content.read(in) : null;
- this.parse = in.readBoolean() ? ParseImpl.read(in) : null;
+ this.parse = in.readBoolean() ? ParseImpl.read(in, this.nutchConf) : null;
}
public final void write(DataOutput out) throws IOException {
@@ -77,4 +80,12 @@ public final class FetcherOutput implements Writable {
return buffer.toString();
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/java/org/apache/nutch/fs/FileUtil.java b/src/java/org/apache/nutch/fs/FileUtil.java
index baf279657..292c27df1 100644
--- a/src/java/org/apache/nutch/fs/FileUtil.java
+++ b/src/java/org/apache/nutch/fs/FileUtil.java
@@ -28,8 +28,8 @@ public class FileUtil {
* Delete a directory and all its contents. If
* we return false, the directory may be partially-deleted.
*/
- public static boolean fullyDelete(File dir) throws IOException {
- return fullyDelete(new LocalFileSystem(), dir);
+ public static boolean fullyDelete(File dir, NutchConf nutchConf) throws IOException {
+ return fullyDelete(new LocalFileSystem(nutchConf), dir);
}
public static boolean fullyDelete(NutchFileSystem nfs, File dir) throws IOException {
// 20041022, xing.
@@ -43,7 +43,7 @@ public class FileUtil {
* Copy a file's contents to a new location.
* Returns whether a target file was overwritten
*/
- public static boolean copyContents(NutchFileSystem nfs, File src, File dst, boolean overwrite) throws IOException {
+ public static boolean copyContents(NutchFileSystem nfs, File src, File dst, boolean overwrite, NutchConf nutchConf) throws IOException {
if (nfs.exists(dst) && !overwrite) {
return false;
}
@@ -57,7 +57,7 @@ public class FileUtil {
NFSInputStream in = nfs.openRaw(src);
try {
NFSOutputStream out = nfs.createRaw(dst, true);
- byte buf[] = new byte[NutchConf.get().getInt("io.file.buffer.size", 4096)];
+ byte buf[] = new byte[nutchConf.getInt("io.file.buffer.size", 4096)];
try {
int readBytes = in.read(buf);
@@ -77,7 +77,7 @@ public class FileUtil {
if (contents != null) {
for (int i = 0; i < contents.length; i++) {
File newDst = new File(dst, contents[i].getName());
- if (! copyContents(nfs, contents[i], newDst, overwrite)) {
+ if (! copyContents(nfs, contents[i], newDst, overwrite, nutchConf)) {
return false;
}
}
@@ -90,7 +90,7 @@ public class FileUtil {
* Copy a file and/or directory and all its contents (whether
* data or other files/dirs)
*/
- public static void recursiveCopy(NutchFileSystem nfs, File src, File dst) throws IOException {
+ public static void recursiveCopy(NutchFileSystem nfs, File src, File dst, NutchConf nutchConf) throws IOException {
//
// Resolve the real target.
//
@@ -107,7 +107,7 @@ public class FileUtil {
//
// If the source is a file, then just copy the contents
//
- copyContents(nfs, src, dst, true);
+ copyContents(nfs, src, dst, true, nutchConf);
} else {
//
// If the source is a dir, then we need to copy all the subfiles.
@@ -115,7 +115,7 @@ public class FileUtil {
nfs.mkdirs(dst);
File contents[] = nfs.listFiles(src);
for (int i = 0; i < contents.length; i++) {
- recursiveCopy(nfs, contents[i], new File(dst, contents[i].getName()));
+ recursiveCopy(nfs, contents[i], new File(dst, contents[i].getName()), nutchConf);
}
}
}
diff --git a/src/java/org/apache/nutch/fs/LocalFileSystem.java b/src/java/org/apache/nutch/fs/LocalFileSystem.java
index 0c562c120..9d51fc190 100644
--- a/src/java/org/apache/nutch/fs/LocalFileSystem.java
+++ b/src/java/org/apache/nutch/fs/LocalFileSystem.java
@@ -23,6 +23,7 @@ import java.nio.channels.*;
import org.apache.nutch.ndfs.NDFSFile;
import org.apache.nutch.ndfs.DF;
import org.apache.nutch.ndfs.NDFSFileInfo;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.UTF8;
/****************************************************************
@@ -38,11 +39,11 @@ public class LocalFileSystem extends NutchFileSystem {
TreeMap lockObjSet = new TreeMap();
// by default use copy/delete instead of rename
boolean useCopyForRename = true;
-
+
/**
*/
- public LocalFileSystem() throws IOException {
- super();
+ public LocalFileSystem(NutchConf nutchConf) throws IOException {
+ super(nutchConf);
// if you find an OS which reliably supports non-POSIX
// rename(2) across filesystems / volumes, you can
// uncomment this.
@@ -175,7 +176,7 @@ public class LocalFileSystem extends NutchFileSystem {
*/
public boolean renameRaw(File src, File dst) throws IOException {
if (useCopyForRename) {
- FileUtil.copyContents(this, src, dst, true);
+ FileUtil.copyContents(this, src, dst, true, nutchConf);
return fullyDelete(src);
} else return src.renameTo(dst);
}
@@ -288,7 +289,7 @@ public class LocalFileSystem extends NutchFileSystem {
public void moveFromLocalFile(File src, File dst) throws IOException {
if (! src.equals(dst)) {
if (useCopyForRename) {
- FileUtil.copyContents(this, src, dst, true);
+ FileUtil.copyContents(this, src, dst, true, this.nutchConf);
fullyDelete(src);
} else src.renameTo(dst);
}
@@ -299,7 +300,7 @@ public class LocalFileSystem extends NutchFileSystem {
*/
public void copyFromLocalFile(File src, File dst) throws IOException {
if (! src.equals(dst)) {
- FileUtil.copyContents(this, src, dst, true);
+ FileUtil.copyContents(this, src, dst, true, this.nutchConf);
}
}
@@ -308,7 +309,7 @@ public class LocalFileSystem extends NutchFileSystem {
*/
public void copyToLocalFile(File src, File dst) throws IOException {
if (! src.equals(dst)) {
- FileUtil.copyContents(this, src, dst, true);
+ FileUtil.copyContents(this, src, dst, true, this.nutchConf);
}
}
diff --git a/src/java/org/apache/nutch/fs/NDFSFileSystem.java b/src/java/org/apache/nutch/fs/NDFSFileSystem.java
index 8326f772f..ff9afdeab 100644
--- a/src/java/org/apache/nutch/fs/NDFSFileSystem.java
+++ b/src/java/org/apache/nutch/fs/NDFSFileSystem.java
@@ -43,8 +43,9 @@ public class NDFSFileSystem extends NutchFileSystem {
* Create the ShareSet automatically, and then go on to
* the regular constructor.
*/
- public NDFSFileSystem(InetSocketAddress namenode) throws IOException {
- this.ndfs = new NDFSClient(namenode);
+ public NDFSFileSystem(InetSocketAddress namenode, NutchConf nutchConf) throws IOException {
+ super(nutchConf);
+ this.ndfs = new NDFSClient(namenode, nutchConf);
this.name = namenode.getHostName() + ":" + namenode.getPort();
}
@@ -172,7 +173,7 @@ public class NDFSFileSystem extends NutchFileSystem {
doFromLocalFile(contents[i], new File(dst, contents[i].getName()), deleteSource);
}
} else {
- byte buf[] = new byte[NutchConf.get().getInt("io.file.buffer.size", 4096)];
+ byte buf[] = new byte[this.nutchConf.getInt("io.file.buffer.size", 4096)];
InputStream in = new BufferedInputStream(new FileInputStream(src));
try {
OutputStream out = create(dst);
@@ -217,10 +218,10 @@ public class NDFSFileSystem extends NutchFileSystem {
copyToLocalFile(contents[i], new File(dst, contents[i].getName()));
}
} else {
- byte buf[] = new byte[NutchConf.get().getInt("io.file.buffer.size", 4096)];
+ byte buf[] = new byte[this.nutchConf.getInt("io.file.buffer.size", 4096)];
InputStream in = open(src);
try {
- OutputStream out = NutchFileSystem.getNamed("local").create(dst);
+ OutputStream out = NutchFileSystem.getNamed("local", this.nutchConf).create(dst);
try {
int bytesRead = in.read(buf);
while (bytesRead >= 0) {
@@ -267,7 +268,7 @@ public class NDFSFileSystem extends NutchFileSystem {
*/
public void completeLocalInput(File localFile) throws IOException {
// Get rid of the local copy - we don't need it anymore.
- FileUtil.fullyDelete(localFile);
+ FileUtil.fullyDelete(localFile, this.nutchConf);
}
/**
diff --git a/src/java/org/apache/nutch/fs/NDFSShell.java b/src/java/org/apache/nutch/fs/NDFSShell.java
index 5133a6302..5e4240b32 100644
--- a/src/java/org/apache/nutch/fs/NDFSShell.java
+++ b/src/java/org/apache/nutch/fs/NDFSShell.java
@@ -122,8 +122,8 @@ public class NDFSShell {
/**
* Copy an NDFS file
*/
- public void copy(String srcf, String dstf) throws IOException {
- if (FileUtil.copyContents(nfs, new File(srcf), new File(dstf), true)) {
+ public void copy(String srcf, String dstf, NutchConf nutchConf) throws IOException {
+ if (FileUtil.copyContents(nfs, new File(srcf), new File(dstf), true, nutchConf)) {
System.out.println("Copied " + srcf + " to " + dstf);
} else {
System.out.println("Copy failed");
@@ -224,8 +224,9 @@ public class NDFSShell {
return;
}
+ NutchConf nutchConf = new NutchConf();
int i = 0;
- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);
+ NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i, nutchConf);
try {
NDFSShell tc = new NDFSShell(nfs);
@@ -244,7 +245,7 @@ public class NDFSShell {
} else if ("-mv".equals(cmd)) {
tc.rename(argv[i++], argv[i++]);
} else if ("-cp".equals(cmd)) {
- tc.copy(argv[i++], argv[i++]);
+ tc.copy(argv[i++], argv[i++], nutchConf);
} else if ("-rm".equals(cmd)) {
tc.delete(argv[i++]);
} else if ("-du".equals(cmd)) {
diff --git a/src/java/org/apache/nutch/fs/NFSDataInputStream.java b/src/java/org/apache/nutch/fs/NFSDataInputStream.java
index 81d6f6ad1..da65625a3 100644
--- a/src/java/org/apache/nutch/fs/NFSDataInputStream.java
+++ b/src/java/org/apache/nutch/fs/NFSDataInputStream.java
@@ -40,7 +40,7 @@ public class NFSDataInputStream extends DataInputStream {
private Checksum sum = new CRC32();
private int inSum;
- public Checker(NutchFileSystem fs, File file)
+ public Checker(NutchFileSystem fs, File file, NutchConf nutchConf)
throws IOException {
super(fs.openRaw(file));
@@ -48,7 +48,7 @@ public class NFSDataInputStream extends DataInputStream {
this.file = file;
File sumFile = fs.getChecksumFile(file);
try {
- this.sums = new NFSDataInputStream(fs.openRaw(sumFile));
+ this.sums = new NFSDataInputStream(fs.openRaw(sumFile), nutchConf);
byte[] version = new byte[VERSION.length];
sums.readFully(version);
if (!Arrays.equals(version, VERSION))
@@ -210,20 +210,25 @@ public class NFSDataInputStream extends DataInputStream {
}
}
-
- public NFSDataInputStream(NutchFileSystem fs, File file) throws IOException {
- this(fs, file, NutchConf.get().getInt("io.file.buffer.size", 4096));
+
+
+ public NFSDataInputStream(NutchFileSystem fs, File file, int bufferSize, NutchConf nutchConf)
+ throws IOException {
+ super(null);
+ this.in = new Buffer(new PositionCache(new Checker(fs, file, nutchConf)), bufferSize);
}
-
- public NFSDataInputStream(NutchFileSystem fs, File file, int bufferSize)
+
+
+ public NFSDataInputStream(NutchFileSystem fs, File file, NutchConf nutchConf)
throws IOException {
super(null);
- this.in = new Buffer(new PositionCache(new Checker(fs, file)), bufferSize);
+ int bufferSize = nutchConf.getInt("io.file.buffer.size", 4096);
+ this.in = new Buffer(new PositionCache(new Checker(fs, file, nutchConf)), bufferSize);
}
/** Construct without checksums. */
- public NFSDataInputStream(NFSInputStream in) throws IOException {
- this(in, NutchConf.get().getInt("io.file.buffer.size", 4096));
+ public NFSDataInputStream(NFSInputStream in, NutchConf nutchConf) throws IOException {
+ this(in, nutchConf.getInt("io.file.buffer.size", 4096));
}
/** Construct without checksums. */
public NFSDataInputStream(NFSInputStream in, int bufferSize)
diff --git a/src/java/org/apache/nutch/fs/NFSDataOutputStream.java b/src/java/org/apache/nutch/fs/NFSDataOutputStream.java
index 66b368739..7e57eca4c 100644
--- a/src/java/org/apache/nutch/fs/NFSDataOutputStream.java
+++ b/src/java/org/apache/nutch/fs/NFSDataOutputStream.java
@@ -29,29 +29,27 @@ public class NFSDataOutputStream extends DataOutputStream {
/** Store checksums for data. */
private static class Summer extends FilterOutputStream {
- private final int bytesPerSum
- = NutchConf.get().getInt("io.bytes.per.checksum", 512);
-
private NFSDataOutputStream sums;
private Checksum sum = new CRC32();
private int inSum;
+ private int bytesPerSum;
- public Summer(NutchFileSystem fs, File file, boolean overwrite)
+ public Summer(NutchFileSystem fs, File file, boolean overwrite, NutchConf nutchConf)
throws IOException {
super(fs.createRaw(file, overwrite));
-
+ this.bytesPerSum = nutchConf.getInt("io.bytes.per.checksum", 512);
this.sums =
- new NFSDataOutputStream(fs.createRaw(fs.getChecksumFile(file), true));
+ new NFSDataOutputStream(fs.createRaw(fs.getChecksumFile(file), true), nutchConf);
sums.write(CHECKSUM_VERSION, 0, CHECKSUM_VERSION.length);
- sums.writeInt(bytesPerSum);
+ sums.writeInt(this.bytesPerSum);
}
public void write(byte b[], int off, int len) throws IOException {
int summed = 0;
while (summed < len) {
- int goal = bytesPerSum - inSum;
+ int goal = this.bytesPerSum - inSum;
int inBuf = len - summed;
int toSum = inBuf <= goal ? inBuf : goal;
@@ -59,7 +57,7 @@ public class NFSDataOutputStream extends DataOutputStream {
summed += toSum;
inSum += toSum;
- if (inSum == bytesPerSum) {
+ if (inSum == this.bytesPerSum) {
writeSum();
}
}
@@ -124,15 +122,15 @@ public class NFSDataOutputStream extends DataOutputStream {
}
public NFSDataOutputStream(NutchFileSystem fs, File file,
- boolean overwrite, int bufferSize)
+ boolean overwrite, NutchConf nutchConf)
throws IOException {
- super(new Buffer(new PositionCache(new Summer(fs, file, overwrite)),
- bufferSize));
+ super(new Buffer(new PositionCache(new Summer(fs, file, overwrite, nutchConf)),
+ nutchConf.getInt("io.file.buffer.size", 4096)));
}
/** Construct without checksums. */
- public NFSDataOutputStream(NFSOutputStream out) throws IOException {
- this(out, NutchConf.get().getInt("io.file.buffer.size", 4096));
+ public NFSDataOutputStream(NFSOutputStream out, NutchConf nutchConf) throws IOException {
+ this(out, nutchConf.getInt("io.file.buffer.size", 4096));
}
/** Construct without checksums. */
diff --git a/src/java/org/apache/nutch/fs/NutchFileSystem.java b/src/java/org/apache/nutch/fs/NutchFileSystem.java
index 3f52b0464..5328fc30d 100644
--- a/src/java/org/apache/nutch/fs/NutchFileSystem.java
+++ b/src/java/org/apache/nutch/fs/NutchFileSystem.java
@@ -45,7 +45,6 @@ public abstract class NutchFileSystem {
public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.util.NutchFileSystem");
private static final HashMap NAME_TO_FS = new HashMap();
-
/**
* Parse the cmd-line args, starting at i. Remove consumed args
* from array. We expect param in the form:
@@ -53,7 +52,7 @@ public abstract class NutchFileSystem {
*
* @deprecated use fs.default.name config option instead
*/
- public static NutchFileSystem parseArgs(String argv[], int i) throws IOException {
+ public static NutchFileSystem parseArgs(String argv[], int i, NutchConf nutchConf) throws IOException {
/**
if (argv.length - i < 1) {
throw new IOException("Must indicate filesystem type for NDFS");
@@ -65,12 +64,12 @@ public abstract class NutchFileSystem {
if ("-ndfs".equals(cmd)) {
i++;
InetSocketAddress addr = DataNode.createSocketAddr(argv[i++]);
- nfs = new NDFSFileSystem(addr);
+ nfs = new NDFSFileSystem(addr, nutchConf);
} else if ("-local".equals(cmd)) {
i++;
- nfs = new LocalFileSystem();
+ nfs = new LocalFileSystem(nutchConf);
} else {
- nfs = get(); // using default
+ nfs = get(nutchConf); // using default
LOG.info("No FS indicated, using default:"+nfs.getName());
}
@@ -81,30 +80,26 @@ public abstract class NutchFileSystem {
return nfs;
}
-
- /** Returns the default filesystem implementation.*/
- public static NutchFileSystem get() throws IOException {
- return get(NutchConf.get());
- }
-
/** Returns the configured filesystem implementation.*/
public static NutchFileSystem get(NutchConf conf) throws IOException {
- return getNamed(conf.get("fs.default.name", "local"));
+ return getNamed(conf.get("fs.default.name", "local"), conf);
}
+ protected NutchConf nutchConf;
/** Returns a name for this filesystem, suitable to pass to {@link
* NutchFileSystem#getNamed(String).*/
public abstract String getName();
/** Returns a named filesystem. Names are either the string "local" or a
* host:port pair, naming an NDFS name server.*/
- public static NutchFileSystem getNamed(String name) throws IOException {
+ public static NutchFileSystem getNamed(String name, NutchConf nutchConf) throws IOException {
NutchFileSystem fs = (NutchFileSystem)NAME_TO_FS.get(name);
+ int ioFileBufferSize = nutchConf.getInt("io.file.buffer.size", 4096);
if (fs == null) {
if ("local".equals(name)) {
- fs = new LocalFileSystem();
+ fs = new LocalFileSystem(nutchConf);
} else {
- fs = new NDFSFileSystem(DataNode.createSocketAddr(name));
+ fs = new NDFSFileSystem(DataNode.createSocketAddr(name), nutchConf);
}
NAME_TO_FS.put(name, fs);
}
@@ -127,7 +122,8 @@ public abstract class NutchFileSystem {
///////////////////////////////////////////////////////////////
/**
*/
- public NutchFileSystem() {
+ public NutchFileSystem(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
}
/**
@@ -143,12 +139,16 @@ public abstract class NutchFileSystem {
public abstract String[][] getFileCacheHints(File f, long start, long len) throws IOException;
/**
- * Opens an NFSDataInputStream for the indicated File.
+ * Opens an NFSDataInputStream at the indicated File.
+ * @param f the file name to open
+ * @param overwrite if a file with this name already exists, then if true,
+ * the file will be overwritten, and if false an error will be thrown.
+ * @param bufferSize the size of the buffer to be used.
*/
- public NFSDataInputStream open(File f) throws IOException {
- return open(f, NutchConf.get().getInt("io.file.buffer.size", 4096));
+ public NFSDataInputStream open(File f, int bufferSize) throws IOException {
+ return new NFSDataInputStream(this, f, bufferSize, this.nutchConf);
}
-
+
/**
* Opens an NFSDataInputStream at the indicated File.
* @param f the file name to open
@@ -156,8 +156,8 @@ public abstract class NutchFileSystem {
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
*/
- public NFSDataInputStream open(File f, int bufferSize) throws IOException {
- return new NFSDataInputStream(this, f, bufferSize);
+ public NFSDataInputStream open(File f) throws IOException {
+ return new NFSDataInputStream(this, f, nutchConf);
}
/**
@@ -171,8 +171,7 @@ public abstract class NutchFileSystem {
* Files are overwritten by default.
*/
public NFSDataOutputStream create(File f) throws IOException {
- return create(f, true,
- NutchConf.get().getInt("io.file.buffer.size", 4096));
+ return create(f, true,this.nutchConf.getInt("io.file.buffer.size", 4096));
}
/**
@@ -184,7 +183,7 @@ public abstract class NutchFileSystem {
*/
public NFSDataOutputStream create(File f, boolean overwrite,
int bufferSize) throws IOException {
- return new NFSDataOutputStream(this, f, overwrite, bufferSize);
+ return new NFSDataOutputStream(this, f, overwrite, this.nutchConf);
}
/** Opens an OutputStream at the indicated File.
diff --git a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java b/src/java/org/apache/nutch/indexer/DeleteDuplicates.java
index f30d35e03..ed71cebbf 100644
--- a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java
+++ b/src/java/org/apache/nutch/indexer/DeleteDuplicates.java
@@ -148,7 +148,7 @@ public class DeleteDuplicates extends NutchConfigured
return new RecordReader() {
private IndexReader indexReader =
- IndexReader.open(new NdfsDirectory(fs, split.getFile(), false));
+ IndexReader.open(new NdfsDirectory(fs, split.getFile(), false, job));
{ indexReader.undeleteAll(); }
@@ -228,6 +228,7 @@ public class DeleteDuplicates extends NutchConfigured
}
private NutchFileSystem fs;
+ private int ioFileBufferSize;
public DeleteDuplicates() { super(null); }
@@ -236,6 +237,7 @@ public class DeleteDuplicates extends NutchConfigured
public void configure(JobConf job) {
try {
fs = NutchFileSystem.get(job);
+ this.ioFileBufferSize = job.getInt("io.file.buffer.size", 4096);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -254,7 +256,7 @@ public class DeleteDuplicates extends NutchConfigured
OutputCollector output, Reporter reporter)
throws IOException {
File index = new File(key.toString());
- IndexReader reader = IndexReader.open(new NdfsDirectory(fs, index, false));
+ IndexReader reader = IndexReader.open(new NdfsDirectory(fs, index, false, getConf()));
try {
while (values.hasNext()) {
reader.delete(((IntWritable)values.next()).get());
@@ -316,6 +318,7 @@ public class DeleteDuplicates extends NutchConfigured
job.setInputKeyClass(HashScore.class);
job.setInputValueClass(IndexDoc.class);
+ job.setInt("io.file.buffer.size", 4096);
job.setMapperClass(DeleteDuplicates.class);
job.setReducerClass(DeleteDuplicates.class);
@@ -331,7 +334,7 @@ public class DeleteDuplicates extends NutchConfigured
}
public static void main(String[] args) throws Exception {
- DeleteDuplicates dedup = new DeleteDuplicates(NutchConf.get());
+ DeleteDuplicates dedup = new DeleteDuplicates(new NutchConf());
if (args.length < 1) {
System.err.println("Usage: <indexes> ...");
diff --git a/src/java/org/apache/nutch/indexer/IndexMerger.java b/src/java/org/apache/nutch/indexer/IndexMerger.java
index db3b5e1d8..54d9dcfd4 100644
--- a/src/java/org/apache/nutch/indexer/IndexMerger.java
+++ b/src/java/org/apache/nutch/indexer/IndexMerger.java
@@ -41,28 +41,21 @@ public class IndexMerger {
public static final String DONE_NAME = "merge.done";
- private int MERGE_FACTOR = NutchConf.get().getInt("indexer.mergeFactor",
- IndexWriter.DEFAULT_MERGE_FACTOR);
- private int MIN_MERGE_DOCS = NutchConf.get().getInt("indexer.minMergeDocs",
- IndexWriter.DEFAULT_MIN_MERGE_DOCS);
- private int MAX_MERGE_DOCS = NutchConf.get().getInt("indexer.maxMergeDocs",
- IndexWriter.DEFAULT_MAX_MERGE_DOCS);
- private int TERM_INDEX_INTERVAL =
- NutchConf.get().getInt("indexer.termIndexInterval",
- IndexWriter.DEFAULT_TERM_INDEX_INTERVAL);
private NutchFileSystem nfs;
private File outputIndex;
private File localWorkingDir;
private File[] indexes;
+ private NutchConf nutchConf;
/**
* Merge all of the indexes given
*/
- public IndexMerger(NutchFileSystem nfs, File[] indexes, File outputIndex, File localWorkingDir) throws IOException {
+ public IndexMerger(NutchFileSystem nfs, File[] indexes, File outputIndex, File localWorkingDir, NutchConf nutchConf) throws IOException {
this.nfs = nfs;
this.indexes = indexes;
this.outputIndex = outputIndex;
this.localWorkingDir = localWorkingDir;
+ this.nutchConf = nutchConf;
}
/**
@@ -81,7 +74,7 @@ public class IndexMerger {
Directory[] dirs = new Directory[indexes.length];
for (int i = 0; i < indexes.length; i++) {
LOG.info("Adding " + indexes[i]);
- dirs[i] = new NdfsDirectory(nfs, indexes[i], false);
+ dirs[i] = new NdfsDirectory(nfs, indexes[i], false, this.nutchConf);
}
//
@@ -90,10 +83,10 @@ public class IndexMerger {
// Merge indices
//
IndexWriter writer = new IndexWriter(localOutput, null, true);
- writer.mergeFactor = MERGE_FACTOR;
- writer.minMergeDocs = MIN_MERGE_DOCS;
- writer.maxMergeDocs = MAX_MERGE_DOCS;
- writer.setTermIndexInterval(TERM_INDEX_INTERVAL);
+ writer.mergeFactor = nutchConf.getInt("indexer.mergeFactor", IndexWriter.DEFAULT_MERGE_FACTOR);
+ writer.minMergeDocs = nutchConf.getInt("indexer.minMergeDocs", IndexWriter.DEFAULT_MIN_MERGE_DOCS);
+ writer.maxMergeDocs = nutchConf.getInt("indexer.maxMergeDocs", IndexWriter.DEFAULT_MAX_MERGE_DOCS);
+ writer.setTermIndexInterval(nutchConf.getInt("indexer.termIndexInterval", IndexWriter.DEFAULT_TERM_INDEX_INTERVAL));
writer.infoStream = LogFormatter.getLogStream(LOG, Level.FINE);
writer.setUseCompoundFile(false);
writer.setSimilarity(new NutchSimilarity());
@@ -121,7 +114,8 @@ public class IndexMerger {
//
// Parse args, read all index directories to be processed
//
- NutchFileSystem nfs = NutchFileSystem.get();
+ NutchConf nutchConf = new NutchConf();
+ NutchFileSystem nfs = NutchFileSystem.get(nutchConf);
File workDir = new File(new File("").getCanonicalPath());
List indexDirs = new ArrayList();
@@ -146,12 +140,12 @@ public class IndexMerger {
File[] indexFiles = (File[])indexDirs.toArray(new File[indexDirs.size()]);
if (workDir.exists()) {
- FileUtil.fullyDelete(workDir);
+ FileUtil.fullyDelete(workDir, nutchConf);
}
workDir.mkdirs();
- IndexMerger merger = new IndexMerger(nfs,indexFiles,outputIndex,workDir);
+ IndexMerger merger = new IndexMerger(nfs,indexFiles,outputIndex,workDir, nutchConf);
merger.merge();
LOG.info("done merging");
- FileUtil.fullyDelete(workDir);
+ FileUtil.fullyDelete(workDir, nutchConf);
}
}
diff --git a/src/java/org/apache/nutch/indexer/IndexSorter.java b/src/java/org/apache/nutch/indexer/IndexSorter.java
index 5c0ecc0d9..2961e8aa3 100644
--- a/src/java/org/apache/nutch/indexer/IndexSorter.java
+++ b/src/java/org/apache/nutch/indexer/IndexSorter.java
@@ -225,14 +225,14 @@ public class IndexSorter {
this.directory = directory;
}
- public void sort() throws IOException {
+ public void sort(int termIndexInterval) throws IOException {
IndexReader reader = IndexReader.open(new File(directory, "index"));
SortingReader sorter = new SortingReader(reader, oldToNew(reader));
IndexWriter writer = new IndexWriter(new File(directory, "index-sorted"),
null, true);
writer.setTermIndexInterval
- (NutchConf.get().getInt("indexer.termIndexInterval", 128));
+ (termIndexInterval);
writer.setUseCompoundFile(false);
writer.addIndexes(new IndexReader[] { sorter });
writer.close();
@@ -283,8 +283,9 @@ public class IndexSorter {
IndexSorter sorter = new IndexSorter(directory);
Date start = new Date();
-
- sorter.sort();
+ NutchConf nutchConf = new NutchConf();
+ int termIndexInterval = nutchConf.getInt("indexer.termIndexInterval", 128);
+ sorter.sort(termIndexInterval);
Date end = new Date();
diff --git a/src/java/org/apache/nutch/indexer/Indexer.java b/src/java/org/apache/nutch/indexer/Indexer.java
index fefcbe0b0..f33aeaa54 100644
--- a/src/java/org/apache/nutch/indexer/Indexer.java
+++ b/src/java/org/apache/nutch/indexer/Indexer.java
@@ -55,7 +55,7 @@ public class Indexer extends NutchConfigured implements Reducer {
reporter.setStatus(split.toString());
- return new SequenceFileRecordReader(fs, split) {
+ return new SequenceFileRecordReader(job, split) {
public synchronized boolean next(Writable key, Writable value)
throws IOException {
ObjectWritable wrapper = (ObjectWritable)value;
@@ -83,7 +83,7 @@ public class Indexer extends NutchConfigured implements Reducer {
final IndexWriter writer = // build locally first
new IndexWriter(fs.startLocalOutput(perm, temp),
- new NutchDocumentAnalyzer(), true);
+ new NutchDocumentAnalyzer(job), true);
writer.mergeFactor = job.getInt("indexer.mergeFactor", 10);
writer.minMergeDocs = job.getInt("indexer.minMergeDocs", 100);
@@ -92,7 +92,7 @@ public class Indexer extends NutchConfigured implements Reducer {
writer.setTermIndexInterval
(job.getInt("indexer.termIndexInterval", 128));
writer.maxFieldLength = job.getInt("indexer.max.tokens", 10000);
- //writer.infoStream = LogFormatter.getLogStream(LOG, Level.FINE);
+ writer.infoStream = LogFormatter.getLogStream(LOG, Level.INFO);
writer.setUseCompoundFile(false);
writer.setSimilarity(new NutchSimilarity());
@@ -133,6 +133,8 @@ public class Indexer extends NutchConfigured implements Reducer {
}
}
+ private IndexingFilters filters;
+
public Indexer() {
super(null);
}
@@ -146,6 +148,8 @@ public class Indexer extends NutchConfigured implements Reducer {
public void configure(JobConf job) {
scorePower = job.getFloat("indexer.score.power", 0.5f);
+ setConf(job);
+ this.filters = new IndexingFilters(getConf());
}
public void reduce(WritableComparable key, Iterator values,
@@ -217,7 +221,7 @@ public class Indexer extends NutchConfigured implements Reducer {
try {
// run indexing filters
- doc = IndexingFilters.filter(doc,new ParseImpl(parseText, parseData), (UTF8)key, fetchDatum, inlinks);
+ doc = this.filters.filter(doc,new ParseImpl(parseText, parseData), (UTF8)key, fetchDatum, inlinks);
} catch (IndexingException e) {
LOG.warning("Error indexing "+key+": "+e);
return;
@@ -261,7 +265,7 @@ public class Indexer extends NutchConfigured implements Reducer {
}
public static void main(String[] args) throws Exception {
- Indexer indexer = new Indexer(NutchConf.get());
+ Indexer indexer = new Indexer(new NutchConf());
if (args.length < 4) {
System.err.println("Usage: <index> <crawldb> <linkdb> <segment> ...");
diff --git a/src/java/org/apache/nutch/indexer/IndexingFilter.java b/src/java/org/apache/nutch/indexer/IndexingFilter.java
index 79846b1d6..1c2c4c59e 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFilter.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFilter.java
@@ -18,6 +18,7 @@ package org.apache.nutch.indexer;
import org.apache.lucene.document.Document;
import org.apache.nutch.parse.Parse;
+import org.apache.nutch.util.NutchConfigurable;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.io.UTF8;
@@ -26,7 +27,7 @@ import org.apache.nutch.io.UTF8;
* fields. All plugins found which implement this extension point are run
* sequentially on the parse.
*/
-public interface IndexingFilter {
+public interface IndexingFilter extends NutchConfigurable {
/** The name of the extension point. */
final static String X_POINT_ID = IndexingFilter.class.getName();
diff --git a/src/java/org/apache/nutch/indexer/IndexingFilters.java b/src/java/org/apache/nutch/indexer/IndexingFilters.java
index 631c5c12c..801a88a4d 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFilters.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFilters.java
@@ -22,6 +22,7 @@ import org.apache.lucene.document.Document;
import org.apache.nutch.plugin.*;
import org.apache.nutch.parse.Parse;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.io.UTF8;
@@ -29,37 +30,38 @@ import org.apache.nutch.io.UTF8;
/** Creates and caches {@link IndexingFilter} implementing plugins.*/
public class IndexingFilters {
- private static final IndexingFilter[] CACHE;
- static {
- try {
- ExtensionPoint point = PluginRepository.getInstance()
- .getExtensionPoint(IndexingFilter.X_POINT_ID);
- if (point == null)
- throw new RuntimeException(IndexingFilter.X_POINT_ID+" not found.");
- Extension[] extensions = point.getExtensions();
- HashMap filterMap = new HashMap();
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- IndexingFilter filter = (IndexingFilter)extension.getExtensionInstance();
- System.out.println("-adding " + filter.getClass().getName());
- if (!filterMap.containsKey(filter.getClass().getName())) {
- filterMap.put(filter.getClass().getName(), filter);
- }
- }
- CACHE = (IndexingFilter[])filterMap.values().toArray(new IndexingFilter[0]);
- } catch (PluginRuntimeException e) {
- throw new RuntimeException(e);
- }
- }
+ private IndexingFilter[] indexingFilters;
- private IndexingFilters() {} // no public ctor
+ public IndexingFilters(NutchConf nutchConf) {
+ this.indexingFilters =(IndexingFilter[]) nutchConf.getObject(IndexingFilter.class.getName());
+ if (this.indexingFilters == null) {
+ try {
+ ExtensionPoint point = nutchConf.getPluginRepository().getExtensionPoint(IndexingFilter.X_POINT_ID);
+ if (point == null)
+ throw new RuntimeException(IndexingFilter.X_POINT_ID + " not found.");
+ Extension[] extensions = point.getExtensions();
+ HashMap filterMap = new HashMap();
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ IndexingFilter filter = (IndexingFilter) extension.getExtensionInstance();
+ System.out.println("-adding " + filter.getClass().getName());
+ if (!filterMap.containsKey(filter.getClass().getName())) {
+ filterMap.put(filter.getClass().getName(), filter);
+ }
+ }
+ nutchConf.setObject(IndexingFilter.class.getName(), (IndexingFilter[]) filterMap.values().toArray(new IndexingFilter[0]));
+ } catch (PluginRuntimeException e) {
+ throw new RuntimeException(e);
+ }
+ this.indexingFilters =(IndexingFilter[]) nutchConf.getObject(IndexingFilter.class.getName());
+ }
+ }
/** Run all defined filters. */
- public static Document filter(Document doc, Parse parse, UTF8 url, CrawlDatum datum, Inlinks inlinks)
+ public Document filter(Document doc, Parse parse, UTF8 url, CrawlDatum datum, Inlinks inlinks)
throws IndexingException {
-
- for (int i = 0; i < CACHE.length; i++) {
- doc = CACHE[i].filter(doc, parse, url, datum, inlinks);
+ for (int i = 0; i < this.indexingFilters.length; i++) {
+ doc = this.indexingFilters[i].filter(doc, parse, url, datum, inlinks);
}
return doc;
diff --git a/src/java/org/apache/nutch/indexer/NdfsDirectory.java b/src/java/org/apache/nutch/indexer/NdfsDirectory.java
index 885282254..f0ddc6f39 100644
--- a/src/java/org/apache/nutch/indexer/NdfsDirectory.java
+++ b/src/java/org/apache/nutch/indexer/NdfsDirectory.java
@@ -19,19 +19,22 @@ package org.apache.nutch.indexer;
import java.io.*;
import org.apache.lucene.store.*;
import org.apache.nutch.fs.*;
+import org.apache.nutch.util.NutchConf;
/** Reads a Lucene index stored in NDFS. */
public class NdfsDirectory extends Directory {
private NutchFileSystem fs;
private File directory;
+ private int ioFileBufferSize;
- public NdfsDirectory(NutchFileSystem fs, File directory, boolean create)
+ public NdfsDirectory(NutchFileSystem fs, File directory, boolean create, NutchConf nutchConf)
throws IOException {
this.fs = fs;
this.directory = directory;
-
+ this.ioFileBufferSize = nutchConf.getInt("io.file.buffer.size", 4096);
+
if (create) {
create();
}
@@ -103,12 +106,12 @@ public class NdfsDirectory extends Directory {
if (fs.exists(file) && !fs.delete(file)) // delete existing, if any
throw new IOException("Cannot overwrite: " + file);
- return new NdfsIndexOutput(file);
+ return new NdfsIndexOutput(file, this.ioFileBufferSize);
}
public IndexInput openInput(String name) throws IOException {
- return new NdfsIndexInput(new File(directory, name));
+ return new NdfsIndexInput(new File(directory, name), this.ioFileBufferSize);
}
public Lock makeLock(final String name) {
@@ -152,7 +155,7 @@ public class NdfsDirectory extends Directory {
private class Descriptor {
public NFSDataInputStream in;
public long position; // cache of in.getPos()
- public Descriptor(File file) throws IOException {
+ public Descriptor(File file, int ioFileBufferSize) throws IOException {
this.in = fs.open(file);
}
}
@@ -161,8 +164,8 @@ public class NdfsDirectory extends Directory {
private final long length;
private boolean isClone;
- public NdfsIndexInput(File path) throws IOException {
- descriptor = new Descriptor(path);
+ public NdfsIndexInput(File path, int ioFileBufferSize) throws IOException {
+ descriptor = new Descriptor(path,ioFileBufferSize);
length = fs.getLength(path);
}
@@ -211,7 +214,7 @@ public class NdfsDirectory extends Directory {
private class NdfsIndexOutput extends BufferedIndexOutput {
private NFSDataOutputStream out;
- public NdfsIndexOutput(File path) throws IOException {
+ public NdfsIndexOutput(File path, int ioFileBufferSize) throws IOException {
out = fs.create(path);
}
diff --git a/src/java/org/apache/nutch/io/ArrayFile.java b/src/java/org/apache/nutch/io/ArrayFile.java
index d11774f17..1c39c28db 100644
--- a/src/java/org/apache/nutch/io/ArrayFile.java
+++ b/src/java/org/apache/nutch/io/ArrayFile.java
@@ -46,8 +46,8 @@ public class ArrayFile extends MapFile {
private LongWritable key = new LongWritable();
/** Construct an array reader for the named file.*/
- public Reader(NutchFileSystem nfs, String file) throws IOException {
- super(nfs, file);
+ public Reader(NutchFileSystem nfs, String file, NutchConf nutchConf) throws IOException {
+ super(nfs, file, nutchConf);
}
/** Positions the reader before its <code>n</code>th value. */
diff --git a/src/java/org/apache/nutch/io/MapFile.java b/src/java/org/apache/nutch/io/MapFile.java
index f05e33884..8c9000ce7 100644
--- a/src/java/org/apache/nutch/io/MapFile.java
+++ b/src/java/org/apache/nutch/io/MapFile.java
@@ -44,11 +44,8 @@ public class MapFile {
/** The name of the data file. */
public static final String DATA_FILE_NAME = "data";
- /** Number of index entries to skip between each entry. Zero by default.
- * Setting this to values larger than zero can facilitate opening large map
- * files using less memory. */
- public static final int INDEX_SKIP =
- NutchConf.get().getInt("io.map.index.skip", 0);
+
+
protected MapFile() {} // no public ctor
@@ -160,6 +157,12 @@ public class MapFile {
/** Provide access to an existing map. */
public static class Reader {
+
+ /** Number of index entries to skip between each entry. Zero by default.
+ * Setting this to values larger than zero can facilitate opening large map
+ * files using less memory. */
+ private int INDEX_SKIP = 0;
+
private WritableComparator comparator;
private DataOutputBuffer keyBuf = new DataOutputBuffer();
@@ -190,19 +193,20 @@ public class MapFile {
public Class getValueClass() { return data.getValueClass(); }
/** Construct a map reader for the named map.*/
- public Reader(NutchFileSystem nfs, String dirName) throws IOException {
- this(nfs, dirName, null);
+ public Reader(NutchFileSystem nfs, String dirName, NutchConf nutchConf) throws IOException {
+ this(nfs, dirName, null, nutchConf);
+ INDEX_SKIP = nutchConf.getInt("io.map.index.skip", 0);
}
/** Construct a map reader for the named map using the named comparator.*/
- public Reader(NutchFileSystem nfs, String dirName, WritableComparator comparator)
+ public Reader(NutchFileSystem nfs, String dirName, WritableComparator comparator, NutchConf nutchConf)
throws IOException {
File dir = new File(dirName);
File dataFile = new File(dir, DATA_FILE_NAME);
File indexFile = new File(dir, INDEX_FILE_NAME);
// open the data
- this.data = new SequenceFile.Reader(nfs, dataFile.getPath());
+ this.data = new SequenceFile.Reader(nfs, dataFile.getPath(), nutchConf);
this.firstPosition = data.getPosition();
if (comparator == null)
@@ -213,7 +217,7 @@ public class MapFile {
this.getKey = this.comparator.newKey();
// open the index
- this.index = new SequenceFile.Reader(nfs, indexFile.getPath());
+ this.index = new SequenceFile.Reader(nfs, indexFile.getPath(), nutchConf);
}
private void readIndex() throws IOException {
@@ -416,7 +420,7 @@ public class MapFile {
* @throws Exception
*/
public static long fix(NutchFileSystem nfs, File dir,
- Class keyClass, Class valueClass, boolean dryrun) throws Exception {
+ Class keyClass, Class valueClass, boolean dryrun, NutchConf nutchConf) throws Exception {
String dr = (dryrun ? "[DRY RUN ] " : "");
File data = new File(dir, DATA_FILE_NAME);
File index = new File(dir, INDEX_FILE_NAME);
@@ -429,7 +433,7 @@ public class MapFile {
// no fixing needed
return -1;
}
- SequenceFile.Reader dataReader = new SequenceFile.Reader(nfs, data.toString());
+ SequenceFile.Reader dataReader = new SequenceFile.Reader(nfs, data.toString(), nutchConf);
if (!dataReader.getKeyClass().equals(keyClass)) {
throw new Exception(dr + "Wrong key class in " + dir + ", expected" + keyClass.getName() +
", got " + dataReader.getKeyClass().getName());
@@ -474,8 +478,10 @@ public class MapFile {
String in = args[0];
String out = args[1];
- NutchFileSystem nfs = new LocalFileSystem();
- MapFile.Reader reader = new MapFile.Reader(nfs, in);
+ NutchConf conf = new NutchConf();
+ int ioFileBufferSize = conf.getInt("io.file.buffer.size", 4096);
+ NutchFileSystem nfs = new LocalFileSystem(conf);
+ MapFile.Reader reader = new MapFile.Reader(nfs, in, conf);
MapFile.Writer writer =
new MapFile.Writer(nfs, out, reader.getKeyClass(), reader.getValueClass());
diff --git a/src/java/org/apache/nutch/io/ObjectWritable.java b/src/java/org/apache/nutch/io/ObjectWritable.java
index bcf9c06af..69bb02947 100644
--- a/src/java/org/apache/nutch/io/ObjectWritable.java
+++ b/src/java/org/apache/nutch/io/ObjectWritable.java
@@ -25,13 +25,17 @@ import java.lang.reflect.InvocationTargetException;
import java.io.*;
import java.util.*;
+import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
+
/** A polymorphic Writable that writes an instance with it's class name.
* Handles arrays, strings and primitive types without a Writable wrapper.
*/
-public class ObjectWritable implements Writable {
+public class ObjectWritable implements Writable, NutchConfigurable {
private Class declaredClass;
private Object instance;
+ private NutchConf nutchConf;
public ObjectWritable() {}
@@ -57,7 +61,7 @@ public class ObjectWritable implements Writable {
}
public void readFields(DataInput in) throws IOException {
- readObject(in, this);
+ readObject(in, this, this.nutchConf);
}
public void write(DataOutput out) throws IOException {
@@ -165,14 +169,14 @@ public class ObjectWritable implements Writable {
/** Read a {@link Writable}, {@link String}, primitive type, or an array of
* the preceding. */
- public static Object readObject(DataInput in)
+ public static Object readObject(DataInput in, NutchConf nutchConf)
throws IOException {
- return readObject(in, null);
+ return readObject(in, null, nutchConf);
}
/** Read a {@link Writable}, {@link String}, primitive type, or an array of
* the preceding. */
- public static Object readObject(DataInput in, ObjectWritable objectWritable)
+ public static Object readObject(DataInput in, ObjectWritable objectWritable, NutchConf nutchConf)
throws IOException {
String className = UTF8.readString(in);
Class declaredClass = (Class)PRIMITIVE_NAMES.get(className);
@@ -220,7 +224,7 @@ public class ObjectWritable implements Writable {
int length = in.readInt();
instance = Array.newInstance(declaredClass.getComponentType(), length);
for (int i = 0; i < length; i++) {
- Array.set(instance, i, readObject(in));
+ Array.set(instance, i, readObject(in, nutchConf));
}
} else if (declaredClass == String.class) { // String
@@ -229,6 +233,9 @@ public class ObjectWritable implements Writable {
} else { // Writable
try {
Writable writable = (Writable)declaredClass.newInstance();
+ if(writable instanceof NutchConfigurable) {
+ ((NutchConfigurable) writable).setConf(nutchConf);
+ }
writable.readFields(in);
instance = writable;
} catch (InstantiationException e) {
@@ -246,5 +253,13 @@ public class ObjectWritable implements Writable {
return instance;
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/java/org/apache/nutch/io/SequenceFile.java b/src/java/org/apache/nutch/io/SequenceFile.java
index 22c38dbce..78d585f06 100644
--- a/src/java/org/apache/nutch/io/SequenceFile.java
+++ b/src/java/org/apache/nutch/io/SequenceFile.java
@@ -222,10 +222,12 @@ public class SequenceFile {
private byte[] inflateIn = new byte[1024];
private DataOutputBuffer inflateOut = new DataOutputBuffer();
private Inflater inflater = new Inflater();
+ private NutchConf nutchConf;
/** Open the named file. */
- public Reader(NutchFileSystem nfs, String file) throws IOException {
- this(nfs, file, NutchConf.get().getInt("io.file.buffer.size", 4096));
+ public Reader(NutchFileSystem nfs, String file, NutchConf nutchConf) throws IOException {
+ this(nfs, file, nutchConf.getInt("io.file.buffer.size", 4096));
+ this.nutchConf = nutchConf;
}
private Reader(NutchFileSystem nfs, String name, int bufferSize) throws IOException {
@@ -339,7 +341,9 @@ public class SequenceFile {
}
inBuf.reset(inflateOut.getData(), inflateOut.getLength());
}
-
+ if(val instanceof NutchConfigurable) {
+ ((NutchConfigurable) val).setConf(this.nutchConf);
+ }
val.readFields(inBuf);
if (inBuf.getPosition() != inBuf.getLength())
@@ -386,9 +390,9 @@ public class SequenceFile {
private void handleChecksumException(ChecksumException e)
throws IOException {
- if (NutchConf.get().getBoolean("io.skip.checksum.errors", false)) {
+ if (this.nutchConf.getBoolean("io.skip.checksum.errors", false)) {
LOG.warning("Bad checksum at "+getPosition()+". Skipping entries.");
- sync(getPosition()+NutchConf.get().getInt("io.bytes.per.checksum", 512));
+ sync(getPosition()+this.nutchConf.getInt("io.bytes.per.checksum", 512));
} else {
throw e;
}
@@ -449,10 +453,6 @@ public class SequenceFile {
* very efficient. In particular, it should avoid allocating memory.
*/
public static class Sorter {
- private static final int FACTOR =
- NutchConf.get().getInt("io.sort.factor", 100);
- private static final int MEGABYTES =
- NutchConf.get().getInt("io.sort.mb", 100);
private WritableComparator comparator;
@@ -461,25 +461,30 @@ public class SequenceFile {
private String outFile;
- private int memory = MEGABYTES * 1024*1024; // bytes
- private int factor = FACTOR; // merged per pass
+ private int memory; // bytes
+ private int factor; // merged per pass
private NutchFileSystem nfs = null;
private Class keyClass;
private Class valClass;
+ private NutchConf nutchConf;
+
/** Sort and merge files containing the named classes. */
- public Sorter(NutchFileSystem nfs, Class keyClass, Class valClass) {
- this(nfs, new WritableComparator(keyClass), valClass);
+ public Sorter(NutchFileSystem nfs, Class keyClass, Class valClass, NutchConf nutchConf) {
+ this(nfs, new WritableComparator(keyClass), valClass, nutchConf);
}
/** Sort and merge using an arbitrary {@link WritableComparator}. */
- public Sorter(NutchFileSystem nfs, WritableComparator comparator, Class valClass) {
+ public Sorter(NutchFileSystem nfs, WritableComparator comparator, Class valClass, NutchConf nutchConf) {
this.nfs = nfs;
this.comparator = comparator;
this.keyClass = comparator.getKeyClass();
this.valClass = valClass;
+ this.memory = nutchConf.getInt("io.sort.mb", 100) * 1024 * 1024;
+ this.factor = nutchConf.getInt("io.sort.factor", 100);
+ this.nutchConf = nutchConf;
}
/** Set the number of streams to merge at once.*/
@@ -513,7 +518,7 @@ public class SequenceFile {
private int sortPass() throws IOException {
LOG.fine("running sort pass");
- SortPass sortPass = new SortPass(); // make the SortPass
+ SortPass sortPass = new SortPass(this.nutchConf); // make the SortPass
try {
return sortPass.run(); // run it
} finally {
@@ -536,8 +541,8 @@ public class SequenceFile {
private NFSDataOutputStream out;
private String outName;
- public SortPass() throws IOException {
- in = new Reader(nfs, inFile);
+ public SortPass(NutchConf nutchConf) throws IOException {
+ in = new Reader(nfs, inFile, nutchConf);
}
public int run() throws IOException {
diff --git a/src/java/org/apache/nutch/io/SetFile.java b/src/java/org/apache/nutch/io/SetFile.java
index e5a0ec5e7..e8501a97e 100644
--- a/src/java/org/apache/nutch/io/SetFile.java
+++ b/src/java/org/apache/nutch/io/SetFile.java
@@ -51,14 +51,14 @@ public class SetFile extends MapFile {
public static class Reader extends MapFile.Reader {
/** Construct a set reader for the named set.*/
- public Reader(NutchFileSystem nfs, String dirName) throws IOException {
- super(nfs, dirName);
+ public Reader(NutchFileSystem nfs, String dirName, NutchConf nutchConf) throws IOException {
+ super(nfs, dirName, nutchConf);
}
/** Construct a set reader for the named set using the named comparator.*/
- public Reader(NutchFileSystem nfs, String dirName, WritableComparator comparator)
+ public Reader(NutchFileSystem nfs, String dirName, WritableComparator comparator, NutchConf nutchConf)
throws IOException {
- super(nfs, dirName, comparator);
+ super(nfs, dirName, comparator, nutchConf);
}
// javadoc inherited
diff --git a/src/java/org/apache/nutch/ipc/Client.java b/src/java/org/apache/nutch/ipc/Client.java
index ea5fc5062..1b00a354f 100644
--- a/src/java/org/apache/nutch/ipc/Client.java
+++ b/src/java/org/apache/nutch/ipc/Client.java
@@ -35,6 +35,7 @@ import java.util.logging.Level;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
import org.apache.nutch.io.Writable;
import org.apache.nutch.io.UTF8;
@@ -52,9 +53,10 @@ public class Client {
private Hashtable connections = new Hashtable();
private Class valueClass; // class of call values
- private int timeout = NutchConf.get().getInt("ipc.client.timeout",10000); // timeout for calls
+ private int timeout ;// timeout for calls
private int counter; // counter for call ids
private boolean running = true; // true while client runs
+ private NutchConf nutchConf;
/** A call waiting for a value. */
private class Call {
@@ -160,6 +162,9 @@ public class Client {
Writable value = makeValue();
try {
readingCall = call;
+ if(value instanceof NutchConfigurable) {
+ ((NutchConfigurable) value).setConf(nutchConf);
+ }
value.readFields(in); // read value
} finally {
readingCall = null;
@@ -256,8 +261,10 @@ public class Client {
/** Construct an IPC client whose values are of the given {@link Writable}
* class. */
- public Client(Class valueClass) {
+ public Client(Class valueClass, NutchConf nutchConf) {
this.valueClass = valueClass;
+ this.timeout = nutchConf.getInt("ipc.client.timeout",10000);
+ this.nutchConf = nutchConf;
}
/** Stop all threads related to this client. No further calls may be made
diff --git a/src/java/org/apache/nutch/ipc/RPC.java b/src/java/org/apache/nutch/ipc/RPC.java
index 134f70895..0c26d5133 100644
--- a/src/java/org/apache/nutch/ipc/RPC.java
+++ b/src/java/org/apache/nutch/ipc/RPC.java
@@ -56,10 +56,11 @@ public class RPC {
/** A method invocation, including the method name and its parameters.*/
- private static class Invocation implements Writable {
+ private static class Invocation implements Writable, NutchConfigurable {
private String methodName;
private Class[] parameterClasses;
private Object[] parameters;
+ private NutchConf nutchConf;
public Invocation() {}
@@ -82,10 +83,9 @@ public class RPC {
methodName = UTF8.readString(in);
parameters = new Object[in.readInt()];
parameterClasses = new Class[parameters.length];
-
ObjectWritable objectWritable = new ObjectWritable();
for (int i = 0; i < parameters.length; i++) {
- parameters[i] = ObjectWritable.readObject(in, objectWritable);
+ parameters[i] = ObjectWritable.readObject(in, objectWritable, this.nutchConf);
parameterClasses[i] = objectWritable.getDeclaredClass();
}
}
@@ -111,15 +111,29 @@ public class RPC {
return buffer.toString();
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
- private static Client CLIENT = new Client(ObjectWritable.class);
+ //TODO [email protected]: static client or non-static client?
+ private static Client CLIENT;
private static class Invoker implements InvocationHandler {
private InetSocketAddress address;
- public Invoker(InetSocketAddress address) {
+ public Invoker(InetSocketAddress address, NutchConf nutchConf) {
this.address = address;
+ CLIENT = (Client) nutchConf.getObject(Client.class.getName());
+ if(CLIENT == null) {
+ CLIENT = new Client(ObjectWritable.class, nutchConf);
+ nutchConf.setObject(Client.class.getName(), CLIENT);
+ }
}
public Object invoke(Object proxy, Method method, Object[] args)
@@ -132,21 +146,25 @@ public class RPC {
/** Construct a client-side proxy object that implements the named protocol,
* talking to a server at the named address. */
- public static Object getProxy(Class protocol, InetSocketAddress addr) {
+ public static Object getProxy(Class protocol, InetSocketAddress addr, NutchConf nutchConf) {
return Proxy.newProxyInstance(protocol.getClassLoader(),
new Class[] { protocol },
- new Invoker(addr));
+ new Invoker(addr, nutchConf));
}
/** Expert: Make multiple, parallel calls to a set of servers. */
public static Object[] call(Method method, Object[][] params,
- InetSocketAddress[] addrs)
+ InetSocketAddress[] addrs, NutchConf nutchConf)
throws IOException {
Invocation[] invocations = new Invocation[params.length];
for (int i = 0; i < params.length; i++)
invocations[i] = new Invocation(method, params[i]);
-
+ CLIENT = (Client) nutchConf.getObject(Client.class.getName());
+ if(CLIENT == null) {
+ CLIENT = new Client(ObjectWritable.class, nutchConf);
+ nutchConf.setObject(Client.class.getName(), CLIENT);
+ }
Writable[] wrappedValues = CLIENT.call(invocations, addrs);
if (method.getReturnType() == Void.TYPE) {
@@ -165,16 +183,16 @@ public class RPC {
/** Construct a server for a protocol implementation instance listening on a
* port. */
- public static Server getServer(final Object instance, final int port) {
- return getServer(instance, port, 1, false);
+ public static Server getServer(final Object instance, final int port, NutchConf nutchConf) {
+ return getServer(instance, port, 1, false, nutchConf);
}
/** Construct a server for a protocol implementation instance listening on a
* port. */
public static Server getServer(final Object instance, final int port,
final int numHandlers,
- final boolean verbose) {
- return new Server(port, Invocation.class, numHandlers) {
+ final boolean verbose, NutchConf nutchConf) {
+ return new Server(port, Invocation.class, numHandlers, nutchConf) {
Class implementation = instance.getClass();
diff --git a/src/java/org/apache/nutch/ipc/Server.java b/src/java/org/apache/nutch/ipc/Server.java
index 3aa990064..beb34fc5c 100644
--- a/src/java/org/apache/nutch/ipc/Server.java
+++ b/src/java/org/apache/nutch/ipc/Server.java
@@ -53,7 +53,7 @@ public abstract class Server {
private int maxQueuedCalls; // max number of queued calls
private Class paramClass; // class of call parameters
- private int timeout = NutchConf.get().getInt("ipc.client.timeout",10000);
+ private int timeout;
private boolean running = true; // true while server runs
private LinkedList callQueue = new LinkedList(); // queued calls
@@ -228,11 +228,12 @@ public abstract class Server {
* be of the named class. The <code>handlerCount</handlerCount> determines
* the number of handler threads that will be used to process calls.
*/
- protected Server(int port, Class paramClass, int handlerCount) {
+ protected Server(int port, Class paramClass, int handlerCount, NutchConf nutchConf) {
this.port = port;
this.paramClass = paramClass;
this.handlerCount = handlerCount;
this.maxQueuedCalls = handlerCount;
+ this.timeout = nutchConf.getInt("ipc.client.timeout",10000);
}
/** Sets the timeout used for network i/o. */
diff --git a/src/java/org/apache/nutch/mapred/CombiningCollector.java b/src/java/org/apache/nutch/mapred/CombiningCollector.java
index 634841b94..2f4e9f5b8 100644
--- a/src/java/org/apache/nutch/mapred/CombiningCollector.java
+++ b/src/java/org/apache/nutch/mapred/CombiningCollector.java
@@ -28,8 +28,7 @@ import org.apache.nutch.util.*;
* then invokes the combiner's reduce method to merge some values before
* they're transferred to a reduce node. */
class CombiningCollector implements OutputCollector {
- private static final int LIMIT
- = NutchConf.get().getInt("mapred.combine.buffer.size", 100000);
+ private int limit;
private int count = 0;
private Map keyToValues; // the buffer
@@ -46,6 +45,7 @@ class CombiningCollector implements OutputCollector {
this.reporter = reporter;
this.combiner = (Reducer)job.newInstance(job.getCombinerClass());
this.keyToValues = new TreeMap(job.getOutputKeyComparator());
+ this.limit = job.getInt("mapred.combine.buffer.size", 100000);
}
public synchronized void collect(WritableComparable key, Writable value)
@@ -63,7 +63,7 @@ class CombiningCollector implements OutputCollector {
count++;
- if (count >= LIMIT) { // time to flush
+ if (count >= this.limit) { // time to flush
flush();
}
}
diff --git a/src/java/org/apache/nutch/mapred/JobClient.java b/src/java/org/apache/nutch/mapred/JobClient.java
index 4eaf1f6ff..4ff1e855a 100644
--- a/src/java/org/apache/nutch/mapred/JobClient.java
+++ b/src/java/org/apache/nutch/mapred/JobClient.java
@@ -166,28 +166,30 @@ public class JobClient implements MRConstants {
JobSubmissionProtocol jobSubmitClient;
NutchFileSystem fs = null;
+ private NutchConf nutchConf;
static Random r = new Random();
/**
* Build a job client, connect to the default job tracker
*/
public JobClient(NutchConf conf) throws IOException {
+ this.nutchConf = conf;
String tracker = conf.get("mapred.job.tracker", "local");
if ("local".equals(tracker)) {
- this.jobSubmitClient = new LocalJobRunner();
+ this.jobSubmitClient = new LocalJobRunner(conf);
} else {
this.jobSubmitClient = (JobSubmissionProtocol)
RPC.getProxy(JobSubmissionProtocol.class,
- JobTracker.getAddress(conf));
+ JobTracker.getAddress(conf), conf);
}
}
/**
* Build a job client, connect to the indicated job tracker.
*/
- public JobClient(InetSocketAddress jobTrackAddr) throws IOException {
+ public JobClient(InetSocketAddress jobTrackAddr, NutchConf nutchConf) throws IOException {
this.jobSubmitClient = (JobSubmissionProtocol)
- RPC.getProxy(JobSubmissionProtocol.class, jobTrackAddr);
+ RPC.getProxy(JobSubmissionProtocol.class, jobTrackAddr, nutchConf);
}
@@ -207,7 +209,7 @@ public class JobClient implements MRConstants {
public synchronized NutchFileSystem getFs() throws IOException {
if (this.fs == null) {
String fsName = jobSubmitClient.getFilesystemName();
- this.fs = NutchFileSystem.getNamed(fsName);
+ this.fs = NutchFileSystem.getNamed(fsName, this.nutchConf);
}
return fs;
}
@@ -234,7 +236,7 @@ public class JobClient implements MRConstants {
//
// Create a number of filenames in the JobTracker's fs namespace
- File submitJobDir = new File(JobConf.getSystemDir(), "submit_" + Integer.toString(Math.abs(r.nextInt()),36));
+ File submitJobDir = new File(job.getSystemDir(), "submit_" + Integer.toString(Math.abs(r.nextInt()), 36));
File submitJobFile = new File(submitJobDir, "job.xml");
File submitJarFile = new File(submitJobDir, "job.jar");
@@ -349,7 +351,7 @@ public class JobClient implements MRConstants {
}
// Submit the request
- JobClient jc = new JobClient(NutchConf.get());
+ JobClient jc = new JobClient(new NutchConf());
try {
if (submitJobFile != null) {
RunningJob job = jc.submitJob(submitJobFile);
diff --git a/src/java/org/apache/nutch/mapred/JobConf.java b/src/java/org/apache/nutch/mapred/JobConf.java
index b318e91ef..a34bfacc0 100644
--- a/src/java/org/apache/nutch/mapred/JobConf.java
+++ b/src/java/org/apache/nutch/mapred/JobConf.java
@@ -50,9 +50,15 @@ import org.apache.nutch.mapred.lib.HashPartitioner;
* of input files, and where the output files should be written. */
public class JobConf extends NutchConf {
- /** Construct a map/reduce job configuration.
- *
- * @param conf a NutchConf whose settings will be inherited.
+ public JobConf() {
+ super();
+ }
+
+ /**
+ * Construct a map/reduce job configuration.
+ *
+ * @param conf
+ * a NutchConf whose settings will be inherited.
*/
public JobConf(NutchConf conf) {
super(conf);
@@ -81,32 +87,32 @@ public class JobConf extends NutchConf {
public String getJar() { return get("mapred.jar"); }
public void setJar(String jar) { set("mapred.jar", jar); }
- public static File getSystemDir() {
- return new File(NutchConf.get().get("mapred.system.dir",
+ public File getSystemDir() {
+ return new File(get("mapred.system.dir",
"/tmp/nutch/mapred/system"));
}
- public static String[] getLocalDirs() throws IOException {
- return NutchConf.get().getStrings("mapred.local.dir");
+ public String[] getLocalDirs() throws IOException {
+ return getStrings("mapred.local.dir");
}
- public static void deleteLocalFiles() throws IOException {
+ public void deleteLocalFiles() throws IOException {
String[] localDirs = getLocalDirs();
for (int i = 0; i < localDirs.length; i++) {
- FileUtil.fullyDelete(new File(localDirs[i]));
+ FileUtil.fullyDelete(new File(localDirs[i]), this);
}
}
- public static void deleteLocalFiles(String subdir) throws IOException {
+ public void deleteLocalFiles(String subdir) throws IOException {
String[] localDirs = getLocalDirs();
for (int i = 0; i < localDirs.length; i++) {
- FileUtil.fullyDelete(new File(localDirs[i], subdir));
+ FileUtil.fullyDelete(new File(localDirs[i], subdir), this);
}
}
/** Constructs a local file name. Files are distributed among configured
* local directories.*/
- public static File getLocalFile(String subdir, String name)
+ public File getLocalFile(String subdir, String name)
throws IOException {
String[] localDirs = getLocalDirs();
String path = subdir + File.separator + name;
diff --git a/src/java/org/apache/nutch/mapred/JobTracker.java b/src/java/org/apache/nutch/mapred/JobTracker.java
index 0458b813b..052ff3516 100644
--- a/src/java/org/apache/nutch/mapred/JobTracker.java
+++ b/src/java/org/apache/nutch/mapred/JobTracker.java
@@ -210,25 +210,29 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
NutchFileSystem fs;
File systemDir;
+ private NutchConf nutchConf;
+
/**
* Start the JobTracker process, listen on the indicated port
*/
JobTracker(NutchConf conf) throws IOException {
// This is a directory of temporary submission files. We delete it
// on startup, and can delete any files that we're done with
- this.systemDir = JobConf.getSystemDir();
- this.fs = NutchFileSystem.get();
+ JobConf jobConf = new JobConf(conf);
+ this.systemDir = jobConf.getSystemDir();
+ this.nutchConf = conf;
+ this.fs = NutchFileSystem.get(conf);
FileUtil.fullyDelete(fs, systemDir);
fs.mkdirs(systemDir);
// Same with 'localDir' except it's always on the local disk.
- JobConf.deleteLocalFiles(SUBDIR);
+ jobConf.deleteLocalFiles(SUBDIR);
// Set ports, start RPC servers, etc.
InetSocketAddress addr = getAddress(conf);
this.localMachine = addr.getHostName();
this.port = addr.getPort();
- this.interTrackerServer = RPC.getServer(this,addr.getPort(),10,false);
+ this.interTrackerServer = RPC.getServer(this, addr.getPort(), 10, false, conf);
this.interTrackerServer.start();
Properties p = System.getProperties();
for (Iterator it = p.keySet().iterator(); it.hasNext(); ) {
@@ -529,7 +533,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
* task allocation.)
*/
JobInProgress createJob(String jobFile) throws IOException {
- JobInProgress job = new JobInProgress(jobFile);
+ JobInProgress job = new JobInProgress(jobFile, this.nutchConf);
jobs.put(job.getProfile().getJobId(), job);
boolean error = true;
@@ -576,6 +580,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
long startTime;
long finishTime;
String deleteUponCompletion = null;
+ private NutchConf nutchConf;
/**
* Create a 'JobInProgress' object, which contains both JobProfile
@@ -583,13 +588,13 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
* of the JobTracker. But JobInProgress adds info that's useful for
* the JobTracker alone.
*/
- public JobInProgress(String jobFile) throws IOException {
+ public JobInProgress(String jobFile, NutchConf nutchConf) throws IOException {
String jobid = createJobId();
String url = "http://" + localMachine + ":" + infoPort + "/jobdetails.jsp?jobid=" + jobid;
this.profile = new JobProfile(jobid, jobFile, url);
this.status = new JobStatus(jobid, 0.0f, 0.0f, JobStatus.RUNNING);
- this.localJobFile = JobConf.getLocalFile(SUBDIR, jobid+".xml");
+ this.localJobFile = new JobConf(nutchConf).getLocalFile(SUBDIR, jobid + ".xml");
fs.copyToLocalFile(new File(jobFile), localJobFile);
JobConf jd = new JobConf(localJobFile);
@@ -602,6 +607,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
if (jobFile.startsWith(systemDir.getPath())) {
this.deleteUponCompletion = jobFile;
}
+ this.nutchConf = nutchConf;
}
/**
@@ -613,7 +619,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
// construct input splits
JobConf jd = new JobConf(localJobFile);
- NutchFileSystem fs = NutchFileSystem.get();
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
FileSplit[] splits =
jd.getInputFormat().getSplits(fs, jd, numMapTasks);
@@ -634,6 +640,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
for (int i = 0; i < numMapTasks; i++) {
mapIds[i] = createMapTaskId();
Task t = new MapTask(jobFile, mapIds[i], splits[i]);
+ t.setConf(this.nutchConf);
incompleteMapTasks.put(mapIds[i], t);
taskToJobMap.put(mapIds[i], jobid);
@@ -643,6 +650,7 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
for (int i = 0; i < numReduceTasks; i++) {
String taskid = createReduceTaskId();
Task t = new ReduceTask(jobFile, taskid, mapIds, i);
+ t.setConf(this.nutchConf);
reducesToLaunch.add(t);
taskToJobMap.put(taskid, jobid);
}
@@ -1067,6 +1075,6 @@ public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmiss
System.exit(-1);
}
- startTracker(NutchConf.get());
+ startTracker(new NutchConf());
}
}
diff --git a/src/java/org/apache/nutch/mapred/LocalJobRunner.java b/src/java/org/apache/nutch/mapred/LocalJobRunner.java
index 98172a677..a3d806355 100644
--- a/src/java/org/apache/nutch/mapred/LocalJobRunner.java
+++ b/src/java/org/apache/nutch/mapred/LocalJobRunner.java
@@ -31,6 +31,7 @@ public class LocalJobRunner implements JobSubmissionProtocol {
private NutchFileSystem fs;
private HashMap jobs = new HashMap();
+ private NutchConf nutchConf;
private class Job extends Thread
implements TaskUmbilicalProtocol {
@@ -40,15 +41,19 @@ public class LocalJobRunner implements JobSubmissionProtocol {
private JobStatus status = new JobStatus();
private ArrayList mapIds = new ArrayList();
+ private MapOutputFile mapoutputFile;
- public Job(String file) throws IOException {
+ public Job(String file, NutchConf nutchConf) throws IOException {
this.file = file;
this.id = "job_" + newId();
+ this.mapoutputFile = new MapOutputFile();
+ this.mapoutputFile.setConf(nutchConf);
- File localFile = JobConf.getLocalFile("localRunner", id+".xml");
+ File localFile = new JobConf(nutchConf).getLocalFile("localRunner", id+".xml");
fs.copyToLocalFile(new File(file), localFile);
this.job = new JobConf(localFile);
-
+
+
this.status.jobid = id;
this.status.runState = JobStatus.RUNNING;
@@ -67,6 +72,7 @@ public class LocalJobRunner implements JobSubmissionProtocol {
for (int i = 0; i < splits.length; i++) {
mapIds.add("map_" + newId());
MapTask map = new MapTask(file, (String)mapIds.get(i), splits[i]);
+ map.setConf(job);
map.run(job, this);
}
@@ -74,12 +80,12 @@ public class LocalJobRunner implements JobSubmissionProtocol {
String reduceId = "reduce_" + newId();
for (int i = 0; i < mapIds.size(); i++) {
String mapId = (String)mapIds.get(i);
- File mapOut = MapOutputFile.getOutputFile(mapId, 0);
- File reduceIn = MapOutputFile.getInputFile(mapId, reduceId);
+ File mapOut = this.mapoutputFile.getOutputFile(mapId, 0);
+ File reduceIn = this.mapoutputFile.getInputFile(mapId, reduceId);
reduceIn.getParentFile().mkdirs();
- if (!NutchFileSystem.getNamed("local").rename(mapOut, reduceIn))
+ if (!NutchFileSystem.getNamed("local", this.job).rename(mapOut, reduceIn))
throw new IOException("Couldn't rename " + mapOut);
- MapOutputFile.removeAll(mapId);
+ this.mapoutputFile.removeAll(mapId);
}
// run a single reduce task
@@ -87,8 +93,9 @@ public class LocalJobRunner implements JobSubmissionProtocol {
new ReduceTask(file, reduceId,
(String[])mapIds.toArray(new String[0]),
0);
+ reduce.setConf(job);
reduce.run(job, this);
- MapOutputFile.removeAll(reduceId);
+ this.mapoutputFile.removeAll(reduceId);
this.status.runState = JobStatus.SUCCEEDED;
@@ -138,14 +145,15 @@ public class LocalJobRunner implements JobSubmissionProtocol {
}
- public LocalJobRunner() throws IOException {
- this.fs = NutchFileSystem.get();
+ public LocalJobRunner(NutchConf nutchConf) throws IOException {
+ this.fs = NutchFileSystem.get(nutchConf);
+ this.nutchConf = nutchConf;
}
// JobSubmissionProtocol methods
public JobStatus submitJob(String jobFile) throws IOException {
- return new Job(jobFile).status;
+ return new Job(jobFile, this.nutchConf).status;
}
public void killJob(String id) {
diff --git a/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java b/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java
index 82eb4cab0..37bce8e11 100644
--- a/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java
+++ b/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java
@@ -25,6 +25,7 @@ import org.apache.nutch.fs.NutchFileSystem;
import org.apache.nutch.io.MapFile;
import org.apache.nutch.io.WritableComparable;
import org.apache.nutch.io.Writable;
+import org.apache.nutch.util.NutchConf;
public class MapFileOutputFormat implements OutputFormat {
@@ -52,7 +53,7 @@ public class MapFileOutputFormat implements OutputFormat {
}
/** Open the output generated by this format. */
- public static MapFile.Reader[] getReaders(NutchFileSystem fs, File dir)
+ public static MapFile.Reader[] getReaders(NutchFileSystem fs, File dir, NutchConf nutchConf)
throws IOException {
File[] names = fs.listFiles(dir);
@@ -61,7 +62,7 @@ public class MapFileOutputFormat implements OutputFormat {
MapFile.Reader[] parts = new MapFile.Reader[names.length];
for (int i = 0; i < names.length; i++) {
- parts[i] = new MapFile.Reader(fs, names[i].toString());
+ parts[i] = new MapFile.Reader(fs, names[i].toString(), nutchConf);
}
return parts;
}
diff --git a/src/java/org/apache/nutch/mapred/MapOutputFile.java b/src/java/org/apache/nutch/mapred/MapOutputFile.java
index 91d0d04ab..4614593e9 100644
--- a/src/java/org/apache/nutch/mapred/MapOutputFile.java
+++ b/src/java/org/apache/nutch/mapred/MapOutputFile.java
@@ -24,19 +24,20 @@ import org.apache.nutch.fs.*;
import org.apache.nutch.util.*;
/** A local file to be transferred via the {@link MapOutputProtocol}. */
-public class MapOutputFile implements Writable {
+public class MapOutputFile implements Writable, NutchConfigurable {
private String mapTaskId;
private String reduceTaskId;
private int partition;
/** Permits reporting of file copy progress. */
- public static interface ProgressReporter {
+ public interface ProgressReporter {
void progress(float progress) throws IOException;
}
- private static final ThreadLocal REPORTERS = new ThreadLocal();
+ private ThreadLocal REPORTERS = new ThreadLocal();
+ private JobConf jobConf;
- public static void setProgressReporter(ProgressReporter reporter) {
+ public void setProgressReporter(ProgressReporter reporter) {
REPORTERS.set(reporter);
}
@@ -44,36 +45,37 @@ public class MapOutputFile implements Writable {
* @param mapTaskId a map task id
* @param partition a reduce partition
*/
- public static File getOutputFile(String mapTaskId, int partition)
+ public File getOutputFile(String mapTaskId, int partition)
throws IOException {
- return JobConf.getLocalFile(mapTaskId, "part-"+partition+".out");
+ return this.jobConf.getLocalFile(mapTaskId, "part-"+partition+".out");
}
/** Create a local reduce input file name.
* @param mapTaskId a map task id
* @param reduceTaskId a reduce task id
*/
- public static File getInputFile(String mapTaskId, String reduceTaskId)
+ public File getInputFile(String mapTaskId, String reduceTaskId)
throws IOException {
- return JobConf.getLocalFile(reduceTaskId, mapTaskId+".out");
+ return this.jobConf.getLocalFile(reduceTaskId, mapTaskId+".out");
}
/** Removes all of the files related to a task. */
- public static void removeAll(String taskId) throws IOException {
- JobConf.deleteLocalFiles(taskId);
+ public void removeAll(String taskId) throws IOException {
+ this.jobConf.deleteLocalFiles(taskId);
}
/**
* Removes all contents of temporary storage. Called upon
* startup, to remove any leftovers from previous run.
*/
- public static void cleanupStorage() throws IOException {
- JobConf.deleteLocalFiles();
+ public void cleanupStorage() throws IOException {
+ this.jobConf.deleteLocalFiles();
}
/** Construct a file for transfer. */
- public MapOutputFile() {
+ public MapOutputFile() {
}
+
public MapOutputFile(String mapTaskId, String reduceTaskId, int partition) {
this.mapTaskId = mapTaskId;
this.reduceTaskId = reduceTaskId;
@@ -88,7 +90,7 @@ public class MapOutputFile implements Writable {
// write the length-prefixed file content to the wire
File file = getOutputFile(mapTaskId, partition);
out.writeLong(file.length());
- NFSDataInputStream in = NutchFileSystem.getNamed("local").open(file);
+ NFSDataInputStream in = NutchFileSystem.getNamed("local", this.jobConf).open(file);
try {
byte[] buffer = new byte[8192];
int l;
@@ -112,7 +114,7 @@ public class MapOutputFile implements Writable {
long length = in.readLong();
float progPerByte = 1.0f / length;
long unread = length;
- NFSDataOutputStream out = NutchFileSystem.getNamed("local").create(file);
+ NFSDataOutputStream out = NutchFileSystem.getNamed("local", this.jobConf).create(file);
try {
byte[] buffer = new byte[8192];
while (unread > 0) {
@@ -129,4 +131,12 @@ public class MapOutputFile implements Writable {
}
}
+ public void setConf(NutchConf conf) {
+ this.jobConf = new JobConf(conf);
+ }
+
+ public NutchConf getConf() {
+ return this.jobConf;
+ }
+
}
diff --git a/src/java/org/apache/nutch/mapred/MapTask.java b/src/java/org/apache/nutch/mapred/MapTask.java
index 95cfe6d37..7a32288ac 100644
--- a/src/java/org/apache/nutch/mapred/MapTask.java
+++ b/src/java/org/apache/nutch/mapred/MapTask.java
@@ -27,6 +27,8 @@ import org.apache.nutch.fs.NutchFileSystem;
/** A Map task. */
public class MapTask extends Task {
private FileSplit split;
+ private MapOutputFile mapOutputFile;
+ private NutchConf nutchConf;
public MapTask() {}
@@ -36,7 +38,7 @@ public class MapTask extends Task {
}
public TaskRunner createRunner(TaskTracker tracker) {
- return new MapTaskRunner(this, tracker);
+ return new MapTaskRunner(this, tracker, this.nutchConf);
}
public FileSplit getSplit() { return split; }
@@ -62,8 +64,8 @@ public class MapTask extends Task {
try {
for (int i = 0; i < partitions; i++) {
outs[i] =
- new SequenceFile.Writer(NutchFileSystem.getNamed("local"),
- MapOutputFile.getOutputFile(getTaskId(), i).toString(),
+ new SequenceFile.Writer(NutchFileSystem.getNamed("local", job),
+ this.mapOutputFile.getOutputFile(getTaskId(), i).toString(),
job.getOutputKeyClass(),
job.getOutputValueClass());
}
@@ -91,7 +93,7 @@ public class MapTask extends Task {
final RecordReader rawIn = // open input
job.getInputFormat().getRecordReader
- (NutchFileSystem.get(), split, job, reporter);
+ (NutchFileSystem.get(job), split, job, reporter);
RecordReader in = new RecordReader() { // wrap in progress reporter
private float perByte = 1.0f /(float)split.getLength();
@@ -131,5 +133,15 @@ public class MapTask extends Task {
}
done(umbilical);
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.mapOutputFile = new MapOutputFile();
+ this.mapOutputFile.setConf(conf);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/java/org/apache/nutch/mapred/MapTaskRunner.java b/src/java/org/apache/nutch/mapred/MapTaskRunner.java
index 48233789e..9fe398f77 100644
--- a/src/java/org/apache/nutch/mapred/MapTaskRunner.java
+++ b/src/java/org/apache/nutch/mapred/MapTaskRunner.java
@@ -26,17 +26,22 @@ import java.util.logging.*;
/** Runs a map task. */
class MapTaskRunner extends TaskRunner {
- public MapTaskRunner(Task task, TaskTracker tracker) {
- super(task, tracker);
+ private MapOutputFile mapOutputFile;
+
+ public MapTaskRunner(Task task, TaskTracker tracker, NutchConf nutchConf) {
+ super(task, tracker, nutchConf);
+ this.mapOutputFile = new MapOutputFile();
+ this.mapOutputFile.setConf(nutchConf);
}
+
/** Delete any temporary files from previous failed attempts. */
public void prepare() throws IOException {
- MapOutputFile.removeAll(getTask().getTaskId());
+ this.mapOutputFile.removeAll(getTask().getTaskId());
}
/** Delete all of the temporary map output files. */
public void close() throws IOException {
LOG.info(getTask()+" done; removing files.");
- MapOutputFile.removeAll(getTask().getTaskId());
+ this.mapOutputFile.removeAll(getTask().getTaskId());
}
}
diff --git a/src/java/org/apache/nutch/mapred/ReduceTask.java b/src/java/org/apache/nutch/mapred/ReduceTask.java
index 361a41c2c..75a971a4b 100644
--- a/src/java/org/apache/nutch/mapred/ReduceTask.java
+++ b/src/java/org/apache/nutch/mapred/ReduceTask.java
@@ -37,6 +37,8 @@ public class ReduceTask extends Task {
private Progress appendPhase = getProgress().addPhase("append");
private Progress sortPhase = getProgress().addPhase("sort");
private Progress reducePhase = getProgress().addPhase("reduce");
+ private NutchConf nutchConf;
+ private MapOutputFile mapOutputFile;
public ReduceTask() {}
@@ -48,7 +50,7 @@ public class ReduceTask extends Task {
}
public TaskRunner createRunner(TaskTracker tracker) {
- return new ReduceTaskRunner(this, tracker);
+ return new ReduceTaskRunner(this, tracker, this.nutchConf);
}
public String[] getMapTaskIds() { return mapTaskIds; }
@@ -157,7 +159,8 @@ public class ReduceTask extends Task {
Class keyClass = job.getOutputKeyClass();
Class valueClass = job.getOutputValueClass();
Reducer reducer = (Reducer)job.newInstance(job.getReducerClass());
- NutchFileSystem lfs = NutchFileSystem.getNamed("local");
+ reducer.configure(job);
+ NutchFileSystem lfs = NutchFileSystem.getNamed("local", job);
copyPhase.complete(); // copy is already complete
@@ -175,12 +178,12 @@ public class ReduceTask extends Task {
for (int i = 0; i < mapTaskIds.length; i++) {
File partFile =
- MapOutputFile.getInputFile(mapTaskIds[i], getTaskId());
+ this.mapOutputFile.getInputFile(mapTaskIds[i], getTaskId());
float progPerByte = 1.0f / lfs.getLength(partFile);
Progress phase = appendPhase.phase();
phase.setStatus(partFile.toString());
SequenceFile.Reader in =
- new SequenceFile.Reader(lfs, partFile.toString());
+ new SequenceFile.Reader(lfs, partFile.toString(), job);
try {
int keyLen;
while((keyLen = in.next(buffer)) > 0) {
@@ -227,7 +230,7 @@ public class ReduceTask extends Task {
// sort the input file
SequenceFile.Sorter sorter =
- new SequenceFile.Sorter(lfs, comparator, valueClass);
+ new SequenceFile.Sorter(lfs, comparator, valueClass, job);
sorter.sort(file, sortedFile); // sort
lfs.delete(new File(file)); // remove unsorted
@@ -240,7 +243,7 @@ public class ReduceTask extends Task {
// make output collector
String name = getOutputName(getPartition());
final RecordWriter out =
- job.getOutputFormat().getRecordWriter(NutchFileSystem.get(), job, name);
+ job.getOutputFormat().getRecordWriter(NutchFileSystem.get(job), job, name);
OutputCollector collector = new OutputCollector() {
public void collect(WritableComparable key, Writable value)
throws IOException {
@@ -250,7 +253,7 @@ public class ReduceTask extends Task {
};
// apply reduce function
- SequenceFile.Reader in = new SequenceFile.Reader(lfs, sortedFile);
+ SequenceFile.Reader in = new SequenceFile.Reader(lfs, sortedFile, job);
Reporter reporter = getReporter(umbilical, getProgress());
long length = lfs.getLength(new File(sortedFile));
try {
@@ -266,7 +269,6 @@ public class ReduceTask extends Task {
lfs.delete(new File(sortedFile)); // remove sorted
out.close(reporter);
}
-
done(umbilical);
}
@@ -284,4 +286,14 @@ public class ReduceTask extends Task {
return "part-" + NUMBER_FORMAT.format(partition);
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.mapOutputFile = new MapOutputFile();
+ this.mapOutputFile.setConf(conf);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java b/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java
index c10c69bbc..40cc1fd15 100644
--- a/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java
+++ b/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java
@@ -28,15 +28,18 @@ import java.util.logging.*;
class ReduceTaskRunner extends TaskRunner {
private static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.mapred.ReduceTaskRunner");
+ private MapOutputFile mapOutputFile;
- public ReduceTaskRunner(Task task, TaskTracker tracker) {
- super(task, tracker);
+ public ReduceTaskRunner(Task task, TaskTracker tracker, NutchConf nutchConf) {
+ super(task, tracker, nutchConf);
+ this.mapOutputFile = new MapOutputFile();
+ this.mapOutputFile.setConf(nutchConf);
}
/** Assemble all of the map output files. */
public void prepare() throws IOException {
ReduceTask task = ((ReduceTask)getTask());
- MapOutputFile.removeAll(task.getTaskId()); // cleanup from failures
+ this.mapOutputFile.removeAll(task.getTaskId()); // cleanup from failures
String[] mapTaskIds = task.getMapTaskIds();
final Progress copyPhase = getTask().getProgress().phase();
@@ -74,9 +77,9 @@ class ReduceTaskRunner extends TaskRunner {
InetSocketAddress addr =
new InetSocketAddress(loc.getHost(), loc.getPort());
MapOutputProtocol client =
- (MapOutputProtocol)RPC.getProxy(MapOutputProtocol.class, addr);
+ (MapOutputProtocol)RPC.getProxy(MapOutputProtocol.class, addr, this.nutchConf);
- MapOutputFile.setProgressReporter(new MapOutputFile.ProgressReporter(){
+ this.mapOutputFile.setProgressReporter(new MapOutputFile.ProgressReporter() {
public void progress(float progress) {
copyPhase.phase().set(progress);
try {
@@ -104,7 +107,7 @@ class ReduceTaskRunner extends TaskRunner {
+loc.getMapTaskId()+" from "+addr,
e);
} finally {
- MapOutputFile.setProgressReporter(null);
+ this.mapOutputFile.setProgressReporter(null);
}
}
@@ -116,7 +119,7 @@ class ReduceTaskRunner extends TaskRunner {
/** Delete all of the temporary map output files. */
public void close() throws IOException {
getTask().getProgress().setStatus("closed");
- MapOutputFile.removeAll(getTask().getTaskId());
+ this.mapOutputFile.removeAll(getTask().getTaskId());
}
}
diff --git a/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java b/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java
index bfa284bec..a5191a83d 100644
--- a/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java
+++ b/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java
@@ -54,7 +54,7 @@ public class SequenceFileInputFormat extends InputFormatBase {
reporter.setStatus(split.toString());
- return new SequenceFileRecordReader(fs, split);
+ return new SequenceFileRecordReader(job, split);
}
}
diff --git a/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.java b/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.java
index dfde84ad7..506a4b1a1 100644
--- a/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.java
+++ b/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.java
@@ -26,6 +26,7 @@ import org.apache.nutch.io.MapFile;
import org.apache.nutch.io.SequenceFile;
import org.apache.nutch.io.WritableComparable;
import org.apache.nutch.io.Writable;
+import org.apache.nutch.util.NutchConf;
public class SequenceFileOutputFormat implements OutputFormat {
@@ -53,8 +54,9 @@ public class SequenceFileOutputFormat implements OutputFormat {
}
/** Open the output generated by this format. */
- public static SequenceFile.Reader[] getReaders(NutchFileSystem fs, File dir)
+ public static SequenceFile.Reader[] getReaders(NutchConf nutchConf, File dir)
throws IOException {
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
File[] names = fs.listFiles(dir);
// sort names, so that hash partitioning works
@@ -62,7 +64,7 @@ public class SequenceFileOutputFormat implements OutputFormat {
SequenceFile.Reader[] parts = new SequenceFile.Reader[names.length];
for (int i = 0; i < names.length; i++) {
- parts[i] = new SequenceFile.Reader(fs, names[i].toString());
+ parts[i] = new SequenceFile.Reader(fs, names[i].toString(), nutchConf);
}
return parts;
}
diff --git a/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java b/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java
index 24982709f..b31099401 100644
--- a/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java
+++ b/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java
@@ -26,6 +26,7 @@ import org.apache.nutch.io.Writable;
import org.apache.nutch.io.WritableComparable;
import org.apache.nutch.io.LongWritable;
import org.apache.nutch.io.UTF8;
+import org.apache.nutch.util.NutchConf;
/** An {@link RecordReader} for {@link SequenceFile}s. */
public class SequenceFileRecordReader implements RecordReader {
@@ -33,9 +34,10 @@ public class SequenceFileRecordReader implements RecordReader {
private long end;
private boolean more = true;
- public SequenceFileRecordReader(NutchFileSystem fs, FileSplit split)
+ public SequenceFileRecordReader(NutchConf nutchConf, FileSplit split)
throws IOException {
- this.in = new SequenceFile.Reader(fs, split.getFile().toString());
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
+ this.in = new SequenceFile.Reader(fs, split.getFile().toString(), nutchConf);
this.end = split.getStart() + split.getLength();
if (split.getStart() > in.getPosition())
diff --git a/src/java/org/apache/nutch/mapred/Task.java b/src/java/org/apache/nutch/mapred/Task.java
index 5619b3374..d506a8d40 100644
--- a/src/java/org/apache/nutch/mapred/Task.java
+++ b/src/java/org/apache/nutch/mapred/Task.java
@@ -24,14 +24,13 @@ import java.net.*;
import java.util.*;
/** Base class for tasks. */
-public abstract class Task implements Writable {
+public abstract class Task implements Writable, NutchConfigurable {
////////////////////////////////////////////
// Fields
////////////////////////////////////////////
private String jobFile; // job configuration file
private String taskId; // unique, includes job id
-
////////////////////////////////////////////
// Constructors
////////////////////////////////////////////
diff --git a/src/java/org/apache/nutch/mapred/TaskRunner.java b/src/java/org/apache/nutch/mapred/TaskRunner.java
index 79f601545..fd95bef70 100644
--- a/src/java/org/apache/nutch/mapred/TaskRunner.java
+++ b/src/java/org/apache/nutch/mapred/TaskRunner.java
@@ -37,9 +37,12 @@ abstract class TaskRunner extends Thread {
private Task t;
private TaskTracker tracker;
- public TaskRunner(Task t, TaskTracker tracker) {
+ protected NutchConf nutchConf;
+
+ public TaskRunner(Task t, TaskTracker tracker, NutchConf nutchConf) {
this.t = t;
this.tracker = tracker;
+ this.nutchConf = nutchConf;
}
public Task getTask() { return t; }
diff --git a/src/java/org/apache/nutch/mapred/TaskTracker.java b/src/java/org/apache/nutch/mapred/TaskTracker.java
index 86f8314a5..9092e9b28 100644
--- a/src/java/org/apache/nutch/mapred/TaskTracker.java
+++ b/src/java/org/apache/nutch/mapred/TaskTracker.java
@@ -33,13 +33,9 @@ import java.util.logging.*;
* @author Mike Cafarella
*******************************************************/
public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutputProtocol, Runnable {
- private static final int MAX_CURRENT_TASKS =
- NutchConf.get().getInt("mapred.tasktracker.tasks.maximum", 2);
-
+ private int maxCurrentTask;
static final long WAIT_FOR_DONE = 3 * 1000;
-
- static final long TASK_TIMEOUT =
- NutchConf.get().getInt("mapred.task.timeout", 10* 60 * 1000);
+ private long taskTimeout;
static final int STALE_STATE = 1;
@@ -68,6 +64,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
static final String SUBDIR = "taskTracker";
private NutchConf fConf;
+ private MapOutputFile mapOutputFile;
/**
* Start with the local machine name, and the default JobTracker
@@ -82,6 +79,10 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
public TaskTracker(InetSocketAddress jobTrackAddr, NutchConf conf) throws IOException {
this.fConf = conf;
this.jobTrackAddr = jobTrackAddr;
+ this.maxCurrentTask = conf.getInt("mapred.tasktracker.tasks.maximum", 2);
+ this.taskTimeout = conf.getInt("mapred.task.timeout", 10* 60 * 1000);
+ this.mapOutputFile = new MapOutputFile();
+ this.mapOutputFile.setConf(conf);
initialize();
}
@@ -94,7 +95,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
this.taskTrackerName = "tracker_" + (Math.abs(r.nextInt()) % 100000);
this.localHostname = InetAddress.getLocalHost().getHostName();
- JobConf.deleteLocalFiles(SUBDIR);
+ new JobConf(this.fConf).deleteLocalFiles(SUBDIR);
// Clear out state tables
this.tasks = new TreeMap();
@@ -107,7 +108,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
// RPC initialization
while (true) {
try {
- this.taskReportServer = RPC.getServer(this, this.taskReportPort, MAX_CURRENT_TASKS, false);
+ this.taskReportServer = RPC.getServer(this, this.taskReportPort, this.maxCurrentTask, false, this.fConf);
this.taskReportServer.start();
break;
} catch (BindException e) {
@@ -118,7 +119,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
}
while (true) {
try {
- this.mapOutputServer = RPC.getServer(this, this.mapOutputPort, MAX_CURRENT_TASKS, false);
+ this.mapOutputServer = RPC.getServer(this, this.mapOutputPort, this.maxCurrentTask, false, this.fConf);
this.mapOutputServer.start();
break;
} catch (BindException e) {
@@ -128,10 +129,10 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
}
// Clear out temporary files that might be lying around
- MapOutputFile.cleanupStorage();
+ this.mapOutputFile.cleanupStorage();
this.justStarted = true;
- this.jobClient = (InterTrackerProtocol) RPC.getProxy(InterTrackerProtocol.class, jobTrackAddr);
+ this.jobClient = (InterTrackerProtocol) RPC.getProxy(InterTrackerProtocol.class, jobTrackAddr, this.fConf);
}
/**
@@ -164,7 +165,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
}
// Clear local storage
- MapOutputFile.cleanupStorage();
+ this.mapOutputFile.cleanupStorage();
}
/**
@@ -213,7 +214,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
// Xmit the heartbeat
//
if (justStarted) {
- this.fs = NutchFileSystem.getNamed(jobClient.getFilesystemName());
+ this.fs = NutchFileSystem.getNamed(jobClient.getFilesystemName(), this.fConf);
}
int resultCode = jobClient.emitHeartbeat(new TaskTrackerStatus(taskTrackerName, localHostname, mapOutputPort, taskReports), justStarted);
@@ -226,10 +227,10 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
//
// Check if we should create a new Task
//
- if (runningTasks.size() < MAX_CURRENT_TASKS) {
+ if (runningTasks.size() < this.maxCurrentTask) {
Task t = jobClient.pollForNewTask(taskTrackerName);
if (t != null) {
- TaskInProgress tip = new TaskInProgress(t);
+ TaskInProgress tip = new TaskInProgress(t, this.fConf);
synchronized (this) {
tasks.put(t.getTaskId(), tip);
runningTasks.put(t.getTaskId(), tip);
@@ -245,7 +246,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
for (Iterator it = runningTasks.values().iterator(); it.hasNext(); ) {
TaskInProgress tip = (TaskInProgress) it.next();
if ((tip.getRunState() == TaskStatus.RUNNING) &&
- (System.currentTimeMillis() - tip.getLastProgressReport() > TASK_TIMEOUT)) {
+ (System.currentTimeMillis() - tip.getLastProgressReport() > this.taskTimeout)) {
LOG.info("Task " + tip.getTask().getTaskId() + " timed out. Killing.");
tip.reportDiagnosticInfo("Timed out.");
tip.killAndCleanup();
@@ -321,13 +322,15 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
TaskRunner runner;
boolean done = false;
boolean wasKilled = false;
+ private JobConf jobConf;
/**
*/
- public TaskInProgress(Task task) throws IOException {
+ public TaskInProgress(Task task, NutchConf nutchConf) throws IOException {
this.task = task;
this.lastProgressReport = System.currentTimeMillis();
- JobConf.deleteLocalFiles(SUBDIR+File.separator+task.getTaskId());
+ this.jobConf = new JobConf(nutchConf);
+ this.jobConf.deleteLocalFiles(SUBDIR + File.separator + task.getTaskId());
localizeTask(task);
}
@@ -337,9 +340,9 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
*/
void localizeTask(Task t) throws IOException {
File localJobFile =
- JobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.xml");
+ this.jobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.xml");
File localJarFile =
- JobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.jar");
+ this.jobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.jar");
String jobFile = t.getJobFile();
fs.copyToLocalFile(new File(jobFile), localJobFile);
@@ -501,7 +504,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
runner.close();
} catch (IOException ie) {
}
- JobConf.deleteLocalFiles(SUBDIR+File.separator+task.getTaskId());
+ this.jobConf.deleteLocalFiles(SUBDIR + File.separator + task.getTaskId());
}
}
@@ -509,11 +512,14 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
// MapOutputProtocol
/////////////////////////////////////////////////////////////////
public MapOutputFile getFile(String mapTaskId, String reduceTaskId,
- IntWritable partition) {
- return new MapOutputFile(mapTaskId, reduceTaskId, partition.get());
- }
-
- /////////////////////////////////////////////////////////////////
+ IntWritable partition) {
+ MapOutputFile mapOutputFile = new MapOutputFile(mapTaskId, reduceTaskId,
+ partition.get());
+ mapOutputFile.setConf(this.fConf);
+ return mapOutputFile;
+ }
+
+ // ///////////////////////////////////////////////////////////////
// TaskUmbilicalProtocol
/////////////////////////////////////////////////////////////////
/**
@@ -586,16 +592,17 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
LogFormatter.showTime(false);
LOG.info("Child starting");
+ NutchConf nutchConf = new NutchConf();
int port = Integer.parseInt(args[0]);
String taskid = args[1];
TaskUmbilicalProtocol umbilical =
(TaskUmbilicalProtocol)RPC.getProxy(TaskUmbilicalProtocol.class,
- new InetSocketAddress(port));
+ new InetSocketAddress(port), nutchConf);
Task task = umbilical.getTask(taskid);
JobConf job = new JobConf(task.getJobFile());
- NutchConf.get().addConfResource(new File(task.getJobFile()));
+ nutchConf.addConfResource(new File(task.getJobFile()));
startPinging(umbilical, taskid); // start pinging parent
@@ -646,7 +653,7 @@ public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutpu
System.exit(-1);
}
- TaskTracker tt = new TaskTracker(NutchConf.get());
+ TaskTracker tt = new TaskTracker(new NutchConf());
tt.run();
}
}
diff --git a/src/java/org/apache/nutch/mapred/demo/Grep.java b/src/java/org/apache/nutch/mapred/demo/Grep.java
index 927088515..8a7885c9a 100644
--- a/src/java/org/apache/nutch/mapred/demo/Grep.java
+++ b/src/java/org/apache/nutch/mapred/demo/Grep.java
@@ -45,7 +45,7 @@ public class Grep {
System.exit(-1);
}
- NutchConf defaults = NutchConf.get();
+ NutchConf defaults = new NutchConf();
File tempDir =
new File("grep-temp-"+
diff --git a/src/java/org/apache/nutch/ndfs/DataNode.java b/src/java/org/apache/nutch/ndfs/DataNode.java
index a4cdffddd..329b45818 100644
--- a/src/java/org/apache/nutch/ndfs/DataNode.java
+++ b/src/java/org/apache/nutch/ndfs/DataNode.java
@@ -85,8 +85,8 @@ public class DataNode implements FSConstants, Runnable {
* Needs a directory to find its data (and config info)
*/
public DataNode(String machineName, File datadir, InetSocketAddress nameNodeAddr, NutchConf conf) throws IOException {
- this.namenode = (DatanodeProtocol) RPC.getProxy(DatanodeProtocol.class, nameNodeAddr);
- this.data = new FSDataset(datadir);
+ this.namenode = (DatanodeProtocol) RPC.getProxy(DatanodeProtocol.class, nameNodeAddr, conf);
+ this.data = new FSDataset(datadir, conf);
ServerSocket ss = null;
int tmpPort = conf.getInt("ndfs.datanode.port", 50010);
@@ -748,6 +748,6 @@ public class DataNode implements FSConstants, Runnable {
*/
public static void main(String args[]) throws IOException {
LogFormatter.setShowThreadIDs(true);
- runAndWait(NutchConf.get());
+ runAndWait(new NutchConf());
}
}
diff --git a/src/java/org/apache/nutch/ndfs/FSConstants.java b/src/java/org/apache/nutch/ndfs/FSConstants.java
index 15b186b32..bf2ae6eeb 100644
--- a/src/java/org/apache/nutch/ndfs/FSConstants.java
+++ b/src/java/org/apache/nutch/ndfs/FSConstants.java
@@ -107,8 +107,8 @@ public interface FSConstants {
public static long LEASE_PERIOD = 60 * 1000;
public static int READ_TIMEOUT = 60 * 1000;
- public static int BUFFER_SIZE =
- NutchConf.get().getInt("io.file.buffer.size", 4096);
+ //TODO [email protected]: should be nutchConf injected?
+ public static final int BUFFER_SIZE = new NutchConf().getInt("io.file.buffer.size", 4096);
}
diff --git a/src/java/org/apache/nutch/ndfs/FSDataset.java b/src/java/org/apache/nutch/ndfs/FSDataset.java
index 6e043e281..706bbcc01 100644
--- a/src/java/org/apache/nutch/ndfs/FSDataset.java
+++ b/src/java/org/apache/nutch/ndfs/FSDataset.java
@@ -191,7 +191,7 @@ public class FSDataset implements FSConstants {
/**
* An FSDataset has a directory where it loads its data files.
*/
- public FSDataset(File dir) throws IOException {
+ public FSDataset(File dir, NutchConf nutchConf) throws IOException {
this.dirpath = dir.getCanonicalPath();
this.data = new File(dir, "data");
if (! data.exists()) {
@@ -199,7 +199,7 @@ public class FSDataset implements FSConstants {
}
this.tmp = new File(dir, "tmp");
if (tmp.exists()) {
- FileUtil.fullyDelete(tmp);
+ FileUtil.fullyDelete(tmp, nutchConf);
}
this.tmp.mkdirs();
this.dirTree = new FSDir(data);
diff --git a/src/java/org/apache/nutch/ndfs/FSNamesystem.java b/src/java/org/apache/nutch/ndfs/FSNamesystem.java
index 0f233c458..3d934f618 100644
--- a/src/java/org/apache/nutch/ndfs/FSNamesystem.java
+++ b/src/java/org/apache/nutch/ndfs/FSNamesystem.java
@@ -34,27 +34,7 @@ import java.util.logging.*;
public class FSNamesystem implements FSConstants {
public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.fs.FSNamesystem");
- // DESIRED_REPLICATION is how many copies we try to have at all times
- final static int DESIRED_REPLICATION =
- NutchConf.get().getInt("ndfs.replication", 3);
-
- // The maximum number of replicates we should allow for a single block
- final static int MAX_REPLICATION = DESIRED_REPLICATION;
-
- // How many outgoing replication streams a given node should have at one time
- final static int MAX_REPLICATION_STREAMS = NutchConf.get().getInt("ndfs.max-repl-streams", 2);
-
- // MIN_REPLICATION is how many copies we need in place or else we disallow the write
- final static int MIN_REPLICATION = 1;
-
- // HEARTBEAT_RECHECK is how often a datanode sends its hearbeat
- final static long HEARTBEAT_RECHECK = 1000;
-
- // Whether we should use disk-availability info when determining target
- final static boolean USE_AVAILABILITY = NutchConf.get().getBoolean("ndfs.availability.allocation", false);
-
- private boolean allowSameHostTargets =
- NutchConf.get().getBoolean("test.ndfs.same.host.targets.allowed", false);
+
//
// Stores the correct file name hierarchy
@@ -148,18 +128,44 @@ public class FSNamesystem implements FSConstants {
Daemon hbthread = null, lmthread = null;
boolean fsRunning = true;
long systemStart = 0;
+ private NutchConf nutchConf;
+
+ // DESIRED_REPLICATION is how many copies we try to have at all times
+ private int desiredReplication;
+ // The maximum number of replicates we should allow for a single block
+ private int maxReplication;
+ // How many outgoing replication streams a given node should have at one time
+ private int maxReplicationStreams;
+ // MIN_REPLICATION is how many copies we need in place or else we disallow the write
+ private int minReplication;
+ // HEARTBEAT_RECHECK is how often a datanode sends its hearbeat
+ private int heartBeatRecheck;
+ // Whether we should use disk-availability info when determining target
+ private boolean useAvailability;
+
+ private boolean allowSameHostTargets;
/**
* dir is where the filesystem directory state
* is stored
*/
- public FSNamesystem(File dir) throws IOException {
+ public FSNamesystem(File dir, NutchConf nutchConf) throws IOException {
this.dir = new FSDirectory(dir);
this.hbthread = new Daemon(new HeartbeatMonitor());
this.lmthread = new Daemon(new LeaseMonitor());
hbthread.start();
lmthread.start();
this.systemStart = System.currentTimeMillis();
+ this.nutchConf = nutchConf;
+
+ this.desiredReplication = nutchConf.getInt("ndfs.replication", 3);
+ this.maxReplication = desiredReplication;
+ this.maxReplicationStreams = nutchConf.getInt("ndfs.max-repl-streams", 2);
+ this.minReplication = 1;
+ this.heartBeatRecheck= 1000;
+ this.useAvailability = nutchConf.getBoolean("ndfs.availability.allocation", false);
+ this.allowSameHostTargets =
+ nutchConf.getBoolean("test.ndfs.same.host.targets.allowed", false);
}
/** Close down this filesystem manager.
@@ -244,10 +250,10 @@ public class FSNamesystem implements FSConstants {
results = new Object[2];
// Get the array of replication targets
- DatanodeInfo targets[] = chooseTargets(DESIRED_REPLICATION, null);
- if (targets.length < MIN_REPLICATION) {
+ DatanodeInfo targets[] = chooseTargets(this.desiredReplication, null);
+ if (targets.length < this.minReplication) {
LOG.warning("Target-length is " + targets.length +
- ", below MIN_REPLICATION (" + MIN_REPLICATION + ")");
+ ", below MIN_REPLICATION (" + this.minReplication+ ")");
return null;
}
@@ -300,8 +306,8 @@ public class FSNamesystem implements FSConstants {
//
if (checkFileProgress(src)) {
// Get the array of replication targets
- DatanodeInfo targets[] = chooseTargets(DESIRED_REPLICATION, null);
- if (targets.length < MIN_REPLICATION) {
+ DatanodeInfo targets[] = chooseTargets(this.desiredReplication, null);
+ if (targets.length < this.minReplication) {
return null;
}
@@ -411,9 +417,9 @@ public class FSNamesystem implements FSConstants {
// the blocks.
for (int i = 0; i < pendingBlocks.length; i++) {
TreeSet containingNodes = (TreeSet) blocksMap.get(pendingBlocks[i]);
- if (containingNodes.size() < DESIRED_REPLICATION) {
+ if (containingNodes.size() < this.desiredReplication) {
synchronized (neededReplications) {
- LOG.info("Completed file " + src + ", at holder " + holder + ". There is/are only " + containingNodes.size() + " copies of block " + pendingBlocks[i] + ", so replicating up to " + DESIRED_REPLICATION);
+ LOG.info("Completed file " + src + ", at holder " + holder + ". There is/are only " + containingNodes.size() + " copies of block " + pendingBlocks[i] + ", so replicating up to " + this.desiredReplication);
neededReplications.add(pendingBlocks[i]);
}
}
@@ -449,7 +455,7 @@ public class FSNamesystem implements FSConstants {
for (Iterator it = v.iterator(); it.hasNext(); ) {
Block b = (Block) it.next();
TreeSet containingNodes = (TreeSet) blocksMap.get(b);
- if (containingNodes == null || containingNodes.size() < MIN_REPLICATION) {
+ if (containingNodes == null || containingNodes.size() < this.minReplication) {
return false;
}
}
@@ -814,7 +820,7 @@ public class FSNamesystem implements FSConstants {
while (fsRunning) {
heartbeatCheck();
try {
- Thread.sleep(HEARTBEAT_RECHECK);
+ Thread.sleep(heartBeatRecheck);
} catch (InterruptedException ie) {
}
}
@@ -946,10 +952,10 @@ public class FSNamesystem implements FSConstants {
synchronized (neededReplications) {
if (dir.isValidBlock(block)) {
- if (containingNodes.size() >= DESIRED_REPLICATION) {
+ if (containingNodes.size() >= this.desiredReplication) {
neededReplications.remove(block);
pendingReplications.remove(block);
- } else if (containingNodes.size() < DESIRED_REPLICATION) {
+ } else if (containingNodes.size() < this.desiredReplication) {
if (! neededReplications.contains(block)) {
neededReplications.add(block);
}
@@ -968,8 +974,8 @@ public class FSNamesystem implements FSConstants {
nonExcess.add(cur);
}
}
- if (nonExcess.size() > MAX_REPLICATION) {
- chooseExcessReplicates(nonExcess, block, MAX_REPLICATION);
+ if (nonExcess.size() > this.maxReplication) {
+ chooseExcessReplicates(nonExcess, block, this.maxReplication);
}
}
}
@@ -1032,7 +1038,7 @@ public class FSNamesystem implements FSConstants {
// necessary. In that case, put block on a possibly-will-
// be-replicated list.
//
- if (dir.isValidBlock(block) && (containingNodes.size() < DESIRED_REPLICATION)) {
+ if (dir.isValidBlock(block) && (containingNodes.size() < this.desiredReplication)) {
synchronized (neededReplications) {
neededReplications.add(block);
}
@@ -1147,7 +1153,7 @@ public class FSNamesystem implements FSConstants {
//
// We can only reply with 'maxXfers' or fewer blocks
//
- if (scheduledXfers >= MAX_REPLICATION_STREAMS - xmitsInProgress) {
+ if (scheduledXfers >= this.maxReplicationStreams - xmitsInProgress) {
break;
}
@@ -1157,7 +1163,7 @@ public class FSNamesystem implements FSConstants {
} else {
TreeSet containingNodes = (TreeSet) blocksMap.get(block);
if (containingNodes.contains(srcNode)) {
- DatanodeInfo targets[] = chooseTargets(Math.min(DESIRED_REPLICATION - containingNodes.size(), MAX_REPLICATION_STREAMS - xmitsInProgress), containingNodes);
+ DatanodeInfo targets[] = chooseTargets(Math.min(this.desiredReplication - containingNodes.size(), this.maxReplicationStreams - xmitsInProgress), containingNodes);
if (targets.length > 0) {
// Build items to return
replicateBlocks.add(block);
@@ -1181,7 +1187,7 @@ public class FSNamesystem implements FSConstants {
DatanodeInfo targets[] = (DatanodeInfo[]) replicateTargetSets.elementAt(i);
TreeSet containingNodes = (TreeSet) blocksMap.get(block);
- if (containingNodes.size() + targets.length >= DESIRED_REPLICATION) {
+ if (containingNodes.size() + targets.length >= this.desiredReplication) {
neededReplications.remove(block);
pendingReplications.add(block);
}
@@ -1313,7 +1319,7 @@ public class FSNamesystem implements FSConstants {
" forbidden2.size()=" +
( forbidden2 != null ? forbidden2.size() : 0 ));
return null;
- } else if (! USE_AVAILABILITY) {
+ } else if (! this.useAvailability) {
int target = r.nextInt(targetList.size());
return (DatanodeInfo) targetList.elementAt(target);
} else {
diff --git a/src/java/org/apache/nutch/ndfs/NDFSClient.java b/src/java/org/apache/nutch/ndfs/NDFSClient.java
index 670aa13c7..796708ce0 100644
--- a/src/java/org/apache/nutch/ndfs/NDFSClient.java
+++ b/src/java/org/apache/nutch/ndfs/NDFSClient.java
@@ -42,8 +42,8 @@ public class NDFSClient implements FSConstants {
/** Create a new NDFSClient connected to the given namenode server.
*/
- public NDFSClient(InetSocketAddress nameNodeAddr) {
- this.namenode = (ClientProtocol) RPC.getProxy(ClientProtocol.class, nameNodeAddr);
+ public NDFSClient(InetSocketAddress nameNodeAddr, NutchConf nutchConf) {
+ this.namenode = (ClientProtocol) RPC.getProxy(ClientProtocol.class, nameNodeAddr, nutchConf);
this.clientName = "NDFSClient_" + r.nextInt();
this.leaseChecker = new Daemon(new LeaseChecker());
this.leaseChecker.start();
diff --git a/src/java/org/apache/nutch/ndfs/NameNode.java b/src/java/org/apache/nutch/ndfs/NameNode.java
index a687985bf..497bc4ecb 100644
--- a/src/java/org/apache/nutch/ndfs/NameNode.java
+++ b/src/java/org/apache/nutch/ndfs/NameNode.java
@@ -48,21 +48,20 @@ public class NameNode implements ClientProtocol, DatanodeProtocol, FSConstants {
/**
* Create a NameNode at the default location
*/
- public NameNode() throws IOException {
- this(new File(NutchConf.get().get("ndfs.name.dir",
+ public NameNode(NutchConf nutchConf) throws IOException {
+ this(new File(nutchConf.get("ndfs.name.dir",
"/tmp/nutch/ndfs/name")),
DataNode.createSocketAddr
- (NutchConf.get().get("fs.default.name", "local")).getPort());
+ (nutchConf.get("fs.default.name", "local")).getPort(), nutchConf);
}
/**
* Create a NameNode at the specified location and start it.
*/
- public NameNode(File dir, int port) throws IOException {
- this.namesystem = new FSNamesystem(dir);
- this.handlerCount =
- NutchConf.get().getInt("ndfs.namenode.handler.count", 10);
- this.server = RPC.getServer(this, port, handlerCount, false);
+ public NameNode(File dir, int port, NutchConf nutchConf) throws IOException {
+ this.namesystem = new FSNamesystem(dir, nutchConf);
+ this.handlerCount = nutchConf.getInt("ndfs.namenode.handler.count", 10);
+ this.server = RPC.getServer(this, port, handlerCount, false, nutchConf);
this.server.start();
}
@@ -346,7 +345,7 @@ public class NameNode implements ClientProtocol, DatanodeProtocol, FSConstants {
/**
*/
public static void main(String argv[]) throws IOException, InterruptedException {
- NameNode namenode = new NameNode();
+ NameNode namenode = new NameNode(new NutchConf());
namenode.join();
}
}
diff --git a/src/java/org/apache/nutch/net/BasicUrlNormalizer.java b/src/java/org/apache/nutch/net/BasicUrlNormalizer.java
index 6d1823fef..2749bd7fc 100644
--- a/src/java/org/apache/nutch/net/BasicUrlNormalizer.java
+++ b/src/java/org/apache/nutch/net/BasicUrlNormalizer.java
@@ -23,6 +23,7 @@ import java.net.MalformedURLException;
import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.oro.text.regex.*;
/** Converts URLs to a normal form . */
@@ -39,6 +40,8 @@ public class BasicUrlNormalizer implements UrlNormalizer {
private Rule relativePathRule = null;
private Rule leadingRelativePathRule = null;
+ private NutchConf nutchConf;
+
public BasicUrlNormalizer() {
try {
// this pattern tries to find spots like "/xx/../" in the url, which
@@ -172,5 +175,14 @@ public class BasicUrlNormalizer implements UrlNormalizer {
public Perl5Substitution substitution;
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/java/org/apache/nutch/net/RegexUrlNormalizer.java b/src/java/org/apache/nutch/net/RegexUrlNormalizer.java
index 1b8d86830..06e7b1e9e 100644
--- a/src/java/org/apache/nutch/net/RegexUrlNormalizer.java
+++ b/src/java/org/apache/nutch/net/RegexUrlNormalizer.java
@@ -27,6 +27,7 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import javax.xml.parsers.*;
import org.w3c.dom.*;
@@ -57,15 +58,8 @@ public class RegexUrlNormalizer extends BasicUrlNormalizer
private List rules;
private PatternMatcher matcher = new Perl5Matcher();
- /** Default constructor which gets the file name from either <tt>nutch-site.xml</tt>
- * or <tt>nutch-default.xml</tt> and reads that configuration file. It stores the regex patterns
- * and corresponding substitutions in a List. The file should be in the CLASSPATH. */
- public RegexUrlNormalizer() throws IOException, MalformedPatternException {
- String filename = NutchConf.get().get("urlnormalizer.regex.file");
- URL url= NutchConf.get().getResource(filename);
-
- rules=readConfigurationFile(url.toString());
- }
+ /** The default constructor which is called from UrlNormalizerFactory (normalizerClass.newInstance()) in method: getNormalizer()**/
+ public RegexUrlNormalizer() {}
/** Constructor which can be passed the file name, so it doesn't look in the configuration files for it. */
public RegexUrlNormalizer(String filename)
@@ -101,7 +95,7 @@ public class RegexUrlNormalizer extends BasicUrlNormalizer
/** Reads the configuration file and populates a List of Rules. */
- private static List readConfigurationFile(String filename)
+ private List readConfigurationFile(String filename)
throws IOException, MalformedPatternException {
Perl5Compiler compiler=new Perl5Compiler();
@@ -153,10 +147,30 @@ public class RegexUrlNormalizer extends BasicUrlNormalizer
return rules;
}
+ public void setConf(NutchConf conf) {
+ super.setConf(conf);
+ // the default constructor was called
+ if (this.rules == null) {
+ String filename = getConf().get("urlnormalizer.regex.file");
+ URL url = getConf().getResource(filename);
+ try {
+ this.rules = readConfigurationFile(url.toString());
+ } catch (IOException e) {
+ // TODO [email protected]: throw Exception? Because broken api.
+ throw new RuntimeException(e.getMessage(), e);
+ } catch (MalformedPatternException e) {
+ // TODO [email protected]: throw Exception? Because broken api.
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+
+ }
+
/** Spits out patterns and substitutions that are in the configuration file. */
public static void main(String args[])
throws MalformedPatternException, IOException {
RegexUrlNormalizer normalizer = new RegexUrlNormalizer();
+ normalizer.setConf(new NutchConf());
Iterator i=normalizer.rules.iterator();
while(i.hasNext()) {
Rule r=(Rule) i.next();
diff --git a/src/java/org/apache/nutch/net/URLFilter.java b/src/java/org/apache/nutch/net/URLFilter.java
index 70d27f766..ade30adbc 100644
--- a/src/java/org/apache/nutch/net/URLFilter.java
+++ b/src/java/org/apache/nutch/net/URLFilter.java
@@ -16,12 +16,14 @@
package org.apache.nutch.net;
+import org.apache.nutch.util.NutchConfigurable;
+
/**
* Interface used to limit which URLs enter Nutch.
* Used by the injector and the db updater.
*/
-public interface URLFilter {
+public interface URLFilter extends NutchConfigurable {
/** The name of the extension point. */
public final static String X_POINT_ID = URLFilter.class.getName();
diff --git a/src/java/org/apache/nutch/net/URLFilterChecker.java b/src/java/org/apache/nutch/net/URLFilterChecker.java
index 36b588312..0bc99fbf9 100644
--- a/src/java/org/apache/nutch/net/URLFilterChecker.java
+++ b/src/java/org/apache/nutch/net/URLFilterChecker.java
@@ -21,6 +21,7 @@ import org.apache.nutch.plugin.ExtensionPoint;
import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import java.util.logging.Logger;
@@ -37,14 +38,17 @@ public class URLFilterChecker {
public static final Logger LOG =
LogFormatter.getLogger(URLFilterChecker.class.getName());
+ private NutchConf nutchConf;
- public URLFilterChecker() {}
+ public URLFilterChecker(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ }
private void checkOne(String filterName) throws Exception {
URLFilter filter = null;
ExtensionPoint point =
- PluginRepository.getInstance().getExtensionPoint(URLFilter.X_POINT_ID);
+ this.nutchConf.getPluginRepository().getExtensionPoint(URLFilter.X_POINT_ID);
if (point == null)
throw new RuntimeException(URLFilter.X_POINT_ID+" not found.");
@@ -90,7 +94,8 @@ public class URLFilterChecker {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line=in.readLine())!=null) {
- String out=URLFilters.filter(line);
+ URLFilters filters = new URLFilters(this.nutchConf);
+ String out = filters.filter(line);
if(out!=null) {
System.out.print("+");
System.out.println(out);
@@ -119,7 +124,7 @@ public class URLFilterChecker {
filterName = args[1];
}
- URLFilterChecker checker = new URLFilterChecker();
+ URLFilterChecker checker = new URLFilterChecker(new NutchConf());
if (filterName != null) {
checker.checkOne(filterName);
} else {
diff --git a/src/java/org/apache/nutch/net/URLFilters.java b/src/java/org/apache/nutch/net/URLFilters.java
index 4c06daea3..65801738c 100644
--- a/src/java/org/apache/nutch/net/URLFilters.java
+++ b/src/java/org/apache/nutch/net/URLFilters.java
@@ -20,63 +20,67 @@ import java.util.HashMap;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
-import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.plugin.PluginRuntimeException;
import org.apache.nutch.util.NutchConf;
-
/** Creates and caches {@link URLFilter} implementing plugins.*/
public class URLFilters {
- private static final URLFilter[] CACHE;
- static {
- String order = NutchConf.get().get("urlfilter.order");
- String[] orderedFilters = null;
- if (order!=null && !order.trim().equals("")) {
- orderedFilters = order.split("\\s+");
- }
-
- try {
- ExtensionPoint point =
- PluginRepository.getInstance().getExtensionPoint(URLFilter.X_POINT_ID);
+ private NutchConf nutchConf;
+ private URLFilter[] filters;
- if (point == null)
- throw new RuntimeException(URLFilter.X_POINT_ID+" not found.");
+ public URLFilters(NutchConf nutchConf) {
+ String order = nutchConf.get("urlfilter.order");
+ this.filters = (URLFilter[]) nutchConf.getObject(URLFilter.class.getName());
+
+ if (this.filters == null) {
+ String[] orderedFilters = null;
+ if (order != null && !order.trim().equals("")) {
+ orderedFilters = order.split("\\s+");
+ }
- Extension[] extensions = point.getExtensions();
- HashMap filterMap = new HashMap();
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- URLFilter filter = (URLFilter)extension.getExtensionInstance();
- if (!filterMap.containsKey(filter.getClass().getName())) {
- filterMap.put(filter.getClass().getName(), filter);
+ try {
+ ExtensionPoint point = nutchConf.getPluginRepository()
+ .getExtensionPoint(URLFilter.X_POINT_ID);
+ if (point == null)
+ throw new RuntimeException(URLFilter.X_POINT_ID
+ + " not found.");
+ Extension[] extensions = point.getExtensions();
+ HashMap filterMap = new HashMap();
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ URLFilter filter = (URLFilter) extension
+ .getExtensionInstance();
+ if (!filterMap.containsKey(filter.getClass().getName())) {
+ filterMap.put(filter.getClass().getName(), filter);
+ }
+ }
+ if (orderedFilters == null) {
+ nutchConf.setObject(URLFilter.class.getName(), filterMap
+ .values().toArray(new URLFilter[0]));
+ } else {
+ URLFilter[] filter = new URLFilter[orderedFilters.length];
+ for (int i = 0; i < orderedFilters.length; i++) {
+ filter[i] = (URLFilter) filterMap
+ .get(orderedFilters[i]);
+ }
+ nutchConf.setObject(URLFilter.class.getName(), filter);
+ }
+ } catch (PluginRuntimeException e) {
+ throw new RuntimeException(e);
+ }
+ this.filters = (URLFilter[]) nutchConf.getObject(URLFilter.class
+ .getName());
}
- }
- if (orderedFilters==null) {
- CACHE = (URLFilter[])filterMap.values().toArray(new URLFilter[0]);
- } else {
- CACHE = new URLFilter[orderedFilters.length];
- for (int i=0; i<orderedFilters.length; i++) {
- CACHE[i] = (URLFilter)filterMap.get(orderedFilters[i]);
- }
- }
- } catch (PluginRuntimeException e) {
- throw new RuntimeException(e);
- }
- }
-
- private URLFilters() {} // no public ctor
+ }
/** Run all defined filters. Assume logical AND. */
- public static String filter(String urlString) throws URLFilterException {
-
- for (int i = 0; i < CACHE.length; i++) {
+ public String filter(String urlString) throws URLFilterException {
+ for (int i = 0; i < this.filters.length; i++) {
if (urlString == null)
return null;
- //System.out.println("using fitler "+i+":"+CACHE[i].getClass().getName());
- urlString = CACHE[i].filter(urlString);
+ urlString = this.filters[i].filter(urlString);
}
-
return urlString;
}
}
diff --git a/src/java/org/apache/nutch/net/UrlNormalizer.java b/src/java/org/apache/nutch/net/UrlNormalizer.java
index 199506b11..1961fa85a 100644
--- a/src/java/org/apache/nutch/net/UrlNormalizer.java
+++ b/src/java/org/apache/nutch/net/UrlNormalizer.java
@@ -18,8 +18,10 @@ package org.apache.nutch.net;
import java.net.MalformedURLException;
+import org.apache.nutch.util.NutchConfigurable;
+
/** Interface used to convert URLs to normal form and optionally do regex substitutions */
-public interface UrlNormalizer {
+public interface UrlNormalizer extends NutchConfigurable {
/* Interface for URL normalization */
public String normalize(String urlString) throws MalformedURLException;
diff --git a/src/java/org/apache/nutch/net/UrlNormalizerFactory.java b/src/java/org/apache/nutch/net/UrlNormalizerFactory.java
index c4db6af41..0028501db 100644
--- a/src/java/org/apache/nutch/net/UrlNormalizerFactory.java
+++ b/src/java/org/apache/nutch/net/UrlNormalizerFactory.java
@@ -17,35 +17,38 @@
package org.apache.nutch.net;
import org.apache.nutch.util.*;
+
+import java.net.URL;
import java.util.logging.*;
/** Factory to create a UrlNormalizer from "urlnormalizer.class" config property. */
public class UrlNormalizerFactory {
- private static final Logger LOG =
- LogFormatter.getLogger("org.apache.nutch.net.UrlNormalizerFactory");
-
- private static final String URLNORMALIZER_CLASS =
- NutchConf.get().get("urlnormalizer.class");
+ private static final Logger LOG = LogFormatter
+ .getLogger("org.apache.nutch.net.UrlNormalizerFactory");
- private UrlNormalizerFactory() {} // no public ctor
+ private NutchConf nutchConf;
- private static UrlNormalizer normalizer;
+ public UrlNormalizerFactory(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ }
/** Return the default UrlNormalizer implementation. */
- public static UrlNormalizer getNormalizer() {
-
+ public UrlNormalizer getNormalizer() {
+ String urlNormalizer = null;
+ UrlNormalizer normalizer = (UrlNormalizer) this.nutchConf
+ .getObject(UrlNormalizer.class.getName());
if (normalizer == null) {
try {
- LOG.info("Using URL normalizer: " + URLNORMALIZER_CLASS);
- Class normalizerClass = Class.forName(URLNORMALIZER_CLASS);
- normalizer = (UrlNormalizer)normalizerClass.newInstance();
+ urlNormalizer = this.nutchConf.get("urlnormalizer.class");
+ LOG.info("Using URL normalizer: " + urlNormalizer);
+ Class normalizerClass = Class.forName(urlNormalizer);
+ normalizer = (UrlNormalizer) normalizerClass.newInstance();
+ normalizer.setConf(this.nutchConf);
+ this.nutchConf.setObject(UrlNormalizer.class.getName(), normalizer);
} catch (Exception e) {
- throw new RuntimeException("Couldn't create "+URLNORMALIZER_CLASS, e);
+ throw new RuntimeException("Couldn't create " + urlNormalizer, e);
}
}
-
return normalizer;
-
}
-
}
diff --git a/src/java/org/apache/nutch/ontology/OntologyFactory.java b/src/java/org/apache/nutch/ontology/OntologyFactory.java
index d34864c86..8db825864 100644
--- a/src/java/org/apache/nutch/ontology/OntologyFactory.java
+++ b/src/java/org/apache/nutch/ontology/OntologyFactory.java
@@ -31,10 +31,13 @@ public class OntologyFactory {
public final static Logger LOG =
LogFormatter.getLogger(OntologyFactory.class.getName());
- private final static ExtensionPoint X_POINT =
- PluginRepository.getInstance().getExtensionPoint(Ontology.X_POINT_ID);
-
- private OntologyFactory() {}
+ private ExtensionPoint extensionPoint;
+ private NutchConf nutchConf;
+
+ public OntologyFactory(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(Ontology.X_POINT_ID);
+ }
/**
* @return Returns the online ontology extension specified
@@ -43,14 +46,14 @@ public class OntologyFactory {
* If the name is empty (no preference),
* the first available ontology extension is returned.
*/
- public static Ontology getOntology() throws PluginRuntimeException {
-
- if (X_POINT == null) {
+ public Ontology getOntology() throws PluginRuntimeException {
+
+ if (this.extensionPoint == null) {
// not even an extension point defined.
return null;
}
- String extensionName = NutchConf.get().get("extension.ontology.extension-name");
+ String extensionName = this.nutchConf.get("extension.ontology.extension-name");
if (extensionName != null) {
Extension extension = findExtension(extensionName);
if (extension != null) {
@@ -62,7 +65,7 @@ public class OntologyFactory {
// not found, fallback to the default, if available.
}
- Extension[] extensions = X_POINT.getExtensions();
+ Extension[] extensions = this.extensionPoint.getExtensions();
if (extensions.length > 0) {
LOG.info("Using the first ontology extension found: "
+ extensions[0].getId());
@@ -73,10 +76,10 @@ public class OntologyFactory {
}
- private static Extension findExtension(String name)
+ private Extension findExtension(String name)
throws PluginRuntimeException {
- Extension[] extensions = X_POINT.getExtensions();
+ Extension[] extensions = this.extensionPoint.getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilter.java b/src/java/org/apache/nutch/parse/HtmlParseFilter.java
index ad3cee57d..efb38bde0 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilter.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilter.java
@@ -17,6 +17,7 @@
package org.apache.nutch.parse;
import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.NutchConfigurable;
import org.w3c.dom.DocumentFragment;
@@ -24,7 +25,7 @@ import org.w3c.dom.DocumentFragment;
* metadata to HTML parses. All plugins found which implement this extension
* point are run sequentially on the parse.
*/
-public interface HtmlParseFilter {
+public interface HtmlParseFilter extends NutchConfigurable {
/** The name of the extension point. */
final static String X_POINT_ID = HtmlParseFilter.class.getName();
diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilters.java b/src/java/org/apache/nutch/parse/HtmlParseFilters.java
index b769c2f23..2d812f2a7 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilters.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilters.java
@@ -16,39 +16,49 @@
package org.apache.nutch.parse;
+import java.util.HashMap;
+
import org.apache.nutch.protocol.Content;
import org.apache.nutch.plugin.*;
+import org.apache.nutch.util.NutchConf;
import org.w3c.dom.DocumentFragment;
/** Creates and caches {@link HtmlParseFilter} implementing plugins.*/
public class HtmlParseFilters {
- private static final HtmlParseFilter[] CACHE;
- static {
- try {
- ExtensionPoint point = PluginRepository.getInstance()
- .getExtensionPoint(HtmlParseFilter.X_POINT_ID);
- if (point == null)
- throw new RuntimeException(HtmlParseFilter.X_POINT_ID+" not found.");
- Extension[] extensions = point.getExtensions();
- CACHE = new HtmlParseFilter[extensions.length];
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- CACHE[i] = (HtmlParseFilter)extension.getExtensionInstance();
- }
- } catch (PluginRuntimeException e) {
- throw new RuntimeException(e);
- }
- }
+ private HtmlParseFilter[] htmlParseFilters;
- private HtmlParseFilters() {} // no public ctor
+ public HtmlParseFilters(NutchConf nutchConf) {
+ this.htmlParseFilters = (HtmlParseFilter[]) nutchConf.getObject(HtmlParseFilter.class.getName());
+ if (htmlParseFilters == null) {
+ HashMap filters = new HashMap();
+ try {
+ ExtensionPoint point = nutchConf.getPluginRepository().getExtensionPoint(HtmlParseFilter.X_POINT_ID);
+ if (point == null)
+ throw new RuntimeException(HtmlParseFilter.X_POINT_ID + " not found.");
+ Extension[] extensions = point.getExtensions();
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ HtmlParseFilter parseFilter = (HtmlParseFilter) extension.getExtensionInstance();
+ if (!filters.containsKey(parseFilter.getClass().getName())) {
+ filters.put(parseFilter.getClass().getName(), parseFilter);
+ }
+ }
+ HtmlParseFilter[] htmlParseFilters = (HtmlParseFilter[]) filters.values().toArray(new HtmlParseFilter[filters.size()]);
+ nutchConf.setObject(HtmlParseFilter.class.getName(), htmlParseFilters);
+ } catch (PluginRuntimeException e) {
+ throw new RuntimeException(e);
+ }
+ this.htmlParseFilters = (HtmlParseFilter[]) nutchConf.getObject(HtmlParseFilter.class.getName());
+ }
+ }
/** Run all defined filters. */
- public static Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
+ public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
- for (int i = 0 ; i < CACHE.length; i++) {
- parse = CACHE[i].filter(content, parse, metaTags, doc);
+ for (int i = 0 ; i < this.htmlParseFilters.length; i++) {
+ parse = this.htmlParseFilters[i].filter(content, parse, metaTags, doc);
if (!parse.getData().getStatus().isSuccess()) break;
}
diff --git a/src/java/org/apache/nutch/parse/Outlink.java b/src/java/org/apache/nutch/parse/Outlink.java
index 0eda8a432..0904e7dbe 100644
--- a/src/java/org/apache/nutch/parse/Outlink.java
+++ b/src/java/org/apache/nutch/parse/Outlink.java
@@ -21,6 +21,7 @@ import java.net.MalformedURLException;
import org.apache.nutch.io.*;
import org.apache.nutch.net.UrlNormalizerFactory;
+import org.apache.nutch.util.NutchConf;
/* An outgoing link from a page. */
public class Outlink implements Writable {
@@ -30,8 +31,8 @@ public class Outlink implements Writable {
public Outlink() {}
- public Outlink(String toUrl, String anchor) throws MalformedURLException {
- this.toUrl = UrlNormalizerFactory.getNormalizer().normalize(toUrl);
+ public Outlink(String toUrl, String anchor, NutchConf nutchConf) throws MalformedURLException {
+ this.toUrl = new UrlNormalizerFactory(nutchConf).getNormalizer().normalize(toUrl);
this.anchor = anchor;
}
diff --git a/src/java/org/apache/nutch/parse/OutlinkExtractor.java b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
index 6aa0a81c5..9b18d9ac2 100644
--- a/src/java/org/apache/nutch/parse/OutlinkExtractor.java
+++ b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
@@ -21,6 +21,7 @@ import java.util.List;
import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
@@ -65,8 +66,8 @@ public class OutlinkExtractor {
*
* @return Array of <code>Outlink</code>s within found in plainText
*/
- public static Outlink[] getOutlinks(final String plainText) {
- return OutlinkExtractor.getOutlinks(plainText, "");
+ public static Outlink[] getOutlinks(final String plainText, NutchConf nutchConf) {
+ return OutlinkExtractor.getOutlinks(plainText, "", nutchConf);
}
/**
@@ -78,7 +79,7 @@ public class OutlinkExtractor {
*
* @return Array of <code>Outlink</code>s within found in plainText
*/
- public static Outlink[] getOutlinks(final String plainText, String anchor) {
+ public static Outlink[] getOutlinks(final String plainText, String anchor, NutchConf nutchConf) {
long start = System.currentTimeMillis();
final List outlinks = new ArrayList();
@@ -105,7 +106,7 @@ public class OutlinkExtractor {
}
result = matcher.getMatch();
url = result.group(0);
- outlinks.add(new Outlink(url, anchor));
+ outlinks.add(new Outlink(url, anchor, nutchConf));
}
} catch (Exception ex) {
// if the matcher fails (perhaps a malformed URL) we just log it and move on
diff --git a/src/java/org/apache/nutch/parse/ParseData.java b/src/java/org/apache/nutch/parse/ParseData.java
index d78c451ad..c10611ebc 100644
--- a/src/java/org/apache/nutch/parse/ParseData.java
+++ b/src/java/org/apache/nutch/parse/ParseData.java
@@ -23,12 +23,13 @@ import org.apache.nutch.io.*;
import org.apache.nutch.fs.*;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
/** Data extracted from a page's content.
* @see Parse#getData()
*/
-public final class ParseData extends VersionedWritable {
+public final class ParseData extends VersionedWritable implements NutchConfigurable {
public static final String DIR_NAME = "parse_data";
private final static byte VERSION = 3;
@@ -37,7 +38,12 @@ public final class ParseData extends VersionedWritable {
private Outlink[] outlinks;
private ContentProperties metadata;
private ParseStatus status;
-
+ private NutchConf nutchConf;
+
+ // TODO [email protected]: should we really implement NutchConfigurable or should we add the
+ // parameter NutchConf to the default-constructor. NOTE: The test
+ // TestWriteable instantiates ParseData with Class.newInstance() -> the default
+ // constructor is called -> nutchConf is null. The programmer which use this object may not forget to set the nutchConf.
public ParseData() {}
public ParseData(ParseStatus status, String title, Outlink[] outlinks, ContentProperties metadata) {
@@ -84,15 +90,13 @@ public final class ParseData extends VersionedWritable {
title = UTF8.readString(in); // read title
int totalOutlinks = in.readInt(); // read outlinks
- // XXX remove the dependency on static NutchConf.get(). How?
- int outlinksToRead =
- Math.min(NutchConf.get().getInt("db.max.outlinks.per.page", 100),
- totalOutlinks);
+ int maxOutlinksPerPage = this.nutchConf.getInt("db.max.outlinks.per.page", 100);
+ int outlinksToRead = Math.min(maxOutlinksPerPage, totalOutlinks);
outlinks = new Outlink[outlinksToRead];
for (int i = 0; i < outlinksToRead; i++) {
outlinks[i] = Outlink.read(in);
}
- for (int i = outlinksToRead; i < totalOutlinks; i++) {
+ for (int i = maxOutlinksPerPage; i < totalOutlinks; i++) {
Outlink.skip(in);
}
@@ -168,7 +172,8 @@ public final class ParseData extends VersionedWritable {
return;
}
- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0);
+ NutchConf nutchConf = new NutchConf();
+ NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0, nutchConf);
try {
int recno = Integer.parseInt(argv[0]);
String segment = argv[1];
@@ -176,7 +181,7 @@ public final class ParseData extends VersionedWritable {
File file = new File(segment, DIR_NAME);
System.out.println("Reading from file: " + file);
- ArrayFile.Reader parses = new ArrayFile.Reader(nfs, file.toString());
+ ArrayFile.Reader parses = new ArrayFile.Reader(nfs, file.toString(), nutchConf);
ParseData parseDatum = new ParseData();
parses.get(recno, parseDatum);
@@ -189,4 +194,12 @@ public final class ParseData extends VersionedWritable {
nfs.close();
}
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/java/org/apache/nutch/parse/ParseImpl.java b/src/java/org/apache/nutch/parse/ParseImpl.java
index 1c3815ea7..e665c5107 100644
--- a/src/java/org/apache/nutch/parse/ParseImpl.java
+++ b/src/java/org/apache/nutch/parse/ParseImpl.java
@@ -18,14 +18,17 @@ package org.apache.nutch.parse;
import java.io.*;
import org.apache.nutch.io.*;
+import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
/** The result of parsing a page's raw content.
* @see Parser#getParse(Content)
*/
-public class ParseImpl implements Parse, Writable {
+public class ParseImpl implements Parse, Writable, NutchConfigurable {
private ParseText text;
private ParseData data;
+ private NutchConf nutchConf;
public ParseImpl() {}
@@ -56,13 +59,24 @@ public class ParseImpl implements Parse, Writable {
text.readFields(in);
data = new ParseData();
+ data.setConf(this.nutchConf);
data.readFields(in);
}
- public static ParseImpl read(DataInput in) throws IOException {
+ public static ParseImpl read(DataInput in, NutchConf nutchConf) throws IOException {
ParseImpl parseImpl = new ParseImpl();
+ parseImpl.setConf(nutchConf);
parseImpl.readFields(in);
return parseImpl;
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
index 0c97f950d..46cfbd5ca 100644
--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java
+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
@@ -31,11 +31,17 @@ import java.util.*;
/* Parse content in a segment. */
public class ParseOutputFormat implements OutputFormat {
- private UrlNormalizer urlNormalizer = UrlNormalizerFactory.getNormalizer();
+ private UrlNormalizer urlNormalizer;
+ private JobConf jobConf;
+ private URLFilters filters;
+
public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,
String name) throws IOException {
+ this.jobConf = job;
+ this.urlNormalizer = new UrlNormalizerFactory(job).getNormalizer();
+ this.filters = new URLFilters(job);
final float interval = job.getFloat("db.default.fetch.interval", 30f);
final float extscore = job.getFloat("db.score.link.external", 1.0f);
@@ -58,6 +64,7 @@ public class ParseOutputFormat implements OutputFormat {
return new RecordWriter() {
+
public void write(WritableComparable key, Writable value)
throws IOException {
@@ -92,7 +99,7 @@ public class ParseOutputFormat implements OutputFormat {
String toUrl = links[i].getToUrl();
try {
toUrl = urlNormalizer.normalize(toUrl); // normalize the url
- toUrl = URLFilters.filter(toUrl); // filter the url
+ toUrl = filters.filter(toUrl); // filter the url
} catch (Exception e) {
toUrl = null;
}
diff --git a/src/java/org/apache/nutch/parse/ParsePluginsReader.java b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
index d44ce332f..13fe52836 100644
--- a/src/java/org/apache/nutch/parse/ParsePluginsReader.java
+++ b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
@@ -74,7 +74,7 @@ public class ParsePluginsReader {
* @throws Exception
* If any parsing error occurs.
*/
- public ParsePluginList parse() {
+ public ParsePluginList parse(NutchConf nutchConf) {
ParsePluginList pList = new ParsePluginList();
@@ -96,8 +96,8 @@ public class ParsePluginsReader {
return pList;
}
} else {
- ppInputStream = NutchConf.get().getConfResourceAsInputStream(
- NutchConf.get().get(PP_FILE_PROP));
+ ppInputStream = nutchConf.getConfResourceAsInputStream(
+ nutchConf.get(PP_FILE_PROP));
}
inputSource = new InputSource(ppInputStream);
@@ -197,7 +197,7 @@ public class ParsePluginsReader {
reader.setFParsePluginsFile(parsePluginFile);
}
- ParsePluginList prefs = reader.parse();
+ ParsePluginList prefs = reader.parse(new NutchConf());
for (Iterator i = prefs.getSupportedMimeTypes().iterator(); i.hasNext();) {
String mimeType = (String) i.next();
diff --git a/src/java/org/apache/nutch/parse/ParseSegment.java b/src/java/org/apache/nutch/parse/ParseSegment.java
index cceb538f8..4c568af6a 100644
--- a/src/java/org/apache/nutch/parse/ParseSegment.java
+++ b/src/java/org/apache/nutch/parse/ParseSegment.java
@@ -34,8 +34,6 @@ public class ParseSegment extends NutchConfigured implements Mapper, Reducer {
public static final Logger LOG =
LogFormatter.getLogger(Parser.class.getName());
- public ParseSegment() { super(NutchConf.get()); }
-
public ParseSegment(NutchConf conf) {
super(conf);
}
@@ -52,7 +50,7 @@ public class ParseSegment extends NutchConfigured implements Mapper, Reducer {
Parse parse = null;
ParseStatus status;
try {
- parse = ParseUtil.parse(content);
+ parse = new ParseUtil(getConf()).parse(content);
status = parse.getData().getStatus();
} catch (Exception e) {
status = new ParseStatus(e);
@@ -116,7 +114,7 @@ public class ParseSegment extends NutchConfigured implements Mapper, Reducer {
segment = new File(args[0]);
- ParseSegment parseSegment = new ParseSegment(NutchConf.get());
+ ParseSegment parseSegment = new ParseSegment(new NutchConf());
parseSegment.parse(segment);
}
}
diff --git a/src/java/org/apache/nutch/parse/ParseStatus.java b/src/java/org/apache/nutch/parse/ParseStatus.java
index 9c81044f7..de47bbeb6 100644
--- a/src/java/org/apache/nutch/parse/ParseStatus.java
+++ b/src/java/org/apache/nutch/parse/ParseStatus.java
@@ -13,6 +13,7 @@ import java.util.Properties;
import org.apache.nutch.io.VersionedWritable;
import org.apache.nutch.io.WritableUtils;
import org.apache.nutch.protocol.ContentProperties;
+import org.apache.nutch.util.NutchConf;
/**
* @author Andrzej Bialecki &lt;[email protected]&gt;
@@ -163,8 +164,8 @@ public class ParseStatus extends VersionedWritable {
/** A convenience method. Creates an empty Parse instance,
* which returns this status.
*/
- public Parse getEmptyParse() {
- return new EmptyParseImpl(this);
+ public Parse getEmptyParse(NutchConf nutchConf) {
+ return new EmptyParseImpl(this, nutchConf);
}
public String toString() {
@@ -230,8 +231,9 @@ public class ParseStatus extends VersionedWritable {
private ParseData data = null;
- public EmptyParseImpl(ParseStatus status) {
+ public EmptyParseImpl(ParseStatus status, NutchConf nutchConf) {
data = new ParseData(status, "", new Outlink[0], new ContentProperties());
+ data.setConf(nutchConf);
}
public ParseData getData() {
diff --git a/src/java/org/apache/nutch/parse/ParseText.java b/src/java/org/apache/nutch/parse/ParseText.java
index c23ed2f3c..3cb469df1 100644
--- a/src/java/org/apache/nutch/parse/ParseText.java
+++ b/src/java/org/apache/nutch/parse/ParseText.java
@@ -80,14 +80,15 @@ public final class ParseText extends VersionedWritable {
return;
}
- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0);
+ NutchConf nutchConf = new NutchConf();
+ NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0, nutchConf);
try {
int recno = Integer.parseInt(argv[0]);
String segment = argv[1];
String filename = new File(segment, ParseText.DIR_NAME).getPath();
ParseText parseText = new ParseText();
- ArrayFile.Reader parseTexts = new ArrayFile.Reader(nfs, filename);
+ ArrayFile.Reader parseTexts = new ArrayFile.Reader(nfs, filename, nutchConf);
parseTexts.get(recno, parseText);
System.out.println("Retrieved " + recno + " from file " + filename);
diff --git a/src/java/org/apache/nutch/parse/ParseUtil.java b/src/java/org/apache/nutch/parse/ParseUtil.java
index 7a6644b2a..01e529c78 100644
--- a/src/java/org/apache/nutch/parse/ParseUtil.java
+++ b/src/java/org/apache/nutch/parse/ParseUtil.java
@@ -21,6 +21,7 @@ import java.util.logging.Logger;
// Nutch Imports
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/**
@@ -37,9 +38,17 @@ public class ParseUtil {
/* our log stream */
public static final Logger LOG = LogFormatter.getLogger(ParseUtil.class
.getName());
+ private NutchConf nutchConf;
+ private ParserFactory parserFactory;
- /** No public constructor */
- private ParseUtil() { }
+ /**
+ *
+ * @param nutchConf
+ */
+ public ParseUtil(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ this.parserFactory = new ParserFactory(nutchConf);
+ }
/**
* Performs a parse by iterating through a List of preferred {@Parser}s
@@ -51,11 +60,11 @@ public class ParseUtil {
* @return A {@link Parse} object containing the parsed data.
* @throws ParseException If no suitable parser is found to perform the parse.
*/
- public final static Parse parse(Content content) throws ParseException {
+ public Parse parse(Content content) throws ParseException {
Parser[] parsers = null;
try {
- parsers = ParserFactory.getParsers(content.getContentType(), "");
+ parsers = this.parserFactory.getParsers(content.getContentType(), "");
} catch (ParserNotFound e) {
LOG.warning("No suitable parser found when trying to parse content " +
content);
@@ -75,7 +84,7 @@ public class ParseUtil {
" of type " + content.getContentType());
ParseStatus ps = (parse.getData() != null) ? parse.getData().getStatus() : null;
- return (ps == null) ? new ParseStatus().getEmptyParse() : ps.getEmptyParse();
+ return (ps == null) ? new ParseStatus().getEmptyParse(this.nutchConf) : ps.getEmptyParse(this.nutchConf);
}
/**
@@ -95,13 +104,13 @@ public class ParseUtil {
* @throws ParseException If there is no suitable {@link Parser} found
* to perform the parse.
*/
- public final static Parse parseByParserId(String parserId, Content content)
+ public Parse parseByParserId(String parserId, Content content)
throws ParseException {
Parse parse = null;
Parser p = null;
try {
- p = ParserFactory.getParserById(parserId);
+ p = this.parserFactory.getParserById(parserId);
} catch (ParserNotFound e) {
LOG.warning("No suitable parser found when trying to parse content " +
content);
@@ -115,7 +124,7 @@ public class ParseUtil {
} else {
LOG.warning("Unable to successfully parse content " + content.getUrl() +
" of type " + content.getContentType());
- return new ParseStatus().getEmptyParse();
+ return new ParseStatus().getEmptyParse(this.nutchConf);
}
}
diff --git a/src/java/org/apache/nutch/parse/Parser.java b/src/java/org/apache/nutch/parse/Parser.java
index d9df89de1..3e0263ea5 100644
--- a/src/java/org/apache/nutch/parse/Parser.java
+++ b/src/java/org/apache/nutch/parse/Parser.java
@@ -17,12 +17,13 @@
package org.apache.nutch.parse;
import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.NutchConfigurable;
/** A parser for content generated by a {@link org.apache.nutch.protocol.Protocol}
* implementation. This interface is implemented by extensions. Nutch's core
* contains no page parsing code.
*/
-public interface Parser {
+public interface Parser extends NutchConfigurable {
/** The name of the extension point. */
public final static String X_POINT_ID = Parser.class.getName();
diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.java
index 2f8ba1c97..45e2adb44 100644
--- a/src/java/org/apache/nutch/parse/ParserChecker.java
+++ b/src/java/org/apache/nutch/parse/ParserChecker.java
@@ -17,6 +17,7 @@
package org.apache.nutch.parse;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.io.UTF8;
@@ -70,7 +71,9 @@ public class ParserChecker {
LOG.info("fetching: "+url);
- Protocol protocol = ProtocolFactory.getProtocol(url);
+ NutchConf nutchConf = new NutchConf();
+ ProtocolFactory factory = new ProtocolFactory(nutchConf);
+ Protocol protocol = factory.getProtocol(url);
Content content = protocol.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();
if (force) {
@@ -87,7 +90,7 @@ public class ParserChecker {
LOG.info("parsing: "+url);
LOG.info("contentType: "+contentType);
- Parse parse = ParseUtil.parse(content);
+ Parse parse = new ParseUtil(nutchConf).parse(content);
System.out.print("---------\nParseData\n---------\n");
System.out.print(parse.getData().toString());
diff --git a/src/java/org/apache/nutch/parse/ParserFactory.java b/src/java/org/apache/nutch/parse/ParserFactory.java
index 3818768e5..de04892dc 100644
--- a/src/java/org/apache/nutch/parse/ParserFactory.java
+++ b/src/java/org/apache/nutch/parse/ParserFactory.java
@@ -17,7 +17,6 @@ package org.apache.nutch.parse;
// JDK imports
import java.util.Collections;
-import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
@@ -26,13 +25,12 @@ import java.util.logging.Logger;
// Nutch imports
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
-import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.plugin.PluginRuntimeException;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.util.mime.MimeType;
import org.apache.nutch.util.mime.MimeTypeException;
-
/** Creates and caches {@link Parser} plugins.*/
public final class ParserFactory {
@@ -41,52 +39,46 @@ public final class ParserFactory {
/** Wildcard for default plugins. */
public static final String DEFAULT_PLUGIN = "*";
-
- /** Extension point. */
- private static final ExtensionPoint X_POINT =
- PluginRepository.getInstance().getExtensionPoint(Parser.X_POINT_ID);
-
- /** List of parser plugins. */
- private static final ParsePluginList PARSE_PLUGIN_LIST =
- new ParsePluginsReader().parse();
/** Empty extension list for caching purposes. */
- private static final List EMPTY_EXTENSION_LIST = Collections.EMPTY_LIST;
+ private final List EMPTY_EXTENSION_LIST = Collections.EMPTY_LIST;
- static {
- if (X_POINT == null) {
- throw new RuntimeException("x point "+Parser.X_POINT_ID+" not found.");
+ private NutchConf nutchConf;
+ private ExtensionPoint extensionPoint;
+ private ParsePluginList parsePluginList;
+
+ public ParserFactory(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(
+ Parser.X_POINT_ID);
+ this.parsePluginList = new ParsePluginsReader().parse(nutchConf);
+
+ if (this.extensionPoint == null) {
+ throw new RuntimeException("x point " + Parser.X_POINT_ID + " not found.");
}
- if (PARSE_PLUGIN_LIST == null) {
- throw new RuntimeException("Parse Plugins preferences could not be loaded.");
+ if (this.parsePluginList == null) {
+ throw new RuntimeException(
+ "Parse Plugins preferences could not be loaded.");
}
- }
-
- //cache mapping mimeType->List of Extensions
- private static final Hashtable CACHE = new Hashtable();
-
- //cache mapping parser plugin id->Parser instance
- private static final Hashtable PARSER_CACHE = new Hashtable();
-
- private ParserFactory() {} // no public ctor
+ }
/**
- * Returns the appropriate {@link Parser} implementation given a content
- * type and url.
+ * Returns the appropriate {@link Parser} implementation given a content type
+ * and url.
*
- * @deprecated Since the addition of NUTCH-88, this method is replaced by
- * taking the highest priority {@link Parser} returned from
- * {@link #getParsers(String, String)}.
+ * @deprecated Since the addition of NUTCH-88, this method is replaced by
+ * taking the highest priority {@link Parser} returned from
+ * {@link #getParsers(String, String)}.
*
* Parser extensions should define the attributes "contentType" and/or
* "pathSuffix". Content type has priority: the first plugin found whose
* "contentType" attribute matches the beginning of the content's type is
* used. If none match, then the first whose "pathSuffix" attribute matches
- * the end of the url's path is used. If neither of these match, then the
+ * the end of the url's path is used. If neither of these match, then the
* first plugin whose "pathSuffix" is the empty string is used.
*/
- public static Parser getParser(String contentType, String url)
+ public Parser getParser(String contentType, String url)
throws ParserNotFound {
Parser[] parsers = getParsers(contentType, url);
@@ -132,7 +124,7 @@ public final class ParserFactory {
* consist of two {@link Parser} interfaces,
* <code>[parse-html, parse-rtf]</code>.
*/
- public static Parser[] getParsers(String contentType, String url)
+ public Parser[] getParsers(String contentType, String url)
throws ParserNotFound {
List parsers = null;
@@ -157,14 +149,15 @@ public final class ParserFactory {
Parser p = null;
try {
//check to see if we've cached this parser instance yet
- p = (Parser) PARSER_CACHE.get(ext.getDescriptor().getPluginId());
+ p = (Parser) this.nutchConf.getObject(ext.getDescriptor().getPluginId());
if (p == null) {
// go ahead and instantiate it and then cache it
p = (Parser) ext.getExtensionInstance();
- PARSER_CACHE.put(ext.getDescriptor().getPluginId(),p);
+ this.nutchConf.setObject(ext.getDescriptor().getPluginId(),p);
}
parsers.add(p);
} catch (PluginRuntimeException e) {
+ e.printStackTrace();
LOG.warning("ParserFactory:PluginRuntimeException when "
+ "initializing parser plugin "
+ ext.getDescriptor().getPluginId()
@@ -176,61 +169,68 @@ public final class ParserFactory {
}
/**
- * <p>Function returns a {@link Parser} instance with the specified <code>parserId</code>.
- * If the Parser instance isn't found, then the function throws a <code>ParserNotFound</code>
- * exception. If the function is able to find the {@link Parser} in the internal <code>PARSER_CACHE</code>
- * then it will return the already instantiated Parser. Otherwise, if it has to instantiate the Parser itself
- * , then this function will cache that Parser in the internal <code>PARSER_CACHE</code>.
+ * <p>
+ * Function returns a {@link Parser} instance with the specified
+ * <code>parserId</code>. If the Parser instance isn't found, then the
+ * function throws a <code>ParserNotFound</code> exception. If the function
+ * is able to find the {@link Parser} in the internal
+ * <code>PARSER_CACHE</code> then it will return the already instantiated
+ * Parser. Otherwise, if it has to instantiate the Parser itself , then this
+ * function will cache that Parser in the internal <code>PARSER_CACHE</code>.
*
- * @param parserId The string ID (e.g., "parse-text", "parse-msword") of the {@link Parser} implementation to return.
- * @return A {@link Parser} implementation specified by the parameter <code>parserId</code>.
- * @throws ParserNotFound If the Parser is not found (i.e., registered with the extension point), or if the there a {@link PluginRuntimeException}
- * instantiating the {@link Parser}.
+ * @param parserId
+ * The string ID (e.g., "parse-text", "parse-msword") of the
+ * {@link Parser} implementation to return.
+ * @return A {@link Parser} implementation specified by the parameter
+ * <code>parserId</code>.
+ * @throws ParserNotFound
+ * If the Parser is not found (i.e., registered with the extension
+ * point), or if the there a {@link PluginRuntimeException}
+ * instantiating the {@link Parser}.
*/
- public static Parser getParserById(String parserId) throws ParserNotFound{
- //first check the cache
-
- if(PARSER_CACHE.get(parserId) != null){
- return (Parser)PARSER_CACHE.get(parserId);
- }
- else{
- //get the list of registered parsing extensions
- //then find the right one by Id
-
- Extension[] extensions = X_POINT.getExtensions();
- Extension parserExt = getExtensionById(extensions,parserId);
-
- if (parserExt == null) {
- throw new ParserNotFound("No Parser Found for parserId: "
- + parserId + "!");
- } else {
- // instantiate the Parser
- try {
- Parser p = null;
- p = (Parser) parserExt.getExtensionInstance();
- PARSER_CACHE
- .put(parserId, p);
- return p;
- } catch (PluginRuntimeException e) {
- LOG.warning("ParserFactory:PluginRuntimeException when "
- + "initializing parser plugin "
- + parserExt.getDescriptor().getPluginId()
- + " instance in getParserById");
- throw new ParserNotFound("No Parser Found for parserId: "
- + parserId + "!");
- }
- }
+ public Parser getParserById(String parserId) throws ParserNotFound {
+ // first check the cache
+
+ if (this.nutchConf.getObject(parserId) != null) {
+ return (Parser) this.nutchConf.getObject(parserId);
+ } else {
+ // get the list of registered parsing extensions
+ // then find the right one by Id
+
+ Extension[] extensions = this.extensionPoint.getExtensions();
+ Extension parserExt = getExtensionById(extensions, parserId);
+
+ if (parserExt == null) {
+ throw new ParserNotFound("No Parser Found for parserId: " + parserId
+ + "!");
+ } else {
+ // instantiate the Parser
+ try {
+ Parser p = null;
+ p = (Parser) parserExt.getExtensionInstance();
+ this.nutchConf.setObject(parserId, p);
+ return p;
+ } catch (PluginRuntimeException e) {
+ LOG.warning("ParserFactory:PluginRuntimeException when "
+ + "initializing parser plugin "
+ + parserExt.getDescriptor().getPluginId()
+ + " instance in getParserById");
+ throw new ParserNotFound("No Parser Found for parserId: " + parserId
+ + "!");
+ }
}
+ }
}
/**
* finds the best-suited parse plugin for a given contentType.
- *
- * @param contentType Content-Type for which we seek a parse plugin.
- * @return List - List of extensions to be used for this contentType.
- * If none, returns null.
+ *
+ * @param contentType
+ * Content-Type for which we seek a parse plugin.
+ * @return List - List of extensions to be used for this contentType. If none,
+ * returns null.
*/
- protected static List getExtensions(String contentType) {
+ protected List getExtensions(String contentType) {
// First of all, tries to clean the content-type
String type = null;
@@ -242,7 +242,7 @@ public final class ParserFactory {
type = contentType;
}
- List extensions = (List) CACHE.get(type);
+ List extensions = (List) this.nutchConf.getObject(type);
// Just compare the reference:
// if this is the empty list, we know we will find no extension.
@@ -253,11 +253,11 @@ public final class ParserFactory {
if (extensions == null) {
extensions = findExtensions(type);
if (extensions != null) {
- CACHE.put(type, extensions);
+ this.nutchConf.setObject(type, extensions);
} else {
// Put the empty extension list into cache
// to remember we don't know any related extension.
- CACHE.put(type, EMPTY_EXTENSION_LIST);
+ this.nutchConf.setObject(type, EMPTY_EXTENSION_LIST);
}
}
return extensions;
@@ -272,19 +272,19 @@ public final class ParserFactory {
* @return List - List of extensions to be used for this contentType.
* If none, returns null.
*/
- private static List findExtensions(String contentType){
+ private List findExtensions(String contentType) {
- Extension[] extensions = X_POINT.getExtensions();
+ Extension[] extensions = this.extensionPoint.getExtensions();
// Look for a preferred plugin.
- List parsePluginList = PARSE_PLUGIN_LIST.getPluginList(contentType);
+ List parsePluginList = this.parsePluginList.getPluginList(contentType);
List extensionList = matchExtensions(parsePluginList, extensions, contentType);
if (extensionList != null) {
return extensionList;
}
// If none found, look for a default plugin.
- parsePluginList = PARSE_PLUGIN_LIST.getPluginList(DEFAULT_PLUGIN);
+ parsePluginList = this.parsePluginList.getPluginList(DEFAULT_PLUGIN);
return matchExtensions(parsePluginList, extensions, DEFAULT_PLUGIN);
}
@@ -302,7 +302,7 @@ public final class ParserFactory {
* @return List - List of extensions to be used for this contentType.
* If none, returns null.
*/
- private static List matchExtensions(List plugins,
+ private List matchExtensions(List plugins,
Extension[] extensions,
String contentType) {
@@ -390,13 +390,13 @@ public final class ParserFactory {
}
}
- private static boolean match(Extension extension, String id, String type) {
+ private boolean match(Extension extension, String id, String type) {
return (id.equals(extension.getDescriptor().getPluginId())) &&
(type.equals(extension.getAttribute("contentType")) ||
(type.equals(DEFAULT_PLUGIN)));
}
- private static Extension getExtensionByIdAndType(Extension[] extList,
+ private Extension getExtensionByIdAndType(Extension[] extList,
String plugId,
String contentType) {
for (int i = 0; i < extList.length; i++) {
@@ -407,7 +407,7 @@ public final class ParserFactory {
return null;
}
- private static Extension getExtensionById(Extension[] extList, String plugId) {
+ private Extension getExtensionById(Extension[] extList, String plugId) {
for(int i = 0; i < extList.length; i++){
if(plugId.equals(extList[i].getDescriptor().getPluginId())){
return extList[i];
diff --git a/src/java/org/apache/nutch/plugin/Extension.java b/src/java/org/apache/nutch/plugin/Extension.java
index 2cb2769f3..fa57b132b 100644
--- a/src/java/org/apache/nutch/plugin/Extension.java
+++ b/src/java/org/apache/nutch/plugin/Extension.java
@@ -16,6 +16,9 @@
*/
package org.apache.nutch.plugin;
import java.util.HashMap;
+
+import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
/**
* An <code>Extension</code> is a kind of listener descriptor that will be
* installed on a concrete <code>ExtensionPoint</code> that acts as kind of
@@ -29,6 +32,8 @@ public class Extension {
private String fTargetPoint;
private String fClazz;
private HashMap fAttributes;
+ private NutchConf nutchConf;
+ private PluginRepository pluginRepository;
/**
* @param pDescriptor
* a plugin descriptor
@@ -38,12 +43,14 @@ public class Extension {
* an unique id of the plugin
*/
public Extension(PluginDescriptor pDescriptor, String pExtensionPoint,
- String pId, String pExtensionClass) {
+ String pId, String pExtensionClass, NutchConf nutchConf, PluginRepository pluginRepository) {
fAttributes = new HashMap();
setDescriptor(pDescriptor);
setExtensionPoint(pExtensionPoint);
setId(pId);
setClazz(pExtensionClass);
+ this.nutchConf = nutchConf;
+ this.pluginRepository = pluginRepository;
}
/**
* @param point
@@ -140,8 +147,11 @@ public class Extension {
Class extensionClazz = loader.loadClass(getClazz());
// lazy loading of Plugin in case there is no instance of the plugin
// already.
- PluginRepository.getInstance().getPluginInstance(getDescriptor());
+ this.pluginRepository.getPluginInstance(getDescriptor());
Object object = extensionClazz.newInstance();
+ if(object instanceof NutchConfigurable) {
+ ((NutchConfigurable)object).setConf(this.nutchConf);
+ }
return object;
} catch (ClassNotFoundException e) {
throw new PluginRuntimeException(e);
diff --git a/src/java/org/apache/nutch/plugin/PluginDescriptor.java b/src/java/org/apache/nutch/plugin/PluginDescriptor.java
index 3c665b48f..aaa4376e3 100644
--- a/src/java/org/apache/nutch/plugin/PluginDescriptor.java
+++ b/src/java/org/apache/nutch/plugin/PluginDescriptor.java
@@ -26,6 +26,7 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/**
* The <code>PluginDescriptor</code> provide access to all meta information of
* a nutch-plugin, as well to the internationalizable resources and the plugin
@@ -52,6 +53,8 @@ public class PluginDescriptor {
private PluginClassLoader fClassLoader;
public static final Logger LOG = LogFormatter
.getLogger(PluginDescriptor.class.getName());
+ private NutchConf fNutchConf;
+
/**
* Constructor
*
@@ -63,7 +66,7 @@ public class PluginDescriptor {
* @param pPath
*/
public PluginDescriptor(String pId, String pVersion, String pName,
- String pProviderName, String pPluginclazz, String pPath) {
+ String pProviderName, String pPluginclazz, String pPath, NutchConf nutchConf) {
setPath(pPath);
setPluginId(pId);
setVersion(pVersion);
@@ -73,6 +76,7 @@ public class PluginDescriptor {
if (pPluginclazz != null)
setPluginClass(pPluginclazz);
+ this.fNutchConf = nutchConf;
}
/**
* @param pPath
@@ -285,8 +289,7 @@ public class PluginDescriptor {
String[] pPluginIds = pDescriptor.getDependencies();
for (int i = 0; i < pPluginIds.length; i++) {
String id = pPluginIds[i];
- PluginDescriptor descriptor = PluginRepository.getInstance()
- .getPluginDescriptor(id);
+ PluginDescriptor descriptor = this.fNutchConf.getPluginRepository().getPluginDescriptor(id);
URL[] libs = descriptor.getExportedLibUrls();
for (int j = 0; j < libs.length; j++) {
URL url = libs[j];
diff --git a/src/java/org/apache/nutch/plugin/PluginManifestParser.java b/src/java/org/apache/nutch/plugin/PluginManifestParser.java
index cd559722e..9c982954e 100644
--- a/src/java/org/apache/nutch/plugin/PluginManifestParser.java
+++ b/src/java/org/apache/nutch/plugin/PluginManifestParser.java
@@ -52,38 +52,15 @@ public class PluginManifestParser {
private static final boolean WINDOWS = System.getProperty("os.name")
.startsWith("Windows");
- /**
- * Filters a list of plugins.
- * The list of plugins is filtered regarding the configuration
- * properties <code>plugin.excludes</code> and <code>plugin.includes</code>.
- */
- public static Map filter(Map plugins) {
- Map map = new HashMap();
- Pattern excludes = Pattern.compile(NutchConf.get().get(
- "plugin.excludes", ""));
- Pattern includes = Pattern.compile(NutchConf.get().get(
- "plugin.includes", ""));
- if (plugins == null) { return map; }
+ private NutchConf nutchConf;
- Iterator iter = plugins.values().iterator();
- while (iter.hasNext()) {
- PluginDescriptor plugin = (PluginDescriptor) iter.next();
- if (plugin == null) { continue; }
- String id = plugin.getPluginId();
- if (id == null) { continue; }
-
- if (!includes.matcher(id).matches()) {
- LOG.fine("not including: " + id);
- continue;
- }
- if (excludes.matcher(id).matches()) {
- LOG.fine("excluding: " + id);
- continue;
- }
- map.put(plugin.getPluginId(), plugin);
- }
- return map;
+ private PluginRepository pluginRepository;
+
+ public PluginManifestParser(NutchConf nutchConf, PluginRepository pluginRepository) {
+ this.nutchConf = nutchConf;
+ this.pluginRepository = pluginRepository;
}
+
/**
* Returns a list with plugin descriptors.
@@ -91,9 +68,8 @@ public class PluginManifestParser {
* @return ArrayList
*
*/
- public static Map parsePluginFolder() {
+ public Map parsePluginFolder(String[] pluginFolders) {
Map map = new HashMap();
- String[] pluginFolders = NutchConf.get().getStrings("plugin.folders");
if (pluginFolders == null) {
throw new IllegalArgumentException("plugin.folders is not defined");
@@ -136,7 +112,7 @@ public class PluginManifestParser {
* Return the named plugin folder. If the name is absolute then it is
* returned. Otherwise, for relative names, the classpath is scanned.
*/
- static File getPluginFolder(String name) {
+ public File getPluginFolder(String name) {
File directory = new File(name);
if (!directory.isAbsolute()) {
URL url = PluginManifestParser.class.getClassLoader().getResource(
@@ -168,7 +144,7 @@ public class PluginManifestParser {
* @throws SAXException
* @throws MalformedURLException
*/
- private static PluginDescriptor parseManifestFile(String pManifestPath)
+ private PluginDescriptor parseManifestFile(String pManifestPath)
throws MalformedURLException, SAXException, IOException,
ParserConfigurationException {
Document document = parseXML(new File(pManifestPath).toURL());
@@ -184,7 +160,7 @@ public class PluginManifestParser {
* @throws ParserConfigurationException
* @throws DocumentException
*/
- private static Document parseXML(URL url) throws SAXException, IOException,
+ private Document parseXML(URL url) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
@@ -195,7 +171,7 @@ public class PluginManifestParser {
* @param pDocument
* @throws MalformedURLException
*/
- private static PluginDescriptor parsePlugin(Document pDocument, String pPath)
+ private PluginDescriptor parsePlugin(Document pDocument, String pPath)
throws MalformedURLException {
Element rootElement = pDocument.getDocumentElement();
String id = rootElement.getAttribute("id");
@@ -207,7 +183,7 @@ public class PluginManifestParser {
pluginClazz = rootElement.getAttribute("class");
}
PluginDescriptor pluginDescriptor = new PluginDescriptor(id, version,
- name, providerName, pluginClazz, pPath);
+ name, providerName, pluginClazz, pPath, this.nutchConf);
LOG.fine("plugin: id="+id+" name="+name+" version="+version
+" provider="+providerName+"class="+pluginClazz);
parseExtension(rootElement, pluginDescriptor);
@@ -222,7 +198,7 @@ public class PluginManifestParser {
* @param pDescriptor
* @throws MalformedURLException
*/
- private static void parseRequires(Element pRootElement,
+ private void parseRequires(Element pRootElement,
PluginDescriptor pDescriptor)
throws MalformedURLException {
@@ -247,7 +223,7 @@ public class PluginManifestParser {
* @param pDescriptor
* @throws MalformedURLException
*/
- private static void parseLibraries(Element pRootElement,
+ private void parseLibraries(Element pRootElement,
PluginDescriptor pDescriptor) throws MalformedURLException {
NodeList nodelist = pRootElement.getElementsByTagName("runtime");
if (nodelist.getLength() > 0) {
@@ -272,7 +248,7 @@ public class PluginManifestParser {
* @param rootElement
* @param pluginDescriptor
*/
- private static void parseExtensionPoints(Element pRootElement,
+ private void parseExtensionPoints(Element pRootElement,
PluginDescriptor pPluginDescriptor) {
NodeList list = pRootElement.getElementsByTagName("extension-point");
if (list != null) {
@@ -293,7 +269,7 @@ public class PluginManifestParser {
* @param rootElement
* @param pluginDescriptor
*/
- private static void parseExtension(Element pRootElement,
+ private void parseExtension(Element pRootElement,
PluginDescriptor pPluginDescriptor) {
NodeList extensions = pRootElement.getElementsByTagName("extension");
if (extensions != null) {
@@ -316,7 +292,7 @@ public class PluginManifestParser {
LOG.fine("impl: point=" + pointId + " class="
+ extensionClass);
Extension extension = new Extension(pPluginDescriptor,
- pointId, id, extensionClass);
+ pointId, id, extensionClass, this.nutchConf, this.pluginRepository);
NamedNodeMap list = oneImplementation.getAttributes();
for (int k = 0; k < list.getLength(); k++) {
Node attribute = list.item(k);
diff --git a/src/java/org/apache/nutch/plugin/PluginRepository.java b/src/java/org/apache/nutch/plugin/PluginRepository.java
index 622a90383..f11ff2eb1 100644
--- a/src/java/org/apache/nutch/plugin/PluginRepository.java
+++ b/src/java/org/apache/nutch/plugin/PluginRepository.java
@@ -25,6 +25,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
+import java.util.regex.Pattern;
// Nutch imports
import org.apache.nutch.util.LogFormatter;
@@ -45,8 +46,7 @@ import org.apache.nutch.util.NutchConf;
*/
public class PluginRepository {
- private final static boolean AUTO =
- NutchConf.get().getBoolean("plugin.auto-activation", true);
+ private boolean auto;
private static PluginRepository fInstance;
@@ -64,16 +64,28 @@ public class PluginRepository {
* @throws PluginRuntimeException
* @see java.lang.Object#Object()
*/
- private PluginRepository() throws PluginRuntimeException{
+ public PluginRepository(NutchConf nutchConf) throws RuntimeException {
fActivatedPlugins = new HashMap();
fExtensionPoints = new HashMap();
- Map allPlugins = PluginManifestParser.parsePluginFolder();
- Map filteredPlugins = PluginManifestParser.filter(allPlugins);
+ this.auto = nutchConf.getBoolean("plugin.auto-activation", true);
+ String[] pluginFolders = nutchConf.getStrings("plugin.folders");
+ PluginManifestParser manifestParser = new PluginManifestParser(nutchConf, this);
+ Map allPlugins =manifestParser.parsePluginFolder(pluginFolders);
+ Pattern excludes = Pattern.compile(nutchConf.get(
+ "plugin.excludes", ""));
+ Pattern includes = Pattern.compile(nutchConf.get(
+ "plugin.includes", ""));
+ Map filteredPlugins = filter(excludes, includes, allPlugins);
fRegisteredPlugins = getDependencyCheckedPlugins(
filteredPlugins,
- AUTO ? allPlugins : filteredPlugins);
+ this.auto ? allPlugins : filteredPlugins);
installExtensionPoints(fRegisteredPlugins);
- installExtensions(fRegisteredPlugins);
+ try {
+ installExtensions(fRegisteredPlugins);
+ } catch (PluginRuntimeException e) {
+ LOG.severe(e.toString());
+ throw new RuntimeException(e.getMessage());
+ }
displayStatus();
}
@@ -204,21 +216,6 @@ public class PluginRepository {
return false;
}
- /**
- * Returns the singelton instance of the <code>PluginRepository</code>
- */
- public static synchronized PluginRepository getInstance() {
- if (fInstance != null)
- return fInstance;
- try {
- fInstance = new PluginRepository();
- } catch (Exception e) {
- LOG.severe(e.toString());
- throw new RuntimeException(e);
- }
- return fInstance;
- }
-
/**
* Returns all registed plugin descriptors.
*
@@ -249,9 +246,10 @@ public class PluginRepository {
* Returns a extension point indentified by a extension point id.
*
* @param pXpId
+ * @return a extentsion point
*/
public ExtensionPoint getExtensionPoint(String pXpId) {
- return (ExtensionPoint) fExtensionPoints.get(pXpId);
+ return (ExtensionPoint) this.fExtensionPoints.get(pXpId);
}
/**
@@ -325,7 +323,7 @@ public class PluginRepository {
private void displayStatus() {
- LOG.info("Plugin Auto-activation mode: [" + AUTO + "]");
+ LOG.info("Plugin Auto-activation mode: [" + this.auto + "]");
LOG.info("Registered Plugins:");
if ((fRegisteredPlugins == null) || (fRegisteredPlugins.size() == 0)) {
@@ -348,4 +346,32 @@ public class PluginRepository {
}
}
}
+ /**
+ * Filters a list of plugins.
+ * The list of plugins is filtered regarding the configuration
+ * properties <code>plugin.excludes</code> and <code>plugin.includes</code>.
+ */
+ private Map filter(Pattern excludes, Pattern includes, Map plugins) {
+ Map map = new HashMap();
+ if (plugins == null) { return map; }
+
+ Iterator iter = plugins.values().iterator();
+ while (iter.hasNext()) {
+ PluginDescriptor plugin = (PluginDescriptor) iter.next();
+ if (plugin == null) { continue; }
+ String id = plugin.getPluginId();
+ if (id == null) { continue; }
+
+ if (!includes.matcher(id).matches()) {
+ LOG.fine("not including: " + id);
+ continue;
+ }
+ if (excludes.matcher(id).matches()) {
+ LOG.fine("excluding: " + id);
+ continue;
+ }
+ map.put(plugin.getPluginId(), plugin);
+ }
+ return map;
+ }
}
diff --git a/src/java/org/apache/nutch/protocol/Content.java b/src/java/org/apache/nutch/protocol/Content.java
index ce85c92e2..c7cbdcdfa 100755
--- a/src/java/org/apache/nutch/protocol/Content.java
+++ b/src/java/org/apache/nutch/protocol/Content.java
@@ -32,25 +32,19 @@ public final class Content extends CompressedWritable {
private final static byte VERSION = 1;
- /** A flag that tells if magic resolution must be performed */
- private final static boolean MAGIC =
- NutchConf.get().getBoolean("mime.type.magic", true);
-
- /** Get the MimeTypes resolver instance. */
- private final static MimeTypes MIME =
- MimeTypes.get(NutchConf.get().get("mime.types.file"));
-
private byte version;
private String url;
private String base;
private byte[] content;
private String contentType;
private ContentProperties metadata;
+ private boolean mimeTypeMagic;
+ private MimeTypes mimeTypes;
public Content() {}
public Content(String url, String base, byte[] content, String contentType,
- ContentProperties metadata){
+ ContentProperties metadata, NutchConf nutchConf) {
if (url == null) throw new IllegalArgumentException("null url");
if (base == null) throw new IllegalArgumentException("null base");
@@ -60,8 +54,10 @@ public final class Content extends CompressedWritable {
this.url = url;
this.base = base;
this.content = content;
- this.contentType = getContentType(contentType, url, content);
this.metadata = metadata;
+ this.mimeTypeMagic = nutchConf.getBoolean("mime.type.magic", true);
+ this.mimeTypes = MimeTypes.get(nutchConf.get("mime.types.file"));
+ this.contentType = getContentType(contentType, url, content);
}
protected final void readFieldsCompressed(DataInput in) throws IOException {
@@ -192,8 +188,8 @@ public final class Content extends CompressedWritable {
System.out.println("usage:" + usage);
return;
}
-
- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0);
+ NutchConf nutchConf = new NutchConf();
+ NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0, nutchConf);
try {
int recno = Integer.parseInt(argv[0]);
String segment = argv[1];
@@ -201,7 +197,7 @@ public final class Content extends CompressedWritable {
File file = new File(segment, DIR_NAME);
System.out.println("Reading from file: " + file);
- ArrayFile.Reader contents = new ArrayFile.Reader(nfs, file.toString());
+ ArrayFile.Reader contents = new ArrayFile.Reader(nfs, file.toString(), nutchConf);
Content content = new Content();
contents.get(recno, content);
@@ -216,11 +212,10 @@ public final class Content extends CompressedWritable {
}
private String getContentType(String typeName, String url, byte[] data) {
-
MimeType type = null;
try {
typeName = MimeType.clean(typeName);
- type = typeName == null ? null : MIME.forName(typeName);
+ type = typeName == null ? null : this.mimeTypes.forName(typeName);
} catch (MimeTypeException mte) {
// Seems to be a malformed mime type name...
}
@@ -229,15 +224,15 @@ public final class Content extends CompressedWritable {
// If no mime-type header, or cannot find a corresponding registered
// mime-type, or the one found doesn't match the url pattern
// it shouldbe, then guess a mime-type from the url pattern
- type = MIME.getMimeType(url);
+ type = this.mimeTypes.getMimeType(url);
typeName = type == null ? typeName : type.getName();
}
if (typeName == null || type == null ||
- (MAGIC && type.hasMagic() && !type.matches(data))) {
+ (this.mimeTypeMagic && type.hasMagic() && !type.matches(data))) {
// If no mime-type already found, or the one found doesn't match
// the magic bytes it should be, then, guess a mime-type from the
// document content (magic bytes)
- type = MIME.getMimeType(data);
+ type = this.mimeTypes.getMimeType(data);
typeName = type == null ? typeName : type.getName();
}
return typeName;
diff --git a/src/java/org/apache/nutch/protocol/Protocol.java b/src/java/org/apache/nutch/protocol/Protocol.java
index 3f945d45c..4c7829efa 100755
--- a/src/java/org/apache/nutch/protocol/Protocol.java
+++ b/src/java/org/apache/nutch/protocol/Protocol.java
@@ -20,9 +20,10 @@ import java.io.IOException;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.io.UTF8;
+import org.apache.nutch.util.NutchConfigurable;
/** A retriever of url content. Implemented by protocol extensions. */
-public interface Protocol {
+public interface Protocol extends NutchConfigurable {
/** The name of the extension point. */
public final static String X_POINT_ID = Protocol.class.getName();
diff --git a/src/java/org/apache/nutch/protocol/ProtocolFactory.java b/src/java/org/apache/nutch/protocol/ProtocolFactory.java
index 5ba3acaab..ac348e797 100644
--- a/src/java/org/apache/nutch/protocol/ProtocolFactory.java
+++ b/src/java/org/apache/nutch/protocol/ProtocolFactory.java
@@ -24,6 +24,7 @@ import org.apache.nutch.plugin.*;
import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/** Creates and caches {@link Protocol} plugins. Protocol plugins should
* define the attribute "protocolName" with the name of the protocol that they
@@ -33,21 +34,20 @@ public class ProtocolFactory {
public static final Logger LOG = LogFormatter
.getLogger(ProtocolFactory.class.getName());
- private final static ExtensionPoint X_POINT = PluginRepository.getInstance()
- .getExtensionPoint(Protocol.X_POINT_ID);
-
- static {
- if (X_POINT == null) {
- throw new RuntimeException("x-point "+Protocol.X_POINT_ID+" not found.");
- }
- }
+ private ExtensionPoint extensionPoint;
+ private NutchConf nutchConf;
- private static final Hashtable CACHE = new Hashtable();
-
- private ProtocolFactory() {} // no public ctor
+ public ProtocolFactory(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ this.extensionPoint = nutchConf.getPluginRepository()
+ .getExtensionPoint(Protocol.X_POINT_ID);
+ if (this.extensionPoint == null) {
+ throw new RuntimeException("x-point " + Protocol.X_POINT_ID + " not found.");
+ }
+ }
/** Returns the appropriate {@link Protocol} implementation for a url. */
- public static Protocol getProtocol(String urlString)
+ public Protocol getProtocol(String urlString)
throws ProtocolNotFound {
try {
URL url = new URL(urlString);
@@ -57,8 +57,9 @@ public class ProtocolFactory {
Extension extension = getExtension(protocolName);
if (extension == null)
throw new ProtocolNotFound(protocolName);
-
- return (Protocol)extension.getExtensionInstance();
+ Protocol protocol = (Protocol) extension.getExtensionInstance();
+ protocol.setConf(this.nutchConf);
+ return protocol;
} catch (MalformedURLException e) {
throw new ProtocolNotFound(urlString, e.toString());
@@ -67,23 +68,23 @@ public class ProtocolFactory {
}
}
- private static Extension getExtension(String name)
+ private Extension getExtension(String name)
throws PluginRuntimeException {
- if (CACHE.containsKey(name))
- return (Extension)CACHE.get(name);
+ if (this.nutchConf.getObject(name) != null)
+ return (Extension)this.nutchConf.getObject(name);
Extension extension = findExtension(name);
- if (extension != null) CACHE.put(name, extension);
+ if (extension != null) this.nutchConf.setObject(name, extension);
return extension;
}
- private static Extension findExtension(String name)
+ private Extension findExtension(String name)
throws PluginRuntimeException {
- Extension[] extensions = X_POINT.getExtensions();
+ Extension[] extensions = this.extensionPoint.getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
diff --git a/src/java/org/apache/nutch/searcher/DistributedSearch.java b/src/java/org/apache/nutch/searcher/DistributedSearch.java
index 57ef3e0fa..4e3db4113 100644
--- a/src/java/org/apache/nutch/searcher/DistributedSearch.java
+++ b/src/java/org/apache/nutch/searcher/DistributedSearch.java
@@ -26,6 +26,7 @@ import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseText;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.*;
import org.apache.nutch.ipc.RPC;
@@ -61,9 +62,10 @@ public class DistributedSearch {
int port = Integer.parseInt(args[0]);
File directory = new File(args[1]);
- NutchBean bean = new NutchBean(directory);
+ NutchConf nutchConf = new NutchConf();
+ NutchBean bean = new NutchBean(nutchConf, directory);
- org.apache.nutch.ipc.Server server = RPC.getServer(bean, port, 10, true);
+ org.apache.nutch.ipc.Server server = RPC.getServer(bean, port, 10, true, nutchConf);
server.start();
server.join();
}
@@ -80,14 +82,15 @@ public class DistributedSearch {
private HashMap segmentToAddress = new HashMap();
private boolean running = true;
+ private NutchConf nutchConf;
/** Construct a client talking to servers listed in the named file.
* Each line in the file lists a server hostname and port, separated by
* whitespace.
*/
- public Client(File file) throws IOException {
- this(readConfig(file));
+ public Client(File file, NutchConf nutchConf) throws IOException {
+ this(readConfig(file), nutchConf);
}
private static InetSocketAddress[] readConfig(File config)
@@ -111,11 +114,12 @@ public class DistributedSearch {
}
/** Construct a client talking to the named servers. */
- public Client(InetSocketAddress[] addresses) throws IOException {
+ public Client(InetSocketAddress[] addresses, NutchConf nutchConf) throws IOException {
this.defaultAddresses = addresses;
updateSegments();
setDaemon(true);
start();
+ this.nutchConf = nutchConf;
}
private static final Method GET_SEGMENTS;
@@ -152,7 +156,7 @@ public class DistributedSearch {
// build segmentToAddress map
Object[][] params = new Object[defaultAddresses.length][0];
String[][] results =
- (String[][])RPC.call(GET_SEGMENTS, params, defaultAddresses);
+ (String[][])RPC.call(GET_SEGMENTS, params, defaultAddresses, this.nutchConf);
for (int i = 0; i < results.length; i++) { // process results of call
InetSocketAddress addr = defaultAddresses[i];
@@ -196,7 +200,7 @@ public class DistributedSearch {
params[i][3] = sortField;
params[i][4] = Boolean.valueOf(reverse);
}
- Hits[] results = (Hits[])RPC.call(SEARCH, params, liveAddresses);
+ Hits[] results = (Hits[])RPC.call(SEARCH, params, liveAddresses, this.nutchConf);
TreeSet queue; // cull top hits from results
@@ -235,13 +239,13 @@ public class DistributedSearch {
private Protocol getRemote(Hit hit) {
return (Protocol)
- RPC.getProxy(Protocol.class, liveAddresses[hit.getIndexNo()]);
+ RPC.getProxy(Protocol.class, liveAddresses[hit.getIndexNo()], nutchConf);
}
private Protocol getRemote(HitDetails hit) {
InetSocketAddress address =
(InetSocketAddress)segmentToAddress.get(hit.getValue("segment"));
- return (Protocol)RPC.getProxy(Protocol.class, address);
+ return (Protocol)RPC.getProxy(Protocol.class, address, nutchConf);
}
public String getExplanation(Query query, Hit hit) throws IOException {
@@ -259,7 +263,7 @@ public class DistributedSearch {
addrs[i] = liveAddresses[hits[i].getIndexNo()];
params[i][0] = hits[i];
}
- return (HitDetails[])RPC.call(DETAILS, params, addrs);
+ return (HitDetails[])RPC.call(DETAILS, params, addrs, nutchConf);
}
@@ -278,7 +282,7 @@ public class DistributedSearch {
params[i][0] = hit;
params[i][1] = query;
}
- return (String[])RPC.call(SUMMARY, params, addrs);
+ return (String[])RPC.call(SUMMARY, params, addrs, nutchConf);
}
public byte[] getContent(HitDetails hit) throws IOException {
@@ -313,7 +317,7 @@ public class DistributedSearch {
System.exit(-1);
}
- Query query = Query.parse(args[0]);
+ Query query = Query.parse(args[0], new NutchConf());
InetSocketAddress[] addresses = new InetSocketAddress[(args.length-1)/2];
for (int i = 0; i < (args.length-1)/2; i++) {
@@ -321,7 +325,7 @@ public class DistributedSearch {
new InetSocketAddress(args[i*2+1], Integer.parseInt(args[i*2+2]));
}
- Client client = new Client(addresses);
+ Client client = new Client(addresses, new NutchConf());
//client.setTimeout(Integer.MAX_VALUE);
Hits hits = client.search(query, 10, null, null, false);
diff --git a/src/java/org/apache/nutch/searcher/FetchedSegments.java b/src/java/org/apache/nutch/searcher/FetchedSegments.java
index 4b0c85978..f5a4cc194 100644
--- a/src/java/org/apache/nutch/searcher/FetchedSegments.java
+++ b/src/java/org/apache/nutch/searcher/FetchedSegments.java
@@ -25,6 +25,7 @@ import org.apache.nutch.io.*;
import org.apache.nutch.fs.*;
import org.apache.nutch.protocol.*;
import org.apache.nutch.parse.*;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.mapred.*;
import org.apache.nutch.mapred.lib.*;
import org.apache.nutch.crawl.*;
@@ -43,10 +44,12 @@ public class FetchedSegments implements HitSummarizer, HitContent {
private MapFile.Reader[] parseText;
private MapFile.Reader[] parseData;
private MapFile.Reader[] crawl;
+ private NutchConf nutchConf;
- public Segment(NutchFileSystem nfs, File segmentDir) throws IOException {
+ public Segment(NutchFileSystem nfs, File segmentDir, NutchConf nutchConf) throws IOException {
this.nfs = nfs;
this.segmentDir = segmentDir;
+ this.nutchConf = nutchConf;
}
public CrawlDatum getCrawlDatum(UTF8 url) throws IOException {
@@ -82,7 +85,7 @@ public class FetchedSegments implements HitSummarizer, HitContent {
}
private MapFile.Reader[] getReaders(String subDir) throws IOException {
- return MapFileOutputFormat.getReaders(nfs, new File(segmentDir, subDir));
+ return MapFileOutputFormat.getReaders(nfs, new File(segmentDir, subDir), this.nutchConf);
}
private Writable getEntry(MapFile.Reader[] readers, UTF8 url,
@@ -93,10 +96,16 @@ public class FetchedSegments implements HitSummarizer, HitContent {
}
private HashMap segments = new HashMap();
+ private int sumContext = 5;
+ private int sumLength = 20;
+ private Summarizer summarizer;
/** Construct given a directory containing fetcher output. */
- public FetchedSegments(NutchFileSystem nfs, String segmentsDir) throws IOException {
+ public FetchedSegments(NutchFileSystem nfs, String segmentsDir, NutchConf nutchConf) throws IOException {
File[] segmentDirs = nfs.listFiles(new File(segmentsDir));
+ this.sumContext = nutchConf.getInt("searcher.summary.context", 5);
+ this.sumLength = nutchConf.getInt("searcher.summary.length", 20);
+ this.summarizer = new Summarizer(nutchConf);
if (segmentDirs != null) {
for (int i = 0; i < segmentDirs.length; i++) {
@@ -105,7 +114,7 @@ public class FetchedSegments implements HitSummarizer, HitContent {
// if (nfs.exists(indexdone) && nfs.isFile(indexdone)) {
// segments.put(segmentDir.getName(), new Segment(nfs, segmentDir));
// }
- segments.put(segmentDir.getName(), new Segment(nfs, segmentDir));
+ segments.put(segmentDir.getName(), new Segment(nfs, segmentDir, nutchConf));
}
}
@@ -137,7 +146,7 @@ public class FetchedSegments implements HitSummarizer, HitContent {
String text = getSegment(details).getParseText(getUrl(details)).getText();
- return new Summarizer().getSummary(text, query).toString();
+ return this.summarizer.getSummary(text, query, this.sumContext, this.sumLength).toString();
}
private class SummaryThread extends Thread {
diff --git a/src/java/org/apache/nutch/searcher/FieldQueryFilter.java b/src/java/org/apache/nutch/searcher/FieldQueryFilter.java
index 3c8e2b0d4..78b15150b 100644
--- a/src/java/org/apache/nutch/searcher/FieldQueryFilter.java
+++ b/src/java/org/apache/nutch/searcher/FieldQueryFilter.java
@@ -25,12 +25,15 @@ import org.apache.nutch.analysis.CommonGrams;
import org.apache.nutch.searcher.Query.Clause;
import org.apache.nutch.searcher.Query.Phrase;
+import org.apache.nutch.util.NutchConf;
/** Translate query fields to search the same-named field, as indexed by an
* IndexingFilter. Best for tokenized fields. */
public abstract class FieldQueryFilter implements QueryFilter {
private String field;
private float boost = 1.0f;
+ private NutchConf nutchConf;
+ private CommonGrams commonGrams;
/** Construct for the named field.*/
protected FieldQueryFilter(String field) {
@@ -57,12 +60,12 @@ public abstract class FieldQueryFilter implements QueryFilter {
// optimize phrase clause
if (c.isPhrase()) {
- String[] opt = CommonGrams.optimizePhrase(c.getPhrase(), field);
+ String[] opt = this.commonGrams.optimizePhrase(c.getPhrase(), field);
if (opt.length==1) {
c = new Clause(new Query.Term(opt[0]),
- c.isRequired(), c.isProhibited());
+ c.isRequired(), c.isProhibited(), getConf());
} else {
- c = new Clause(new Phrase(opt), c.isRequired(), c.isProhibited());
+ c = new Clause(new Phrase(opt), c.isRequired(), c.isProhibited(), getConf());
}
}
@@ -89,4 +92,13 @@ public abstract class FieldQueryFilter implements QueryFilter {
// return the modified Lucene query
return output;
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.commonGrams = new CommonGrams(conf);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/java/org/apache/nutch/searcher/IndexSearcher.java b/src/java/org/apache/nutch/searcher/IndexSearcher.java
index d9e457304..4b90ff0a5 100644
--- a/src/java/org/apache/nutch/searcher/IndexSearcher.java
+++ b/src/java/org/apache/nutch/searcher/IndexSearcher.java
@@ -47,38 +47,43 @@ public class IndexSearcher implements Searcher, HitDetailer {
private org.apache.lucene.search.Searcher luceneSearcher;
private org.apache.lucene.index.IndexReader reader;
-
- private LuceneQueryOptimizer optimizer = new LuceneQueryOptimizer
- (NutchConf.get().getInt("searcher.filter.cache.size", 16),
- NutchConf.get().getFloat("searcher.filter.cache.threshold", 0.05f));
+ private LuceneQueryOptimizer optimizer;
+ private NutchFileSystem fs;
+ private NutchConf nutchConf;
+ private QueryFilters queryFilters;
/** Construct given a number of indexes. */
- public IndexSearcher(File[] indexDirs) throws IOException {
+ public IndexSearcher(File[] indexDirs, NutchConf nutchConf) throws IOException {
IndexReader[] readers = new IndexReader[indexDirs.length];
+ this.nutchConf = nutchConf;
+ this.fs = NutchFileSystem.get(nutchConf);
for (int i = 0; i < indexDirs.length; i++) {
readers[i] = IndexReader.open(getDirectory(indexDirs[i]));
}
- init(new MultiReader(readers));
+ init(new MultiReader(readers), nutchConf);
}
/** Construct given a single merged index. */
- public IndexSearcher(File index)
+ public IndexSearcher(File index, NutchConf nutchConf)
throws IOException {
- init(IndexReader.open(getDirectory(index)));
+ this.nutchConf = nutchConf;
+ this.fs = NutchFileSystem.get(nutchConf);
+ init(IndexReader.open(getDirectory(index)), nutchConf);
}
- private void init(IndexReader reader) throws IOException {
+ private void init(IndexReader reader, NutchConf nutchConf) throws IOException {
this.reader = reader;
this.luceneSearcher = new org.apache.lucene.search.IndexSearcher(reader);
this.luceneSearcher.setSimilarity(new NutchSimilarity());
+ this.optimizer = new LuceneQueryOptimizer(nutchConf);
+ this.queryFilters = new QueryFilters(nutchConf);
}
private Directory getDirectory(File file) throws IOException {
- NutchFileSystem fs = NutchFileSystem.get();
- if ("local".equals(fs.getName())) {
+ if ("local".equals(this.fs.getName())) {
return FSDirectory.getDirectory(file, false);
} else {
- return new NdfsDirectory(fs, file, false);
+ return new NdfsDirectory(this.fs, file, false, this.nutchConf);
}
}
@@ -86,10 +91,8 @@ public class IndexSearcher implements Searcher, HitDetailer {
String dedupField, String sortField, boolean reverse)
throws IOException {
-
org.apache.lucene.search.BooleanQuery luceneQuery =
- QueryFilters.filter(query);
-
+ this.queryFilters.filter(query);
return translateHits
(optimizer.optimize(luceneQuery, luceneSearcher, numHits,
sortField, reverse),
@@ -97,7 +100,7 @@ public class IndexSearcher implements Searcher, HitDetailer {
}
public String getExplanation(Query query, Hit hit) throws IOException {
- return luceneSearcher.explain(QueryFilters.filter(query),
+ return luceneSearcher.explain(this.queryFilters.filter(query),
hit.getIndexDocNo()).toHtml();
}
diff --git a/src/java/org/apache/nutch/searcher/LinkDbInlinks.java b/src/java/org/apache/nutch/searcher/LinkDbInlinks.java
index d76d3b582..13925a50f 100644
--- a/src/java/org/apache/nutch/searcher/LinkDbInlinks.java
+++ b/src/java/org/apache/nutch/searcher/LinkDbInlinks.java
@@ -11,6 +11,7 @@ import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.crawl.LinkDbReader;
import org.apache.nutch.fs.NutchFileSystem;
import org.apache.nutch.io.UTF8;
+import org.apache.nutch.util.NutchConf;
import java.io.File;
@@ -18,8 +19,8 @@ public class LinkDbInlinks implements HitInlinks {
private LinkDbReader linkdb = null;
- public LinkDbInlinks(NutchFileSystem fs, File dir) {
- linkdb = new LinkDbReader(fs, dir);
+ public LinkDbInlinks(NutchFileSystem fs, File dir, NutchConf nutchConf) {
+ linkdb = new LinkDbReader(fs, dir, nutchConf);
}
public String[] getAnchors(HitDetails details) throws IOException {
diff --git a/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.java b/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.java
index 3b1f6ed9e..b66ba67cb 100644
--- a/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.java
+++ b/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.java
@@ -37,8 +37,6 @@ import java.io.IOException;
* which do not affect ranking but might otherwise slow search considerably. */
class LuceneQueryOptimizer {
- private static int MAX_HITS = NutchConf.get().getInt("searcher.max.hits",-1);
-
private static class LimitExceeded extends RuntimeException {
private int maxDoc;
public LimitExceeded(int maxDoc) { this.maxDoc = maxDoc; }
@@ -63,18 +61,28 @@ class LuceneQueryOptimizer {
private float threshold;
- /** Construct an optimizer that caches and uses filters for required clauses
+ private int searcherMaxHits;
+
+ /**
+ * Construct an optimizer that caches and uses filters for required clauses
* whose boost is zero.
- * @param cacheSize the number of QueryFilters to cache
- * @param threshold the fraction of documents which must contain a term
+ *
+ * @param cacheSize
+ * the number of QueryFilters to cache
+ * @param threshold
+ * the fraction of documents which must contain a term
*/
- public LuceneQueryOptimizer(final int cacheSize, float threshold) {
+ public LuceneQueryOptimizer(NutchConf nutchConf) {
+ final int cacheSize = nutchConf.getInt("searcher.filter.cache.size", 16);
+ this.threshold = nutchConf.getFloat("searcher.filter.cache.threshold",
+ 0.05f);
+ this.searcherMaxHits = nutchConf.getInt("searcher.max.hits", -1);
+ this.searcherMaxHits = searcherMaxHits;
this.cache = new LinkedHashMap(cacheSize, 0.75f, true) {
- protected boolean removeEldestEntry(Map.Entry eldest) {
- return size() > cacheSize; // limit size of cache
- }
- };
- this.threshold = threshold;
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ return size() > cacheSize; // limit size of cache
+ }
+ };
}
public TopDocs optimize(BooleanQuery original,
@@ -123,7 +131,6 @@ class LuceneQueryOptimizer {
}
Filter filter = null;
-
if (cacheQuery.getClauses().length != 0) {
synchronized (cache) { // check cache
filter = (Filter)cache.get(cacheQuery);
@@ -151,12 +158,12 @@ class LuceneQueryOptimizer {
if (sortField == null && !reverse) {
// no hit limit
- if (MAX_HITS <= 0) {
+ if (this.searcherMaxHits <= 0) {
return searcher.search(query, filter, numHits);
}
// hits limited -- use a LimitedCollector
- LimitedCollector collector = new LimitedCollector(numHits, MAX_HITS);
+ LimitedCollector collector = new LimitedCollector(numHits, searcherMaxHits);
LimitExceeded exceeded = null;
try {
searcher.search(query, filter, collector);
diff --git a/src/java/org/apache/nutch/searcher/NutchBean.java b/src/java/org/apache/nutch/searcher/NutchBean.java
index 1d46f08e9..9e3f1fb43 100644
--- a/src/java/org/apache/nutch/searcher/NutchBean.java
+++ b/src/java/org/apache/nutch/searcher/NutchBean.java
@@ -42,8 +42,6 @@ public class NutchBean
LogFormatter.setShowThreadIDs(true);
}
- private NutchFileSystem fs = NutchFileSystem.get();
-
private String[] segmentNames;
private Searcher searcher;
@@ -52,50 +50,65 @@ public class NutchBean
private HitContent content;
private HitInlinks linkDb;
- private float RAW_HITS_FACTOR =
- NutchConf.get().getFloat("searcher.hostgrouping.rawhits.factor", 2.0f);
/** BooleanQuery won't permit more than 32 required/prohibited clauses. We
* don't want to use too many of those. */
private static final int MAX_PROHIBITED_TERMS = 20;
+
+ private NutchConf nutchConf;
+
+ private NutchFileSystem fs;
/** Cache in servlet context. */
- public static NutchBean get(ServletContext app) throws IOException {
+ public static NutchBean get(ServletContext app, NutchConf conf) throws IOException {
NutchBean bean = (NutchBean)app.getAttribute("nutchBean");
if (bean == null) {
LOG.info("creating new bean");
- bean = new NutchBean();
+ bean = new NutchBean(conf);
app.setAttribute("nutchBean", bean);
}
return bean;
}
- /** Construct reading from connected directory. */
- public NutchBean() throws IOException {
- this(new File(NutchConf.get().get("searcher.dir", "crawl")));
- }
- /** Construct in a named directory. */
- public NutchBean(File dir) throws IOException {
- File servers = new File(dir, "search-servers.txt");
- if (fs.exists(servers)) {
- LOG.info("searching servers in " + servers.getCanonicalPath());
- init(new DistributedSearch.Client(servers));
- } else {
- init(new File(dir, "index"),
- new File(dir, "indexes"),
- new File(dir, "segments"),
- new File(dir, "linkdb"));
- }
+ /**
+ *
+ * @param nutchConf
+ * @throws IOException
+ */
+ public NutchBean(NutchConf nutchConf) throws IOException {
+ this(nutchConf, null);
}
+
+ /**
+ * Construct in a named directory.
+ * @param nutchConf
+ * @param dir
+ * @throws IOException
+ */
+ public NutchBean(NutchConf nutchConf, File dir) throws IOException {
+ this.nutchConf = nutchConf;
+ this.fs = NutchFileSystem.get(this.nutchConf);
+ if (dir == null) {
+ dir = new File(this.nutchConf.get("searcher.dir", "crawl"));
+ }
+ File servers = new File(dir, "search-servers.txt");
+ if (fs.exists(servers)) {
+ LOG.info("searching servers in " + servers.getCanonicalPath());
+ init(new DistributedSearch.Client(servers, nutchConf));
+ } else {
+ init(new File(dir, "index"), new File(dir, "indexes"), new File(
+ dir, "segments"), new File(dir, "linkdb"));
+ }
+ }
private void init(File indexDir, File indexesDir, File segmentsDir,
File linkDb)
throws IOException {
IndexSearcher indexSearcher;
- if (fs.exists(indexDir)) {
+ if (this.fs.exists(indexDir)) {
LOG.info("opening merged index in " + indexDir);
- indexSearcher = new IndexSearcher(indexDir);
+ indexSearcher = new IndexSearcher(indexDir, this.nutchConf);
} else {
LOG.info("opening indexes in " + indexesDir);
@@ -108,16 +121,17 @@ public class NutchBean
}
}
+
directories = new File[ vDirs.size() ];
for(int i = 0; vDirs.size()>0; i++) {
directories[i]=(File)vDirs.remove(0);
}
- indexSearcher = new IndexSearcher(directories);
+ indexSearcher = new IndexSearcher(directories, this.nutchConf);
}
LOG.info("opening segments in " + segmentsDir);
- FetchedSegments segments = new FetchedSegments(fs, segmentsDir.toString());
+ FetchedSegments segments = new FetchedSegments(this.fs, segmentsDir.toString(),this.nutchConf);
this.segmentNames = segments.getSegmentNames();
@@ -127,7 +141,7 @@ public class NutchBean
this.content = segments;
LOG.info("opening linkdb in " + linkDb);
- this.linkDb = new LinkDbInlinks(fs, linkDb);
+ this.linkDb = new LinkDbInlinks(fs, linkDb, this.nutchConf);
}
private void init(DistributedSearch.Client client) {
@@ -216,7 +230,8 @@ public class NutchBean
if (maxHitsPerDup <= 0) // disable dup checking
return search(query, numHits, dedupField, sortField, reverse);
- int numHitsRaw = (int)(numHits * RAW_HITS_FACTOR);
+ float rawHitsFactor = this.nutchConf.getFloat("searcher.hostgrouping.rawhits.factor", 2.0f);
+ int numHitsRaw = (int)(numHits * rawHitsFactor);
LOG.info("searching for "+numHitsRaw+" raw hits");
Hits hits = searcher.search(query, numHitsRaw,
dedupField, sortField, reverse);
@@ -237,7 +252,7 @@ public class NutchBean
optQuery.addProhibitedTerm(((String)excludedValues.get(i)),
dedupField);
}
- numHitsRaw = (int)(numHitsRaw * RAW_HITS_FACTOR);
+ numHitsRaw = (int)(numHitsRaw * rawHitsFactor);
LOG.info("re-searching for "+numHitsRaw+" raw hits, query: "+optQuery);
hits = searcher.search(optQuery, numHitsRaw,
dedupField, sortField, reverse);
@@ -344,9 +359,9 @@ public class NutchBean
System.exit(-1);
}
- NutchBean bean = new NutchBean();
- Query query = Query.parse(args[0]);
-
+ NutchConf nutchConf = new NutchConf();
+ NutchBean bean = new NutchBean(nutchConf);
+ Query query = Query.parse(args[0], nutchConf);
Hits hits = bean.search(query, 10);
System.out.println("Total hits: " + hits.getTotal());
int length = (int)Math.min(hits.getTotal(), 10);
diff --git a/src/java/org/apache/nutch/searcher/OpenSearchServlet.java b/src/java/org/apache/nutch/searcher/OpenSearchServlet.java
index df1708236..2be5a0223 100644
--- a/src/java/org/apache/nutch/searcher/OpenSearchServlet.java
+++ b/src/java/org/apache/nutch/searcher/OpenSearchServlet.java
@@ -31,6 +31,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.*;
+
+import org.apache.nutch.util.NutchConf;
import org.w3c.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
@@ -55,10 +57,12 @@ public class OpenSearchServlet extends HttpServlet {
}
private NutchBean bean;
+ private NutchConf nutchConf;
- public void init(ServletConfig config) throws ServletException {
+ public void init(ServletConfig config, NutchConf nutchConf) throws ServletException {
try {
- bean = NutchBean.get(config.getServletContext());
+ bean = NutchBean.get(config.getServletContext(), nutchConf);
+ this.nutchConf = nutchConf;
} catch (IOException e) {
throw new ServletException(e);
}
@@ -114,7 +118,7 @@ public class OpenSearchServlet extends HttpServlet {
(sort == null ? "" : "&sort=" + sort + (reverse? "&reverse=true": "") +
(dedupField == null ? "" : "&dedupField=" + dedupField));
- Query query = Query.parse(queryString);
+ Query query = Query.parse(queryString, this.nutchConf);
NutchBean.LOG.info("query: " + queryString);
// execute the query
diff --git a/src/java/org/apache/nutch/searcher/Query.java b/src/java/org/apache/nutch/searcher/Query.java
index ae56ccc54..f46a7df6c 100644
--- a/src/java/org/apache/nutch/searcher/Query.java
+++ b/src/java/org/apache/nutch/searcher/Query.java
@@ -26,6 +26,7 @@ import java.util.ArrayList;
import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.analysis.NutchAnalysis;
import org.apache.nutch.io.Writable;
@@ -47,30 +48,34 @@ public final class Query implements Writable, Cloneable {
private boolean isProhibited;
private String field = DEFAULT_FIELD;
private float weight = 1.0f;
- private Object termOrPhrase;
+ private Object termOrPhrase;
+
+ private NutchConf nutchConf;
public Clause(Term term, String field,
- boolean isRequired, boolean isProhibited) {
- this(term, isRequired, isProhibited);
+ boolean isRequired, boolean isProhibited, NutchConf nutchConf) {
+ this(term, isRequired, isProhibited, nutchConf);
this.field = field;
}
- public Clause(Term term, boolean isRequired, boolean isProhibited) {
+ public Clause(Term term, boolean isRequired, boolean isProhibited, NutchConf nutchConf) {
this.isRequired = isRequired;
this.isProhibited = isProhibited;
this.termOrPhrase = term;
+ this.nutchConf = nutchConf;
}
public Clause(Phrase phrase, String field,
- boolean isRequired, boolean isProhibited) {
- this(phrase, isRequired, isProhibited);
+ boolean isRequired, boolean isProhibited, NutchConf nutchConf) {
+ this(phrase, isRequired, isProhibited, nutchConf);
this.field = field;
}
- public Clause(Phrase phrase, boolean isRequired, boolean isProhibited) {
+ public Clause(Phrase phrase, boolean isRequired, boolean isProhibited, NutchConf nutchConf) {
this.isRequired = isRequired;
this.isProhibited = isProhibited;
this.termOrPhrase = phrase;
+ this.nutchConf = nutchConf;
}
public boolean isRequired() { return isRequired; }
@@ -104,7 +109,7 @@ public final class Query implements Writable, Cloneable {
getTerm().write(out);
}
- public static Clause read(DataInput in) throws IOException {
+ public static Clause read(DataInput in, NutchConf nutchConf) throws IOException {
byte bits = in.readByte();
boolean required = ((bits & REQUIRED_BIT) != 0);
boolean prohibited = ((bits & PROHIBITED_BIT) != 0);
@@ -114,9 +119,9 @@ public final class Query implements Writable, Cloneable {
Clause clause;
if ((bits & PHRASE_BIT) == 0) {
- clause = new Clause(Term.read(in), field, required, prohibited);
+ clause = new Clause(Term.read(in), field, required, prohibited, nutchConf);
} else {
- clause = new Clause(Phrase.read(in), field, required, prohibited);
+ clause = new Clause(Phrase.read(in), field, required, prohibited, nutchConf);
}
clause.weight = weight;
return clause;
@@ -135,7 +140,7 @@ public final class Query implements Writable, Cloneable {
buffer.append(":");
}
- if (!isPhrase() && QueryFilters.isRawField(field)) {
+ if (!isPhrase() && new QueryFilters(nutchConf).isRawField(field)) {
buffer.append('"'); // quote raw terms
buffer.append(termOrPhrase.toString());
buffer.append('"');
@@ -274,7 +279,13 @@ public final class Query implements Writable, Cloneable {
private ArrayList clauses = new ArrayList();
+ private NutchConf nutchConf;
+
private static final Clause[] CLAUSES_PROTO = new Clause[0];
+
+ public Query(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ }
/** Return all clauses. */
public Clause[] getClauses() {
@@ -288,7 +299,7 @@ public final class Query implements Writable, Cloneable {
/** Add a required term in a specified field. */
public void addRequiredTerm(String term, String field) {
- clauses.add(new Clause(new Term(term), field, true, false));
+ clauses.add(new Clause(new Term(term), field, true, false, this.nutchConf));
}
/** Add a prohibited term in the default field. */
@@ -298,7 +309,7 @@ public final class Query implements Writable, Cloneable {
/** Add a prohibited term in the specified field. */
public void addProhibitedTerm(String term, String field) {
- clauses.add(new Clause(new Term(term), field, false, true));
+ clauses.add(new Clause(new Term(term), field, false, true, this.nutchConf));
}
/** Add a required phrase in the default field. */
@@ -312,7 +323,7 @@ public final class Query implements Writable, Cloneable {
} else if (terms.length == 1) {
addRequiredTerm(terms[0], field); // optimize to term query
} else {
- clauses.add(new Clause(new Phrase(terms), field, true, false));
+ clauses.add(new Clause(new Phrase(terms), field, true, false, this.nutchConf));
}
}
@@ -327,7 +338,7 @@ public final class Query implements Writable, Cloneable {
} else if (terms.length == 1) {
addProhibitedTerm(terms[0], field); // optimize to term query
} else {
- clauses.add(new Clause(new Phrase(terms), field, false, true));
+ clauses.add(new Clause(new Phrase(terms), field, false, true, this.nutchConf));
}
}
@@ -337,8 +348,8 @@ public final class Query implements Writable, Cloneable {
((Clause)clauses.get(i)).write(out);
}
- public static Query read(DataInput in) throws IOException {
- Query result = new Query();
+ public static Query read(DataInput in, NutchConf nutchConf) throws IOException {
+ Query result = new Query(nutchConf);
result.readFields(in);
return result;
}
@@ -347,7 +358,7 @@ public final class Query implements Writable, Cloneable {
clauses.clear();
int length = in.readByte();
for (int i = 0; i < length; i++)
- clauses.add(Clause.read(in));
+ clauses.add(Clause.read(in, this.nutchConf));
}
public String toString() {
@@ -404,18 +415,18 @@ public final class Query implements Writable, Cloneable {
/** Parse a query from a string. */
- public static Query parse(String queryString) throws IOException {
- return fixup(NutchAnalysis.parseQuery(queryString));
+ public static Query parse(String queryString, NutchConf nutchConf) throws IOException {
+ return fixup(NutchAnalysis.parseQuery(queryString, nutchConf), nutchConf);
}
/** Convert clauses in unknown fields to the default field. */
- private static Query fixup(Query input) {
+ private static Query fixup(Query input, NutchConf nutchConf) {
// walk the query
- Query output = new Query();
+ Query output = new Query(nutchConf);
Clause[] clauses = input.getClauses();
for (int i = 0; i < clauses.length; i++) {
Clause c = clauses[i];
- if (!QueryFilters.isField(c.getField())) { // unknown field
+ if (!new QueryFilters(nutchConf).isField(c.getField())) { // unknown field
ArrayList terms = new ArrayList(); // add name to query
if (c.isPhrase()) {
terms.addAll(Arrays.asList(c.getPhrase().getTerms()));
@@ -436,12 +447,13 @@ public final class Query implements Writable, Cloneable {
/** For debugging. */
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ NutchConf nutchConf = new NutchConf();
while (true) {
System.out.print("Query: ");
String line = in.readLine();
- Query query = parse(line);
+ Query query = parse(line, nutchConf);
System.out.println("Parsed: " + query);
- System.out.println("Translated: " + QueryFilters.filter(query));
+ System.out.println("Translated: " + new QueryFilters(nutchConf).filter(query));
}
}
}
diff --git a/src/java/org/apache/nutch/searcher/QueryFilter.java b/src/java/org/apache/nutch/searcher/QueryFilter.java
index 343fe93f3..07e47361d 100644
--- a/src/java/org/apache/nutch/searcher/QueryFilter.java
+++ b/src/java/org/apache/nutch/searcher/QueryFilter.java
@@ -17,12 +17,13 @@
package org.apache.nutch.searcher;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.nutch.util.NutchConfigurable;
/** Extension point for query translation. Permits one to add metadata to a
* query. All plugins found which implement this extension point are run
* sequentially on the query.
*/
-public interface QueryFilter {
+public interface QueryFilter extends NutchConfigurable {
/** The name of the extension point. */
final static String X_POINT_ID = QueryFilter.class.getName();
diff --git a/src/java/org/apache/nutch/searcher/QueryFilters.java b/src/java/org/apache/nutch/searcher/QueryFilters.java
index c9f828241..375e41e6a 100644
--- a/src/java/org/apache/nutch/searcher/QueryFilters.java
+++ b/src/java/org/apache/nutch/searcher/QueryFilters.java
@@ -19,6 +19,8 @@ package org.apache.nutch.searcher;
import org.apache.nutch.plugin.*;
import org.apache.nutch.searcher.Query.Clause;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
+
import java.util.logging.Logger;
import java.util.*;
@@ -35,35 +37,9 @@ public class QueryFilters {
private static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.searcher.QueryFilters");
- private static final QueryFilter[] CACHE;
- private static final HashSet FIELD_NAMES = new HashSet();
- private static final HashSet RAW_FIELD_NAMES = new HashSet();
-
- static {
- try {
- ExtensionPoint point = PluginRepository.getInstance()
- .getExtensionPoint(QueryFilter.X_POINT_ID);
- if (point == null)
- throw new RuntimeException(QueryFilter.X_POINT_ID+" not found.");
- Extension[] extensions = point.getExtensions();
- CACHE = new QueryFilter[extensions.length];
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- ArrayList fieldNames = parseFieldNames(extension, "fields");
- ArrayList rawFieldNames = parseFieldNames(extension, "raw-fields");
- if (fieldNames.size() == 0 && rawFieldNames.size() == 0) {
- LOG.warning("QueryFilter: "+extension.getId()+" names no fields.");
- continue;
- }
- CACHE[i] = (QueryFilter)extension.getExtensionInstance();
- FIELD_NAMES.addAll(fieldNames);
- FIELD_NAMES.addAll(rawFieldNames);
- RAW_FIELD_NAMES.addAll(rawFieldNames);
- }
- } catch (PluginRuntimeException e) {
- throw new RuntimeException(e);
- }
- }
+ private QueryFilter[] queryFilters;
+ private HashSet FIELD_NAMES ;
+ private HashSet RAW_FIELD_NAMES;
private static ArrayList parseFieldNames(Extension extension,
String attribute) {
@@ -72,10 +48,50 @@ public class QueryFilters {
return Collections.list(new StringTokenizer(fields, " ,\t\n\r"));
}
- private QueryFilters() {} // no public ctor
+ public QueryFilters(NutchConf nutchConf) {
+ this.queryFilters = (QueryFilter[]) nutchConf.getObject(QueryFilter.class
+ .getName());
+ if (this.queryFilters == null) {
+ try {
+ ExtensionPoint point = nutchConf.getPluginRepository()
+ .getExtensionPoint(QueryFilter.X_POINT_ID);
+ if (point == null)
+ throw new RuntimeException(QueryFilter.X_POINT_ID + " not found.");
+ Extension[] extensions = point.getExtensions();
+ QueryFilter[] filters = new QueryFilter[extensions.length];
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ ArrayList fieldNames = parseFieldNames(extension, "fields");
+ ArrayList rawFieldNames = parseFieldNames(extension, "raw-fields");
+ if (fieldNames.size() == 0 && rawFieldNames.size() == 0) {
+ LOG.warning("QueryFilter: " + extension.getId()
+ + " names no fields.");
+ continue;
+ }
+ filters[i] = (QueryFilter) extension.getExtensionInstance();
+ FIELD_NAMES = new HashSet();
+ FIELD_NAMES.addAll(fieldNames);
+ FIELD_NAMES.addAll(rawFieldNames);
+ nutchConf.setObject("FIELD_NAMES", FIELD_NAMES);
+ RAW_FIELD_NAMES = new HashSet();
+ RAW_FIELD_NAMES.addAll(rawFieldNames);
+ nutchConf.setObject("RAW_FIELD_NAMES", RAW_FIELD_NAMES);
+ }
+ nutchConf.setObject(QueryFilter.class.getName(), filters);
+ } catch (PluginRuntimeException e) {
+ throw new RuntimeException(e);
+ }
+ this.queryFilters = (QueryFilter[]) nutchConf.getObject(QueryFilter.class
+ .getName());
+ } else {
+ // cache already filled
+ FIELD_NAMES = (HashSet) nutchConf.getObject("FIELD_NAMES");
+ RAW_FIELD_NAMES = (HashSet) nutchConf.getObject("RAW_FIELD_NAMES");
+ }
+ }
/** Run all defined filters. */
- public static BooleanQuery filter(Query input) throws QueryException {
+ public BooleanQuery filter(Query input) throws QueryException {
// first check that all field names are claimed by some plugin
Clause[] clauses = input.getClauses();
for (int i = 0; i < clauses.length; i++) {
@@ -86,16 +102,17 @@ public class QueryFilters {
// then run each plugin
BooleanQuery output = new BooleanQuery();
- for (int i = 0 ; i < CACHE.length; i++) {
- output = CACHE[i].filter(input, output);
+ for (int i = 0; i < this.queryFilters.length; i++) {
+ output = this.queryFilters[i].filter(input, output);
}
return output;
}
- public static boolean isField(String name) {
+ public boolean isField(String name) {
return FIELD_NAMES.contains(name);
}
- public static boolean isRawField(String name) {
+
+ public boolean isRawField(String name) {
return RAW_FIELD_NAMES.contains(name);
}
}
diff --git a/src/java/org/apache/nutch/searcher/Summarizer.java b/src/java/org/apache/nutch/searcher/Summarizer.java
index 43df60bba..596020147 100644
--- a/src/java/org/apache/nutch/searcher/Summarizer.java
+++ b/src/java/org/apache/nutch/searcher/Summarizer.java
@@ -29,21 +29,23 @@ import org.apache.nutch.analysis.NutchDocumentAnalyzer;
/** Implements hit summarization. */
public class Summarizer {
-
- /** The number of context terms to display preceding and following matches.*/
- private static final int SUM_CONTEXT =
- NutchConf.get().getInt("searcher.summary.context", 5);
-
- /** The total number of terms to display in a summary.*/
- private static final int SUM_LENGTH =
- NutchConf.get().getInt("searcher.summary.length", 20);
-
+
/** Converts text to tokens. */
- private static final Analyzer ANALYZER = new NutchDocumentAnalyzer();
+ private Analyzer ANALYZER;
+ private NutchConf nutchConf;
+
+ /**
+ * The constructor.
+ * @param conf
+ */
+ public Summarizer(NutchConf conf) {
+ this.nutchConf = conf;
+ this.ANALYZER = new NutchDocumentAnalyzer(conf);
+ }
/**
- * Class Excerpt represents a single passage found in the
- * document, with some appropriate regions highlit.
+ * Class Excerpt represents a single passage found in the document, with some
+ * appropriate regions highlit.
*/
class Excerpt {
Vector passages = new Vector();
@@ -54,7 +56,7 @@ public class Summarizer {
*/
public Excerpt() {
}
-
+
/**
*/
public void addToken(String token) {
@@ -99,7 +101,7 @@ public class Summarizer {
}
/** Returns a summary for the given pre-tokenized text. */
- public Summary getSummary(String text, Query query) throws IOException {
+ public Summary getSummary(String text, Query query, int sumContext, int sumLength) throws IOException {
// Simplistic implementation. Finds the first fragments in the document
// containing any query terms.
@@ -161,8 +163,8 @@ public class Summarizer {
// Start searching at a point SUM_CONTEXT terms back,
// and move SUM_CONTEXT terms into the future.
//
- int startToken = (i > SUM_CONTEXT) ? i-SUM_CONTEXT : 0;
- int endToken = Math.min(i+SUM_CONTEXT, tokens.length);
+ int startToken = (i > sumContext) ? i - sumContext : 0;
+ int endToken = Math.min(i + sumContext, tokens.length);
int offset = tokens[startToken].startOffset();
int j = startToken;
@@ -181,7 +183,7 @@ public class Summarizer {
// the document and we haven't hit the max-number-of-items
// -in-a-summary.
//
- while ((j < endToken) && (j - startToken < SUM_LENGTH)) {
+ while ((j < endToken) && (j - startToken < sumLength)) {
//
// Now grab the hit-element, if present
//
@@ -191,7 +193,7 @@ public class Summarizer {
excerpt.add(new Fragment(text.substring(offset, t.startOffset())));
excerpt.add(new Highlight(text.substring(t.startOffset(),t.endOffset())));
offset = t.endOffset();
- endToken = Math.min(j+SUM_CONTEXT, tokens.length);
+ endToken = Math.min(j + sumContext, tokens.length);
}
j++;
@@ -226,7 +228,7 @@ public class Summarizer {
// Start SUM_CONTEXT places away. The next
// search for relevant excerpts begins at i-SUM_CONTEXT
//
- i = j+SUM_CONTEXT;
+ i = j + sumContext;
}
}
@@ -236,7 +238,7 @@ public class Summarizer {
//
if (excerptSet.size() == 0) {
Excerpt excerpt = new Excerpt();
- int excerptLen = Math.min(SUM_LENGTH, tokens.length);
+ int excerptLen = Math.min(sumLength, tokens.length);
lastExcerptPos = excerptLen;
excerpt.add(new Fragment(text.substring(tokens[0].startOffset(), tokens[excerptLen-1].startOffset())));
@@ -250,7 +252,7 @@ public class Summarizer {
//
double tokenCount = 0;
Summary s = new Summary();
- while (tokenCount <= SUM_LENGTH && excerptSet.size() > 0) {
+ while (tokenCount <= sumLength && excerptSet.size() > 0) {
Excerpt excerpt = (Excerpt) excerptSet.last();
excerptSet.remove(excerpt);
@@ -258,7 +260,7 @@ public class Summarizer {
for (Enumeration e = excerpt.elements(); e.hasMoreElements(); ) {
Fragment f = (Fragment) e.nextElement();
// Don't add fragments if it takes us over the max-limit
- if (tokenCount + tokenFraction <= SUM_LENGTH) {
+ if (tokenCount + tokenFraction <= sumLength) {
s.add(f);
}
tokenCount += tokenFraction;
@@ -290,7 +292,7 @@ public class Summarizer {
return;
}
- Summarizer s = new Summarizer();
+ Summarizer s = new Summarizer(new NutchConf());
//
// Parse the args
@@ -318,8 +320,11 @@ public class Summarizer {
in.close();
}
+ NutchConf nutchConf = new NutchConf();
+ int sumContext = nutchConf.getInt("searcher.summary.context", 5);
+ int sumLength = nutchConf.getInt("searcher.summary.length", 20);
// Convert the query string into a proper Query
- Query query = Query.parse(queryBuf.toString());
- System.out.println("Summary: '" + s.getSummary(body.toString(), query) + "'");
+ Query query = Query.parse(queryBuf.toString(), nutchConf);
+ System.out.println("Summary: '" + s.getSummary(body.toString(), query, sumContext, sumLength) + "'");
}
}
diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.java
index 8a3b518c6..8e011cc17 100644
--- a/src/java/org/apache/nutch/segment/SegmentReader.java
+++ b/src/java/org/apache/nutch/segment/SegmentReader.java
@@ -68,7 +68,7 @@ public class SegmentReader extends NutchConfigured implements Reducer {
throws IOException {
reporter.setStatus(split.toString());
- return new SequenceFileRecordReader(fs, split) {
+ return new SequenceFileRecordReader(job, split) {
public synchronized boolean next(Writable key, Writable value)
throws IOException {
ObjectWritable wrapper = (ObjectWritable)value;
@@ -219,7 +219,8 @@ public class SegmentReader extends NutchConfigured implements Reducer {
}
public static void main(String[] args) throws Exception {
- SegmentReader segmentReader = new SegmentReader(NutchConf.get());
+ NutchConf nutchConf = new NutchConf();
+ SegmentReader segmentReader = new SegmentReader(nutchConf);
String usage = "Usage: SegmentReader <segment>";
diff --git a/src/java/org/apache/nutch/servlet/Cached.java b/src/java/org/apache/nutch/servlet/Cached.java
index 16c992f95..7f6a6b015 100644
--- a/src/java/org/apache/nutch/servlet/Cached.java
+++ b/src/java/org/apache/nutch/servlet/Cached.java
@@ -47,9 +47,9 @@ public class Cached extends HttpServlet {
NutchBean bean = null;
- public void init() {
+ public void init(NutchConf nutchConf) {
try {
- bean = NutchBean.get(this.getServletContext());
+ bean = NutchBean.get(this.getServletContext(), nutchConf);
} catch (IOException e) {
// nothing
}
diff --git a/src/java/org/apache/nutch/tools/DmozParser.java b/src/java/org/apache/nutch/tools/DmozParser.java
index 1bae3f2b0..6c0b54b2d 100644
--- a/src/java/org/apache/nutch/tools/DmozParser.java
+++ b/src/java/org/apache/nutch/tools/DmozParser.java
@@ -338,7 +338,8 @@ public class DmozParser {
Pattern topicPattern = null;
Vector topics = new Vector();
- NutchFileSystem nfs = NutchFileSystem.get();
+ NutchConf nutchConf = new NutchConf();
+ NutchFileSystem nfs = NutchFileSystem.get(nutchConf);
try {
for (int i = 1; i < argv.length; i++) {
if ("-includeAdultMaterial".equals(argv[i])) {
diff --git a/src/java/org/apache/nutch/tools/PruneIndexTool.java b/src/java/org/apache/nutch/tools/PruneIndexTool.java
index 4ee053af7..74e8a14b7 100644
--- a/src/java/org/apache/nutch/tools/PruneIndexTool.java
+++ b/src/java/org/apache/nutch/tools/PruneIndexTool.java
@@ -459,8 +459,9 @@ public class PruneIndexTool implements Runnable {
if (qPath != null) {
is = new FileInputStream(qPath);
} else {
- qPath = NutchConf.get().get("prune.index.tool.queries");
- is = NutchConf.get().getConfResourceAsInputStream(qPath);
+ NutchConf nutchConf = new NutchConf();
+ qPath = nutchConf.get("prune.index.tool.queries");
+ is = nutchConf.getConfResourceAsInputStream(qPath);
}
if (is == null) {
LOG.severe("Can't load queries from " + qPath);
diff --git a/src/java/org/apache/nutch/util/NutchConf.java b/src/java/org/apache/nutch/util/NutchConf.java
index 672197d3f..74e8488a3 100644
--- a/src/java/org/apache/nutch/util/NutchConf.java
+++ b/src/java/org/apache/nutch/util/NutchConf.java
@@ -18,11 +18,12 @@ package org.apache.nutch.util;
import java.util.*;
import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.MalformedURLException;
import java.io.*;
import java.util.logging.Logger;
+
import javax.xml.parsers.*;
+
+import org.apache.nutch.plugin.PluginRepository;
import org.w3c.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
@@ -45,16 +46,13 @@ public class NutchConf {
private static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.util.NutchConf");
- private static final NutchConf DEFAULT = new NutchConf();
-
- /** Return the default configuration. */
- public static NutchConf get() { return DEFAULT; }
-
private ArrayList resourceNames = new ArrayList();
private Properties properties;
private ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
+ private PluginRepository pluginRepository;
+
/** A new configuration. */
public NutchConf() {
resourceNames.add("nutch-default.xml");
@@ -89,9 +87,21 @@ public class NutchConf {
resourceNames.add(resourceNames.size()-1, name); // add second to last
properties = null; // trigger reload
}
+
+ /**
+ * @return a cached instance of the plugin repository
+ */
+ public PluginRepository getPluginRepository() {
+ if (this.pluginRepository == null) {
+ this.pluginRepository = new PluginRepository(this);
+ }
+ return this.pluginRepository;
+ }
- /** Returns the value of the <code>name</code> property, or null if no
- * such property exists. */
+ /**
+ * Returns the value of the <code>name</code> property, or null if no such
+ * property exists.
+ */
public Object getObject(String name) { return getProps().get(name);}
/** Sets the value of the <code>name</code> property. */
@@ -390,8 +400,13 @@ public class NutchConf {
conf.appendChild(doc.createTextNode("\n"));
for (Enumeration e = properties.keys(); e.hasMoreElements();) {
String name = (String)e.nextElement();
- String value = (String)properties.get(name);
-
+ Object object = properties.get(name);
+ String value = null;
+ if(object instanceof String) {
+ value = (String) object;
+ }else {
+ continue;
+ }
Element propNode = doc.createElement("property");
conf.appendChild(propNode);
@@ -437,7 +452,7 @@ public class NutchConf {
/** For debugging. List non-default properties to the terminal and exit. */
public static void main(String[] args) throws Exception {
- get().write(System.out);
+ new NutchConf().write(System.out);
}
}
diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
index 8708ac1b6..08a9860f7 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
@@ -30,6 +30,7 @@ import org.apache.nutch.crawl.Inlinks;
import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import java.util.*;
import java.net.URL;
@@ -43,6 +44,8 @@ public class CCIndexingFilter implements IndexingFilter {
/** The name of the document field we use. */
public static String FIELD = "cc";
+ private NutchConf nutchConf;
+
public Document filter(Document doc, Parse parse, UTF8 url, CrawlDatum datum, Inlinks inlinks)
throws IndexingException {
@@ -100,4 +103,12 @@ public class CCIndexingFilter implements IndexingFilter {
doc.add(Field.Keyword(FIELD, feature));
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
index f240dc0de..73e2c40bc 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
@@ -36,8 +36,6 @@ public class CCParseFilter implements HtmlParseFilter {
public static final Logger LOG
= LogFormatter.getLogger(CCParseFilter.class.getName());
- private static final boolean EXCLUDE_UNLICENSED =
- NutchConf.get().getBoolean("creativecommons.exclude.unlicensed", false);
/** Walks DOM tree, looking for RDF in comments and licenses in anchors.*/
public static class Walker {
@@ -52,7 +50,7 @@ public class CCParseFilter implements HtmlParseFilter {
}
/** Scan the document adding attributes to metadata.*/
- public static void walk(Node doc, URL base, ContentProperties metadata)
+ public static void walk(Node doc, URL base, ContentProperties metadata, NutchConf nutchConf)
throws ParseException {
// walk the DOM tree, scanning for license data
@@ -71,7 +69,7 @@ public class CCParseFilter implements HtmlParseFilter {
} else if (walker.anchorLicense != null) { // 3rd: anchor w/ CC license
licenseLocation = "a";
licenseUrl = walker.anchorLicense.toString();
- } else if (EXCLUDE_UNLICENSED) {
+ } else if (nutchConf.getBoolean("creativecommons.exclude.unlicensed", false)) {
throw new ParseException("No CC license. Excluding.");
}
@@ -251,6 +249,8 @@ public class CCParseFilter implements HtmlParseFilter {
WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Image", "image");
}
+ private NutchConf nutchConf;
+
/** Adds metadata or otherwise modifies a parse of an HTML document, given
* the DOM tree of a page. */
public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
@@ -260,17 +260,24 @@ public class CCParseFilter implements HtmlParseFilter {
try {
base = new URL(content.getBaseUrl());
} catch (MalformedURLException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
}
try {
// extract license metadata
- Walker.walk(doc, base, parse.getData().getMetadata());
+ Walker.walk(doc, base, parse.getData().getMetadata(), getConf());
} catch (ParseException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
}
return parse;
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.java
index 57e209463..aadfcf425 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.java
@@ -17,11 +17,24 @@
package org.creativecommons.nutch;
import org.apache.nutch.searcher.RawFieldQueryFilter;
+import org.apache.nutch.util.NutchConf;
-/** Handles "cc:" query clauses, causing them to search the "cc" field
- * indexed by CCIndexingFilter. */
+/**
+ * Handles "cc:" query clauses, causing them to search the "cc" field indexed by
+ * CCIndexingFilter.
+ */
public class CCQueryFilter extends RawFieldQueryFilter {
+ private NutchConf nutchConf;
+
public CCQueryFilter() {
super(CCIndexingFilter.FIELD);
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java b/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java
index 30c3043ee..72f1eab44 100755
--- a/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java
+++ b/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java
@@ -1,68 +1,70 @@
-/**
- * Copyright 2005 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.creativecommons.nutch;
-
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseUtil;
-import org.apache.nutch.protocol.Content;
-import org.apache.nutch.protocol.ContentProperties;
-
-import java.util.Properties;
-import java.io.*;
-import java.net.URL;
-
-import junit.framework.TestCase;
-
-public class TestCCParseFilter extends TestCase {
-
- private static final File testDir =
- new File(System.getProperty("test.input"));
-
- public void testPages() throws Exception {
- pageTest(new File(testDir, "anchor.html"), "http://foo.com/",
- "http://creativecommons.org/licenses/by-nc-sa/1.0", "a", null);
- pageTest(new File(testDir, "rel.html"), "http://foo.com/",
- "http://creativecommons.org/licenses/by-nc/2.0", "rel", null);
- pageTest(new File(testDir, "rdf.html"), "http://foo.com/",
- "http://creativecommons.org/licenses/by-nc/1.0", "rdf", "text");
- }
-
- public void pageTest(File file, String url,
- String license, String location, String type)
- throws Exception {
-
- String contentType = "text/html";
- InputStream in = new FileInputStream(file);
- ByteArrayOutputStream out = new ByteArrayOutputStream((int)file.length());
- byte[] buffer = new byte[1024];
- int i;
- while ((i = in.read(buffer)) != -1) {
- out.write(buffer, 0, i);
- }
- in.close();
- byte[] bytes = out.toByteArray();
-
- Content content =
- new Content(url, url, bytes, contentType, new ContentProperties());
- Parse parse = ParseUtil.parseByParserId("parse-html",content);
-
- ContentProperties metadata = parse.getData().getMetadata();
- assertEquals(license, metadata.get("License-Url"));
- assertEquals(location, metadata.get("License-Location"));
- assertEquals(type, metadata.get("Work-Type"));
- }
-}
+/**
+ * Copyright 2005 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.creativecommons.nutch;
+
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.parse.ParseUtil;
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.protocol.ContentProperties;
+import org.apache.nutch.util.NutchConf;
+
+import java.util.Properties;
+import java.io.*;
+import java.net.URL;
+
+import junit.framework.TestCase;
+
+public class TestCCParseFilter extends TestCase {
+
+ private static final File testDir =
+ new File(System.getProperty("test.input"));
+
+ public void testPages() throws Exception {
+ pageTest(new File(testDir, "anchor.html"), "http://foo.com/",
+ "http://creativecommons.org/licenses/by-nc-sa/1.0", "a", null);
+ pageTest(new File(testDir, "rel.html"), "http://foo.com/",
+ "http://creativecommons.org/licenses/by-nc/2.0", "rel", null);
+ pageTest(new File(testDir, "rdf.html"), "http://foo.com/",
+ "http://creativecommons.org/licenses/by-nc/1.0", "rdf", "text");
+ }
+
+ public void pageTest(File file, String url,
+ String license, String location, String type)
+ throws Exception {
+
+ String contentType = "text/html";
+ InputStream in = new FileInputStream(file);
+ ByteArrayOutputStream out = new ByteArrayOutputStream((int)file.length());
+ byte[] buffer = new byte[1024];
+ int i;
+ while ((i = in.read(buffer)) != -1) {
+ out.write(buffer, 0, i);
+ }
+ in.close();
+ byte[] bytes = out.toByteArray();
+ NutchConf nutchConf = new NutchConf();
+
+ Content content =
+ new Content(url, url, bytes, contentType, new ContentProperties(), nutchConf);
+ Parse parse = new ParseUtil(nutchConf).parseByParserId("parse-html",content);
+
+ ContentProperties metadata = parse.getData().getMetadata();
+ assertEquals(license, metadata.get("License-Url"));
+ assertEquals(location, metadata.get("License-Location"));
+ assertEquals(type, metadata.get("Work-Type"));
+ }
+}
diff --git a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java
index a381163ce..1ced445fe 100644
--- a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java
+++ b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java
@@ -40,8 +40,8 @@ public class BasicIndexingFilter implements IndexingFilter {
public static final Logger LOG
= LogFormatter.getLogger(BasicIndexingFilter.class.getName());
- private static final int MAX_TITLE_LENGTH =
- NutchConf.get().getInt("indexer.max.title.length", 100);
+ private int MAX_TITLE_LENGTH;
+ private NutchConf nutchConf;
public Document filter(Document doc, Parse parse, UTF8 url, CrawlDatum datum, Inlinks inlinks)
throws IndexingException {
@@ -89,4 +89,13 @@ public class BasicIndexingFilter implements IndexingFilter {
return doc;
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.MAX_TITLE_LENGTH = conf.getInt("indexer.max.title.length", 100);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java
index e90ca7e20..41dc87119 100644
--- a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java
+++ b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java
@@ -75,13 +75,10 @@ public class MoreIndexingFilter implements IndexingFilter {
= LogFormatter.getLogger(MoreIndexingFilter.class.getName());
/** A flag that tells if magic resolution must be performed */
- private final static boolean MAGIC =
- NutchConf.get().getBoolean("mime.type.magic", true);
+ private boolean MAGIC;
/** Get the MimeTypes resolver instance. */
- private final static MimeTypes MIME =
- MimeTypes.get(NutchConf.get().get("mime.types.file"));
-
+ private MimeTypes MIME;
public Document filter(Document doc, Parse parse, UTF8 url, CrawlDatum datum, Inlinks inlinks)
throws IndexingException {
@@ -247,6 +244,8 @@ public class MoreIndexingFilter implements IndexingFilter {
// HTTP header "Content-Disposition". Typically it looks like:
// Content-Disposition: inline; filename="foo.ppt"
private PatternMatcher matcher = new Perl5Matcher();
+
+ private NutchConf nutchConf;
static Perl5Pattern patterns[] = {null, null};
static {
Perl5Compiler compiler = new Perl5Compiler();
@@ -302,4 +301,14 @@ public class MoreIndexingFilter implements IndexingFilter {
return normalized;
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ MAGIC = conf.getBoolean("mime.type.magic", true);
+ MIME = MimeTypes.get(getConf().get("mime.types.file"));
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
index da5c2a146..c26b47481 100644
--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
@@ -28,6 +28,7 @@ import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.HtmlParseFilter;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
// DOM imports
import org.w3c.dom.DocumentFragment;
@@ -67,6 +68,8 @@ public class HTMLLanguageParser implements HtmlParseFilter {
LOG.severe(e.toString());
}
}
+
+ private NutchConf nutchConf;
@@ -195,5 +198,11 @@ public class HTMLLanguageParser implements HtmlParseFilter {
}
-
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java
index 3302701ac..ddfa81f81 100644
--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java
+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java
@@ -95,12 +95,12 @@ public class LanguageIdentifier {
/**
* Constructs a new Language Identifier.
*/
- private LanguageIdentifier() {
+ public LanguageIdentifier(NutchConf nutchConf) {
// Gets ngram sizes to take into account from the Nutch Config
- minLength = NutchConf.get().getInt("lang.ngram.min.length",
+ minLength = nutchConf.getInt("lang.ngram.min.length",
NGramProfile.DEFAULT_MIN_NGRAM_LENGTH);
- maxLength = NutchConf.get().getInt("lang.ngram.max.length",
+ maxLength = nutchConf.getInt("lang.ngram.max.length",
NGramProfile.DEFAULT_MAX_NGRAM_LENGTH);
// Ensure the min and max values are in an acceptale range
// (ie min >= DEFAULT_MIN_NGRAM_LENGTH and max <= DEFAULT_MAX_NGRAM_LENGTH)
@@ -110,7 +110,7 @@ public class LanguageIdentifier {
minLength = Math.min(minLength, maxLength);
// Gets the value of the maximum size of data to analyze
- analyzeLength = NutchConf.get().getInt("lang.analyze.max.length",
+ analyzeLength = nutchConf.getInt("lang.analyze.max.length",
DEFAULT_ANALYSIS_LENGTH);
Properties p = new Properties();
@@ -174,20 +174,6 @@ public class LanguageIdentifier {
}
}
- /**
- * Get a LanguageIdentifier instance.
- * @return the LanguageIdentifier singleton instance.
- */
- public static LanguageIdentifier getInstance() {
- if (identifier == null) {
- synchronized(LanguageIdentifier.class) {
- if (identifier == null) {
- identifier = new LanguageIdentifier();
- }
- }
- }
- return identifier;
- }
/**
* Main method used for command line process.
@@ -272,9 +258,10 @@ public class LanguageIdentifier {
}
+ NutchConf nutchConf = new NutchConf();
String lang = null;
//LanguageIdentifier idfr = LanguageIdentifier.getInstance();
- LanguageIdentifier idfr = new LanguageIdentifier();
+ LanguageIdentifier idfr = new LanguageIdentifier(nutchConf);
File f;
FileInputStream fis;
try {
@@ -292,7 +279,7 @@ public class LanguageIdentifier {
break;
case IDURL:
- text = getUrlContent(filename);
+ text = getUrlContent(filename, nutchConf);
lang = idfr.identify(text);
break;
@@ -348,13 +335,13 @@ public class LanguageIdentifier {
* @param url
* @return contents of url
*/
- private static String getUrlContent(String url) {
+ private static String getUrlContent(String url, NutchConf nutchConf) {
Protocol protocol;
try {
- protocol = ProtocolFactory.getProtocol(url);
+ protocol = new ProtocolFactory(nutchConf).getProtocol(url);
Content content = protocol.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();
String contentType = content.getContentType();
- Parser parser = ParserFactory.getParser(contentType, url);
+ Parser parser = new ParserFactory(nutchConf).getParser(contentType, url);
Parse parse = parser.getParse(content);
System.out.println("text:" + parse.getText());
return parse.getText();
diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
index 3517a3da4..cf7d9f1eb 100644
--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
@@ -24,6 +24,7 @@ import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.IndexingException;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.parse.Parse;
+import org.apache.nutch.util.NutchConf;
// Lucene imports
import org.apache.lucene.document.Field;
@@ -49,7 +50,10 @@ import org.apache.lucene.document.Document;
public class LanguageIndexingFilter implements IndexingFilter {
- /**
+ private NutchConf nutchConf;
+ private LanguageIdentifier languageIdentifier;
+
+/**
* Constructs a new Language Indexing Filter.
*/
public LanguageIndexingFilter() {
@@ -77,7 +81,7 @@ public class LanguageIndexingFilter implements IndexingFilter {
text.append(parse.getData().getTitle())
.append(" ")
.append(parse.getText());
- lang = LanguageIdentifier.getInstance().identify(text);
+ lang = this.languageIdentifier.identify(text);
}
if (lang == null) {
@@ -88,5 +92,13 @@ public class LanguageIndexingFilter implements IndexingFilter {
return doc;
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.languageIdentifier = new LanguageIdentifier(conf);
+ }
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.java
index 138dc52d7..b41b92717 100644
--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.java
+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.java
@@ -17,11 +17,22 @@
package org.apache.nutch.analysis.lang;
import org.apache.nutch.searcher.RawFieldQueryFilter;
+import org.apache.nutch.util.NutchConf;
/** Handles "lang:" query clauses, causing them to search the "lang" field
* indexed by LanguageIdentifier. */
public class LanguageQueryFilter extends RawFieldQueryFilter {
+ private NutchConf nutchConf;
+
public LanguageQueryFilter() {
super("lang");
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
index be105fd45..25fcc3b83 100644
--- a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
+++ b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
@@ -26,6 +26,7 @@ import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.ParserFactory;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
+import org.apache.nutch.util.NutchConf;
public class TestHTMLLanguageParser extends TestCase {
@@ -52,7 +53,7 @@ public class TestHTMLLanguageParser extends TestCase {
for (int t = 0; t < docs.length; t++) {
Content content = getContent(docs[t]);
- Parser parser = ParserFactory.getParser("text/html", URL);
+ Parser parser = new ParserFactory(new NutchConf()).getParser("text/html", URL);
Parse parse = parser.getParse(content);
assertEquals(metalanguages[t], (String) parse.getData().get(
@@ -125,7 +126,7 @@ public class TestHTMLLanguageParser extends TestCase {
ContentProperties p = new ContentProperties();
p.put("Content-Type", "text/html");
- Content content = new Content(URL, BASE, text.getBytes(), "text/html", p);
+ Content content = new Content(URL, BASE, text.getBytes(), "text/html", p, new NutchConf());
return content;
}
diff --git a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java
index 160f4e8fa..c95ad42fc 100644
--- a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java
+++ b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java
@@ -32,6 +32,7 @@ import junit.textui.TestRunner;
// Lucene imports
import org.apache.lucene.analysis.Token;
+import org.apache.nutch.util.NutchConf;
/**
@@ -204,7 +205,7 @@ public class TestLanguageIdentifier extends TestCase {
public void testIdentify() {
try {
long total = 0;
- LanguageIdentifier idfr = LanguageIdentifier.getInstance();
+ LanguageIdentifier idfr = new LanguageIdentifier(new NutchConf());
BufferedReader in = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("test-referencial.txt")));
String line = null;
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
index a443e6031..8f69f1d0f 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
@@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
+
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.net.protocols.Response;
@@ -43,35 +44,46 @@ public abstract class HttpBase implements Protocol {
public static final int BUFFER_SIZE = 8 * 1024;
- public static String PROXY_HOST =
- NutchConf.get().get("http.proxy.host");
-
- public static int PROXY_PORT =
- NutchConf.get().getInt("http.proxy.port", 8080);
-
- public static boolean PROXY =
- (PROXY_HOST != null && PROXY_HOST.length() > 0);
-
- public static int TIMEOUT =
- NutchConf.get().getInt("http.timeout", 10000);
-
- public static int MAX_CONTENT =
- NutchConf.get().getInt("http.content.limit", 64 * 1024);
-
- public static int MAX_DELAYS =
- NutchConf.get().getInt("http.max.delays", 3);
-
- public static int MAX_THREADS_PER_HOST =
- NutchConf.get().getInt("fetcher.threads.per.host", 1);
-
- public static String AGENT_STRING =
- getAgentString();
-
- public static long SERVER_DELAY =
- (long) (NutchConf.get().getFloat("fetcher.server.delay", 1.0f) * 1000);
-
-
private static final byte[] EMPTY_CONTENT = new byte[0];
+
+ private RobotRulesParser robots = null;
+
+ /** The proxy hostname. */
+ protected String proxyHost = null;
+
+ /** The proxy port. */
+ protected int proxyPort = 8080;
+
+ /** Indicates if a proxy is used */
+ protected boolean useProxy = false;
+
+ /** The network timeout in millisecond */
+ protected int timeout = 10000;
+
+ /** The length limit for downloaded content, in bytes. */
+ protected int maxContent = 64 * 1024;
+
+ /** The number of times a thread will delay when trying to fetch a page. */
+ protected int maxDelays = 3;
+
+ /**
+ * The maximum number of threads that should be allowed
+ * to access a host at one time.
+ */
+ protected int maxThreadsPerHost = 1;
+
+ /**
+ * The number of seconds the fetcher will delay between
+ * successive requests to the same server.
+ */
+ protected long serverDelay = 1000;
+
+ /** The Nutch 'User-Agent' request header */
+ protected String userAgent = getAgentString(
+ "NutchCVS", null, "Nutch",
+ "http://lucene.apache.org/nutch/bot.html",
+
/**
* Maps from InetAddress to a Long naming the time it should be unblocked.
@@ -97,7 +109,10 @@ public abstract class HttpBase implements Protocol {
/** The specified logger */
private Logger logger = LOGGER;
-
+
+ /** The nutch configuration */
+ private NutchConf conf = null;
+
/** Creates a new instance of HttpBase */
public HttpBase() {
@@ -109,14 +124,32 @@ public abstract class HttpBase implements Protocol {
if (logger != null) {
this.logger = logger;
}
- logger.fine("http.proxy.host = " + PROXY_HOST);
- logger.fine("http.proxy.port = " + PROXY_PORT);
- logger.fine("http.timeout = " + TIMEOUT);
- logger.fine("http.content.limit = " + MAX_CONTENT);
- logger.fine("http.agent = " + AGENT_STRING);
- logger.fine("fetcher.server.delay = " + SERVER_DELAY);
- logger.fine("http.max.delays = " + MAX_DELAYS);
+ robots = new RobotRulesParser();
+ }
+
+ // Inherited Javadoc
+ public void setConf(NutchConf conf) {
+ this.conf = conf;
+ this.proxyHost = conf.get("http.proxy.host");
+ this.proxyPort = conf.getInt("http.proxy.port", 8080);
+ this.useProxy = (proxyHost != null && proxyHost.length() > 0);
+ this.timeout = conf.getInt("http.timeout", 10000);
+ this.maxContent = conf.getInt("http.content.limit", 64 * 1024);
+ this.maxDelays = conf.getInt("http.max.delays", 3);
+ this.maxThreadsPerHost = conf.getInt("fetcher.threads.per.host", 1);
+ this.userAgent = getAgentString(conf.get("http.agent.name"), conf.get("http.agent.version"), conf
+ .get("http.agent.description"), conf.get("http.agent.url"), conf.get("http.agent.email"));
+ this.serverDelay = (long) (conf.getFloat("fetcher.server.delay", 1.0f) * 1000);
+ this.robots.setConf(conf);
+ logConf();
+ }
+
+ // Inherited Javadoc
+ public NutchConf getConf() {
+ return this.conf;
}
+
+
public ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum) {
@@ -125,7 +158,7 @@ public abstract class HttpBase implements Protocol {
URL u = new URL(urlString);
try {
- if (!RobotRulesParser.isAllowed(this, u)) {
+ if (!robots.isAllowed(this, u)) {
return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.ROBOTS_DENIED, url));
}
} catch (Throwable e) {
@@ -146,7 +179,7 @@ public abstract class HttpBase implements Protocol {
Content c = new Content(u.toString(), u.toString(),
(content == null ? EMPTY_CONTENT : content),
response.getHeader("Content-Type"),
- response.getHeaders());
+ response.getHeaders(), this.conf);
if (code == 200) { // got a good response
return new ProtocolOutput(c); // return it
@@ -203,8 +236,49 @@ public abstract class HttpBase implements Protocol {
}
}
-
- private static InetAddress blockAddr(URL url) throws ProtocolException {
+ /* -------------------------- *
+ * </implementation:Protocol> *
+ * -------------------------- */
+
+
+ public String getProxyHost() {
+ return proxyHost;
+ }
+
+ public int getProxyPort() {
+ return proxyPort;
+ }
+
+ public boolean useProxy() {
+ return useProxy;
+ }
+
+ public int getTimeout() {
+ return timeout;
+ }
+
+ public int getMaxContent() {
+ return maxContent;
+ }
+
+ public int getMaxDelays() {
+ return maxDelays;
+ }
+
+ public int getMaxThreadsPerHost() {
+ return maxThreadsPerHost;
+ }
+
+ public long getServerDelay() {
+ return serverDelay;
+ }
+
+ public String getUserAgent() {
+ return userAgent;
+ }
+
+
+ private InetAddress blockAddr(URL url) throws ProtocolException {
InetAddress addr;
try {
@@ -229,21 +303,21 @@ public abstract class HttpBase implements Protocol {
count++; // increment & store
THREADS_PER_HOST_COUNT.put(addr, new Integer(count));
- if (count >= MAX_THREADS_PER_HOST) {
+ if (count >= maxThreadsPerHost) {
BLOCKED_ADDR_TO_TIME.put(addr, new Long(0)); // block it
}
return addr;
}
}
- if (delays == MAX_DELAYS)
+ if (delays == maxDelays)
throw new HttpException("Exceeded http.max.delays: retry later.");
long done = time.longValue();
long now = System.currentTimeMillis();
long sleep = 0;
if (done == 0) { // address is still in use
- sleep = SERVER_DELAY; // wait at least delay
+ sleep = serverDelay; // wait at least delay
} else if (now < done) { // address is on hold
sleep = done - now; // wait until its free
@@ -256,14 +330,14 @@ public abstract class HttpBase implements Protocol {
}
}
- private static void unblockAddr(InetAddress addr) {
+ private void unblockAddr(InetAddress addr) {
synchronized (BLOCKED_ADDR_TO_TIME) {
int addrCount = ((Integer)THREADS_PER_HOST_COUNT.get(addr)).intValue();
if (addrCount == 1) {
THREADS_PER_HOST_COUNT.remove(addr);
BLOCKED_ADDR_QUEUE.addFirst(addr);
BLOCKED_ADDR_TO_TIME.put
- (addr, new Long(System.currentTimeMillis()+SERVER_DELAY));
+ (addr, new Long(System.currentTimeMillis() + serverDelay));
} else {
THREADS_PER_HOST_COUNT.put(addr, new Integer(addrCount - 1));
}
@@ -285,13 +359,11 @@ public abstract class HttpBase implements Protocol {
}
}
- private static String getAgentString() {
-
- String agentName = NutchConf.get().get("http.agent.name");
- String agentVersion = NutchConf.get().get("http.agent.version");
- String agentDesc = NutchConf.get().get("http.agent.description");
- String agentURL = NutchConf.get().get("http.agent.url");
- String agentEmail = NutchConf.get().get("http.agent.email");
+ private static String getAgentString(String agentName,
+ String agentVersion,
+ String agentDesc,
+ String agentURL,
+ String agentEmail) {
if ( (agentName == null) || (agentName.trim().length() == 0) )
LOGGER.severe("No User-Agent string set (http.agent.name)!");
@@ -327,6 +399,16 @@ public abstract class HttpBase implements Protocol {
}
return buf.toString();
}
+
+ protected void logConf() {
+ logger.info("http.proxy.host = " + proxyHost);
+ logger.info("http.proxy.port = " + proxyPort);
+ logger.info("http.timeout = " + timeout);
+ logger.info("http.content.limit = " + maxContent);
+ logger.info("http.agent = " + userAgent);
+ logger.info("fetcher.server.delay = " + serverDelay);
+ logger.info("http.max.delays = " + maxDelays);
+ }
protected static void main(HttpBase http, String[] args) throws Exception {
boolean verbose = false;
@@ -341,7 +423,7 @@ public abstract class HttpBase implements Protocol {
for (int i = 0; i < args.length; i++) { // parse command line
if (args[i].equals("-timeout")) { // found -timeout option
- TIMEOUT = Integer.parseInt(args[++i]) * 1000;
+ http.timeout = Integer.parseInt(args[++i]) * 1000;
} else if (args[i].equals("-verbose")) { // found -verbose option
verbose = true;
} else if (i != args.length - 1) {
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
index 31e74b389..422b0814d 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
@@ -30,6 +30,7 @@ import java.util.logging.Logger;
// Nutch imports
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.net.protocols.Response;
@@ -45,14 +46,13 @@ import org.apache.nutch.protocol.ProtocolException;
* @author Mike Cafarella
* @author Doug Cutting
*/
-public class RobotRulesParser {
+public class RobotRulesParser implements NutchConfigurable {
+
public static final Logger LOG=
- LogFormatter.getLogger("org.apache.nutch.fetcher.RobotRulesParser");
+ LogFormatter.getLogger(RobotRulesParser.class.getName());
- private static final boolean ALLOW_FORBIDDEN =
- NutchConf.get().getBoolean("http.robots.403.allow", false);
+ private boolean allowForbidden = false;
- private static final String[] AGENTS = getAgents();
private static final Hashtable CACHE = new Hashtable();
private static final String CHARACTER_ENCODING= "UTF-8";
@@ -60,9 +60,9 @@ public class RobotRulesParser {
private static final RobotRuleSet EMPTY_RULES= new RobotRuleSet();
- private static RobotRuleSet FORBID_ALL_RULES =
- new RobotRulesParser().getForbidAllRules();
+ private static RobotRuleSet FORBID_ALL_RULES = getForbidAllRules();
+ private NutchConf conf;
private HashMap robotNames;
/**
@@ -86,14 +86,6 @@ public class RobotRulesParser {
}
}
- /**
- * should not be instantiated from outside RobotRulesParser
- */
- private RobotRuleSet() {
- tmpEntries= new ArrayList();
- entries= null;
- }
-
/**
*/
private void addPrefix(String prefix, boolean allow) {
@@ -182,14 +174,25 @@ public class RobotRulesParser {
}
- public RobotRulesParser() { this(AGENTS); }
+ RobotRulesParser() { }
+
+ public RobotRulesParser(NutchConf conf) {
+ setConf(conf);
+ }
+
+
+ /* ---------------------------------- *
+ * <implementation:NutchConfigurable> *
+ * ---------------------------------- */
- private static String[] getAgents() {
+ public void setConf(NutchConf conf) {
+ this.conf = conf;
+ allowForbidden = conf.getBoolean("http.robots.403.allow", false);
//
// Grab the agent names we advertise to robots files.
//
- String agentName = NutchConf.get().get("http.agent.name");
- String agentNames = NutchConf.get().get("http.robots.agents");
+ String agentName = conf.get("http.agent.name");
+ String agentNames = conf.get("http.robots.agents");
StringTokenizer tok = new StringTokenizer(agentNames, ",");
ArrayList agents = new ArrayList();
while (tok.hasMoreTokens()) {
@@ -197,22 +200,38 @@ public class RobotRulesParser {
}
//
- // If there are no agents for robots-parsing, use our
+ // If there are no agents for robots-parsing, use our
// default agent-string. If both are present, our agent-string
// should be the first one we advertise to robots-parsing.
- //
+ //
if (agents.size() == 0) {
agents.add(agentName);
LOG.severe("No agents listed in 'http.robots.agents' property!");
} else if (!((String)agents.get(0)).equalsIgnoreCase(agentName)) {
agents.add(0, agentName);
- LOG.severe("Agent we advertise (" + agentName
+ LOG.severe("Agent we advertise (" + agentName
+ ") not listed first in 'http.robots.agents' property!");
}
+ setRobotNames((String[]) agents.toArray(new String[agents.size()]));
+ }
- return (String[])agents.toArray(new String[agents.size()]);
+ public NutchConf getConf() {
+ return conf;
}
+ /* ---------------------------------- *
+ * <implementation:NutchConfigurable> *
+ * ---------------------------------- */
+
+ private void setRobotNames(String[] robotNames) {
+ this.robotNames= new HashMap();
+ for (int i= 0; i < robotNames.length; i++) {
+ this.robotNames.put(robotNames[i].toLowerCase(), new Integer(i));
+ }
+ // always make sure "*" is included
+ if (!this.robotNames.containsKey("*"))
+ this.robotNames.put("*", new Integer(robotNames.length));
+ }
/**
* Creates a new <code>RobotRulesParser</code> which will use the
@@ -223,14 +242,8 @@ public class RobotRulesParser {
* rules associated with the robot name having the smallest index
* will be used.
*/
- public RobotRulesParser(String[] robotNames) {
- this.robotNames= new HashMap();
- for (int i= 0; i < robotNames.length; i++) {
- this.robotNames.put(robotNames[i].toLowerCase(), new Integer(i));
- }
- // always make sure "*" is included
- if (!this.robotNames.containsKey("*"))
- this.robotNames.put("*", new Integer(robotNames.length));
+ RobotRulesParser(String[] robotNames) {
+ setRobotNames(robotNames);
}
/**
@@ -368,7 +381,7 @@ public class RobotRulesParser {
return rules;
}
- public static boolean isAllowed(HttpBase http, URL url)
+ public boolean isAllowed(HttpBase http, URL url)
throws ProtocolException, IOException {
String host = url.getHost();
@@ -382,8 +395,8 @@ public class RobotRulesParser {
new CrawlDatum(), true);
if (response.getCode() == 200) // found rules: parse them
- robotRules = new RobotRulesParser().parseRules(response.getContent());
- else if ( (response.getCode() == 403) && (!ALLOW_FORBIDDEN) )
+ robotRules = parseRules(response.getContent());
+ else if ( (response.getCode() == 403) && (!allowForbidden) )
robotRules = FORBID_ALL_RULES; // use forbid all
else
robotRules = EMPTY_RULES; // use default rules
diff --git a/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.java b/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.java
index 1141b38d2..5f08e0321 100644
--- a/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.java
+++ b/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.java
@@ -325,9 +325,10 @@ public class OntologyImpl implements org.apache.nutch.ontology.Ontology {
public static void main( String[] args ) throws Exception {
- Ontology ontology = OntologyFactory.getOntology();
+ NutchConf nutchConf = new NutchConf();
+ Ontology ontology = new OntologyFactory(nutchConf).getOntology();
- String urls = NutchConf.get().get("extension.ontology.urls");
+ String urls = nutchConf.get("extension.ontology.urls");
if (urls==null || urls.trim().equals("")) {
LOG.severe("No ontology url found.");
return;
diff --git a/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.java b/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.java
index 9623985fa..c77b2eead 100644
--- a/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.java
+++ b/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.java
@@ -25,6 +25,7 @@ import org.apache.nutch.parse.ParserFactory;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseException;
+import org.apache.nutch.util.NutchConf;
import junit.framework.TestCase;
@@ -50,12 +51,14 @@ public class TestOntology extends TestCase {
private String[] sampleFiles = {"time.owl"};
private static Ontology ontology;
-
+ private NutchConf nutchConf;
public TestOntology(String name) {
super(name);
}
- protected void setUp() {}
+ protected void setUp() {
+ this.nutchConf = new NutchConf();
+ }
protected void tearDown() {}
@@ -66,7 +69,7 @@ public class TestOntology extends TestCase {
if (ontology==null) {
try {
- ontology = OntologyFactory.getOntology();
+ ontology = new OntologyFactory(this.nutchConf).getOntology();
} catch (Exception e) {
throw new Exception("Failed to instantiate ontology");
}
diff --git a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java
index 254351c40..0baf1342d 100644
--- a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java
+++ b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java
@@ -28,6 +28,7 @@ import org.apache.nutch.parse.OutlinkExtractor;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.util.CommandRunner;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
@@ -55,39 +56,13 @@ public class ExtParser implements Parser {
static final int TIMEOUT_DEFAULT = 30; // in seconds
// handy map from String contentType to String[] {command, timeoutString}
- static Hashtable TYPE_PARAMS_MAP = new Hashtable();
+ Hashtable TYPE_PARAMS_MAP = new Hashtable();
- // set TYPE_PARAMS_MAP using plugin.xml of this plugin
- static {
- Extension[] extensions = PluginRepository.getInstance()
- .getExtensionPoint("org.apache.nutch.parse.Parser").getExtensions();
+ private NutchConf nutchConf;
- String contentType, command, timeoutString;
-
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
-
- // only look for extensions defined by plugin parse-ext
- if (!extension.getDescriptor().getPluginId().equals("parse-ext"))
- continue;
-
- contentType = extension.getAttribute("contentType");
- if (contentType == null || contentType.equals(""))
- continue;
+ private boolean loaded = false;
- command = extension.getAttribute("command");
- if (command == null || command.equals(""))
- continue;
-
- timeoutString = extension.getAttribute("timeout");
- if (timeoutString == null || timeoutString.equals(""))
- timeoutString = "" + TIMEOUT_DEFAULT;
-
- TYPE_PARAMS_MAP.put(contentType, new String[]{command, timeoutString});
- }
- }
-
- public ExtParser () {}
+ public ExtParser () { }
public Parse getParse(Content content) {
@@ -96,7 +71,7 @@ public class ExtParser implements Parser {
String[] params = (String[]) TYPE_PARAMS_MAP.get(contentType);
if (params == null)
return new ParseStatus(ParseStatus.FAILED,
- "No external command defined for contentType: " + contentType).getEmptyParse();
+ "No external command defined for contentType: " + contentType).getEmptyParse(getConf());
String command = params[0];
int timeout = Integer.parseInt(params[1]);
@@ -118,7 +93,7 @@ public class ExtParser implements Parser {
return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
"Content truncated at " + raw.length
+" bytes. Parser can't handle incomplete "
- + contentType + " file.").getEmptyParse();
+ + contentType + " file.").getEmptyParse(getConf());
}
ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE);
@@ -138,12 +113,12 @@ public class ExtParser implements Parser {
if (cr.getExitValue() != 0)
return new ParseStatus(ParseStatus.FAILED,
"External command " + command
- + " failed with error: " + es.toString()).getEmptyParse();
+ + " failed with error: " + es.toString()).getEmptyParse(getConf());
text = os.toString();
} catch (Exception e) { // run time exception
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
}
if (text == null)
@@ -153,14 +128,48 @@ public class ExtParser implements Parser {
title = "";
// collect outlink
- Outlink[] outlinks = OutlinkExtractor.getOutlinks(text);
+ Outlink[] outlinks = OutlinkExtractor.getOutlinks(text, getConf());
// collect meta data
ContentProperties metaData = new ContentProperties();
metaData.putAll(content.getMetadata()); // copy through
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);
+ parseData.setConf(this.nutchConf);
return new ParseImpl(text, parseData);
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ Extension[] extensions = conf.getPluginRepository().getExtensionPoint(
+ "org.apache.nutch.parse.Parser").getExtensions();
+
+ String contentType, command, timeoutString;
+
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+
+ // only look for extensions defined by plugin parse-ext
+ if (!extension.getDescriptor().getPluginId().equals("parse-ext"))
+ continue;
+
+ contentType = extension.getAttribute("contentType");
+ if (contentType == null || contentType.equals(""))
+ continue;
+
+ command = extension.getAttribute("command");
+ if (command == null || command.equals(""))
+ continue;
+
+ timeoutString = extension.getAttribute("timeout");
+ if (timeoutString == null || timeoutString.equals(""))
+ timeoutString = "" + TIMEOUT_DEFAULT;
+
+ TYPE_PARAMS_MAP.put(contentType, new String[] { command, timeoutString });
+ }
+ }
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.java b/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.java
index ac57b53dd..27159ac37 100644
--- a/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.java
+++ b/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.java
@@ -24,6 +24,7 @@ import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseUtil;
import org.apache.nutch.parse.ParseException;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.crawl.CrawlDatum;
@@ -79,7 +80,7 @@ public class TestExtParser extends TestCase {
fos.close();
// get nutch content
- Protocol protocol = ProtocolFactory.getProtocol(urlString);
+ Protocol protocol = new ProtocolFactory(new NutchConf()).getProtocol(urlString);
content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();
protocol = null;
}
@@ -103,18 +104,19 @@ public class TestExtParser extends TestCase {
return;
}
+ NutchConf nutchConf = new NutchConf();
// loop alternately, total 10*2 times of invoking external command
for (int i=0; i<10; i++) {
// check external parser that does 'cat'
contentType = "application/vnd.nutch.example.cat";
content.setContentType(contentType);
- parse = ParseUtil.parseByParserId("parse-ext", content);
+ parse = new ParseUtil(nutchConf).parseByParserId("parse-ext", content);
assertEquals(expectedText,parse.getText());
// check external parser that does 'md5sum'
contentType = "application/vnd.nutch.example.md5sum";
content.setContentType(contentType);
- parse = ParseUtil.parseByParserId("parse-ext", content);
+ parse = new ParseUtil(nutchConf).parseByParserId("parse-ext", content);
assertTrue(parse.getText().startsWith(expectedMD5sum));
}
}
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
index 3bce99e2f..dc59c5782 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.util.NutchConf;
import org.w3c.dom.*;
@@ -286,7 +287,7 @@ public class DOMContentUtils {
* nekohtml).
*/
public static final void getOutlinks(URL base, ArrayList outlinks,
- Node node) {
+ Node node, NutchConf nutchConf) {
NodeList children = node.getChildNodes();
int childLen= 0;
@@ -322,7 +323,7 @@ public class DOMContentUtils {
try {
URL url = new URL(base, target);
outlinks.add(new Outlink(url.toString(),
- linkText.toString().trim()));
+ linkText.toString().trim(), nutchConf));
} catch (MalformedURLException e) {
// don't care
}
@@ -332,7 +333,7 @@ public class DOMContentUtils {
}
}
for ( int i = 0; i < childLen; i++ ) {
- getOutlinks(base, outlinks, children.item(i));
+ getOutlinks(base, outlinks, children.item(i), nutchConf);
}
}
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
index f8feb9c36..108416761 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
@@ -51,7 +51,7 @@ public class HtmlParser implements Parser {
Pattern.compile("charset=\\s*([a-z][_\\-0-9a-z]*)",
Pattern.CASE_INSENSITIVE);
- private static String parserImpl = NutchConf.get().get("parser.html.impl", "neko");
+ private String parserImpl;
/**
* Given a <code>byte[]</code> representing an html file of an
@@ -91,8 +91,11 @@ public class HtmlParser implements Parser {
}
- private static String defaultCharEncoding =
- NutchConf.get().get("parser.character.encoding.default", "windows-1252");
+ private String defaultCharEncoding;
+
+ private NutchConf nutchConf;
+
+ private HtmlParseFilters htmlParseFilters;
public Parse getParse(Content content) {
HTMLMetaTags metaTags = new HTMLMetaTags();
@@ -101,7 +104,7 @@ public class HtmlParser implements Parser {
try {
base = new URL(content.getBaseUrl());
} catch (MalformedURLException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
}
String text = "";
@@ -151,14 +154,14 @@ public class HtmlParser implements Parser {
LOG.fine("Parsing...");
root = parse(input);
} catch (IOException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
} catch (DOMException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
} catch (SAXException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
} catch (Exception e) {
e.printStackTrace();
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
}
// get meta directives
@@ -180,7 +183,7 @@ public class HtmlParser implements Parser {
ArrayList l = new ArrayList(); // extract outlinks
URL baseTag = DOMContentUtils.getBase(root);
LOG.fine("Getting links...");
- DOMContentUtils.getOutlinks(baseTag!=null?baseTag:base, l, root);
+ DOMContentUtils.getOutlinks(baseTag!=null?baseTag:base, l, root, getConf());
outlinks = (Outlink[])l.toArray(new Outlink[l.size()]);
LOG.fine("found "+outlinks.length+" outlinks in "+content.getUrl());
}
@@ -197,10 +200,11 @@ public class HtmlParser implements Parser {
status.setMessage(metaTags.getRefreshHref().toString());
}
ParseData parseData = new ParseData(status, title, outlinks, metadata);
+ parseData.setConf(this.nutchConf);
Parse parse = new ParseImpl(text, parseData);
// run filters on parse
- return HtmlParseFilters.filter(content, parse, metaTags, root);
+ return this.htmlParseFilters.filter(content, parse, metaTags, root);
}
private DocumentFragment parse(InputSource input) throws Exception {
@@ -267,10 +271,22 @@ public class HtmlParser implements Parser {
in.readFully(bytes);
Parse parse = new HtmlParser().getParse(new Content(url,url,
bytes,"text/html",
- new ContentProperties()));
+ new ContentProperties(), new NutchConf()));
System.out.println("data: "+parse.getData());
System.out.println("text: "+parse.getText());
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.htmlParseFilters = new HtmlParseFilters(getConf());
+ this.parserImpl = getConf().get("parser.html.impl", "neko");
+ this.defaultCharEncoding = getConf().get(
+ "parser.character.encoding.default", "windows-1252");
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
index 3ed211a31..3418dcbfa 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
@@ -19,6 +19,7 @@ package org.apache.nutch.parse.html;
import junit.framework.TestCase;
import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.util.NutchConf;
import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
@@ -174,6 +175,7 @@ public class TestDOMContentUtils extends TestCase {
}
private static void setup() {
+ NutchConf nutchConf = new NutchConf();
DOMFragmentParser parser= new DOMFragmentParser();
for (int i= 0; i < testPages.length; i++) {
DocumentFragment node=
@@ -192,36 +194,36 @@ public class TestDOMContentUtils extends TestCase {
try {
answerOutlinks = new Outlink[][]{
{
- new Outlink("http://www.nutch.org", "anchor"),
+ new Outlink("http://www.nutch.org", "anchor", nutchConf),
},
{
- new Outlink("http://www.nutch.org/", "home"),
- new Outlink("http://www.nutch.org/docs/bot.html", "bots"),
+ new Outlink("http://www.nutch.org/", "home", nutchConf),
+ new Outlink("http://www.nutch.org/docs/bot.html", "bots", nutchConf),
},
{
- new Outlink("http://www.nutch.org/", "separate this"),
- new Outlink("http://www.nutch.org/docs/ok", "from this"),
+ new Outlink("http://www.nutch.org/", "separate this", nutchConf),
+ new Outlink("http://www.nutch.org/docs/ok", "from this", nutchConf),
},
{
- new Outlink("http://www.nutch.org/", "home"),
- new Outlink("http://www.nutch.org/docs/1", "1"),
- new Outlink("http://www.nutch.org/docs/2", "2"),
+ new Outlink("http://www.nutch.org/", "home", nutchConf),
+ new Outlink("http://www.nutch.org/docs/1", "1", nutchConf),
+ new Outlink("http://www.nutch.org/docs/2", "2", nutchConf),
},
{
- new Outlink("http://www.nutch.org/frames/top.html", ""),
- new Outlink("http://www.nutch.org/frames/left.html", ""),
- new Outlink("http://www.nutch.org/frames/invalid.html", ""),
- new Outlink("http://www.nutch.org/frames/right.html", ""),
+ new Outlink("http://www.nutch.org/frames/top.html", "", nutchConf),
+ new Outlink("http://www.nutch.org/frames/left.html", "", nutchConf),
+ new Outlink("http://www.nutch.org/frames/invalid.html", "", nutchConf),
+ new Outlink("http://www.nutch.org/frames/right.html", "", nutchConf),
},
{
- new Outlink("http://www.nutch.org/maps/logo.gif", ""),
- new Outlink("http://www.nutch.org/index.html", ""),
- new Outlink("http://www.nutch.org/maps/#bottom", ""),
- new Outlink("http://www.nutch.org/bot.html", ""),
- new Outlink("http://www.nutch.org/docs/index.html", ""),
+ new Outlink("http://www.nutch.org/maps/logo.gif", "", nutchConf),
+ new Outlink("http://www.nutch.org/index.html", "", nutchConf),
+ new Outlink("http://www.nutch.org/maps/#bottom", "", nutchConf),
+ new Outlink("http://www.nutch.org/bot.html", "", nutchConf),
+ new Outlink("http://www.nutch.org/docs/index.html", "", nutchConf),
},
{
- new Outlink("http://www.nutch.org/index.html", "whitespace test"),
+ new Outlink("http://www.nutch.org/index.html", "whitespace test", nutchConf),
},
{
}
@@ -282,7 +284,7 @@ public class TestDOMContentUtils extends TestCase {
setup();
for (int i= 0; i < testPages.length; i++) {
ArrayList outlinks= new ArrayList();
- DOMContentUtils.getOutlinks(testBaseHrefURLs[i], outlinks, testDOMs[i]);
+ DOMContentUtils.getOutlinks(testBaseHrefURLs[i], outlinks, testDOMs[i], new NutchConf());
Outlink[] outlinkArr= new Outlink[outlinks.size()];
outlinkArr= (Outlink[]) outlinks.toArray(outlinkArr);
compareOutlinks(answerOutlinks[i], outlinkArr);
diff --git a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
index 4117b5915..9651a88de 100644
--- a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
+++ b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
@@ -24,6 +24,7 @@ import org.apache.nutch.parse.Parser;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
@@ -50,6 +51,8 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
LogFormatter.getLogger("org.apache.nutch.parse.js.JSParseFilter");
private static final int MAX_TITLE_LEN = 80;
+
+ private NutchConf nutchConf;
public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
String url = content.getBaseUrl();
@@ -64,7 +67,9 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
ParseStatus status = parse.getData().getStatus();
String text = parse.getText();
Outlink[] newlinks = (Outlink[])outlinks.toArray(new Outlink[outlinks.size()]);
- parse = new ParseImpl(text, new ParseData(status, title, newlinks, metadata));
+ ParseData parseData = new ParseData(status, title, newlinks, metadata);
+ parseData.setConf(this.nutchConf);
+ parse = new ParseImpl(text, parseData);
}
return parse;
}
@@ -123,7 +128,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
String type = c.getContentType();
if (type != null && !type.trim().equals("") && !type.toLowerCase().startsWith("application/x-javascript"))
return new ParseStatus(ParseStatus.FAILED_INVALID_FORMAT,
- "Content not JavaScript: '" + type + "'").getEmptyParse();
+ "Content not JavaScript: '" + type + "'").getEmptyParse(getConf());
String script = new String(c.getContent());
Outlink[] outlinks = getJSLinks(script, c.getUrl(), c.getUrl());
if (outlinks == null) outlinks = new Outlink[0];
@@ -141,6 +146,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
metadata.putAll(c.getMetadata());
ParseData pd = new ParseData(ParseStatus.STATUS_SUCCESS, title,
outlinks, metadata);
+ pd.setConf(this.nutchConf);
Parse parse = new ParseImpl(script, pd);
return parse;
}
@@ -154,7 +160,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
/**
* This method extracts URLs from literals embedded in JavaScript.
*/
- private static Outlink[] getJSLinks(String plainText, String anchor, String base) {
+ private Outlink[] getJSLinks(String plainText, String anchor, String base) {
final List outlinks = new ArrayList();
URL baseURL = null;
@@ -195,7 +201,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
} else url = new URL(baseURL, url).toString();
url = url.replaceAll("&amp;", "&");
LOG.fine(" - outlink from JS: '" + url + "'");
- outlinks.add(new Outlink(url, anchor));
+ outlinks.add(new Outlink(url, anchor, getConf()));
}
} catch (Exception ex) {
// if it is a malformed URL we just throw it away and continue with
@@ -225,9 +231,19 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) sb.append(line + "\n");
- Outlink[] links = getJSLinks(sb.toString(), args[1], args[1]);
+ JSParseFilter parseFilter = new JSParseFilter();
+ parseFilter.setConf(new NutchConf());
+ Outlink[] links = parseFilter.getJSLinks(sb.toString(), args[1], args[1]);
System.out.println("Outlinks extracted: " + links.length);
for (int i = 0; i < links.length; i++)
System.out.println(" - " + links[i]);
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.java b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.java
index c8f4aa676..2d02e4673 100644
--- a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.java
+++ b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.java
@@ -19,6 +19,7 @@ package org.apache.nutch.parse.mp3;
import org.apache.nutch.parse.*;
import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.NutchConf;
import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.AbstractID3v2;
@@ -39,7 +40,8 @@ import java.util.Iterator;
public class MP3Parser implements Parser {
- private MetadataCollector metadataCollector = new MetadataCollector();
+ private MetadataCollector metadataCollector;
+ private NutchConf nutchConf;
public Parse getParse(Content content) throws ParseException {
Parse parse = null;
@@ -84,7 +86,7 @@ public class MP3Parser implements Parser {
metadataCollector.notifyProperty("TYER-Text", tag.getYear());
ParseData parseData = new ParseData(metadataCollector.getTitle(),
metadataCollector.getOutlinks(),
- metadataCollector.getData());
+ metadataCollector.getData(), getConf());
return new ParseImpl(metadataCollector.getText(), parseData);
}
@@ -113,4 +115,12 @@ public class MP3Parser implements Parser {
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.metadataCollector = new MetadataCollector(conf);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.java b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.java
index 613e64292..669cc737a 100644
--- a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.java
+++ b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.java
@@ -17,6 +17,7 @@
package org.apache.nutch.parse.mp3;
import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.util.NutchConf;
import java.net.MalformedURLException;
import java.util.ArrayList;
@@ -34,7 +35,12 @@ public class MetadataCollector {
private String album = null;
private ArrayList links = new ArrayList();
private String text = "";
+ private NutchConf nutchConf;
+ public MetadataCollector(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ }
+
public void notifyProperty(String name, String value) throws MalformedURLException {
if (name.equals("TIT2-Text"))
setTitle(value);
@@ -44,7 +50,7 @@ public class MetadataCollector {
setArtist(value);
if (name.indexOf("URL Link") > -1) {
- links.add(new Outlink(value, ""));
+ links.add(new Outlink(value, "", this.nutchConf));
} else if (name.indexOf("Text") > -1) {
text += value + "\n";
}
diff --git a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.java b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.java
index a5c1e23f5..f8bb0d564 100644
--- a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.java
+++ b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.java
@@ -32,6 +32,7 @@ import org.apache.nutch.parse.Parser;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/**
* Nutch-Parser for parsing MS PowerPoint slides ( mime type:
@@ -51,6 +52,8 @@ public class MSPowerPointParser implements Parser {
private static final Logger LOG = LogFormatter
.getLogger(MSPowerPointParser.class.getName());
+ private NutchConf nutchConf;
+
/**
*
*/
@@ -77,7 +80,7 @@ public class MSPowerPointParser implements Parser {
ContentProperties prop = new ContentProperties();
prop.setProperty("Content-Length", "" + raw.length);
- Content content = new Content(file, file, raw, MIME_TYPE, prop);
+ Content content = new Content(file, file, raw, MIME_TYPE, prop, new NutchConf());
System.out.println(ppe.getParse(content).getText());
}
@@ -106,7 +109,7 @@ public class MSPowerPointParser implements Parser {
+ raw.length
+ " bytes. Please increase <protocol>.content.limit at nutch-default.xml. "
+ "Parser can't handle incomplete PowerPoint files.")
- .getEmptyParse();
+ .getEmptyParse(getConf());
}
final PPTExtractor extractor = new PPTExtractor(new ByteArrayInputStream(
@@ -114,11 +117,11 @@ public class MSPowerPointParser implements Parser {
plainText = extractor.getText();
properties = extractor.getProperties();
- outlinks = OutlinkExtractor.getOutlinks(plainText, content.getUrl());
+ outlinks = OutlinkExtractor.getOutlinks(plainText, content.getUrl(), getConf());
} catch (Exception e) {
LOG.throwing(this.getClass().getName(), "getParse", e);
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
}
// collect meta data
@@ -141,6 +144,7 @@ public class MSPowerPointParser implements Parser {
final ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);
final ParseData parseData = new ParseData(status, title, outlinks, metadata);
+ parseData.setConf(this.nutchConf);
LOG.finest("PowerPoint file parsed sucessful.");
return new ParseImpl(plainText, parseData);
@@ -161,4 +165,12 @@ public class MSPowerPointParser implements Parser {
}
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.java b/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.java
index 002a8eba5..9a509bcec 100644
--- a/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.java
+++ b/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.java
@@ -34,6 +34,7 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolFactory;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.crawl.CrawlDatum;
@@ -105,7 +106,7 @@ public class TestMSPowerPointParser extends TestCase {
this.urlString = createUrl(this.testFile.getName());
System.out.println("Testing file: " + this.urlString + "...");
- this.protocol = ProtocolFactory.getProtocol(this.urlString);
+ this.protocol =new ProtocolFactory(new NutchConf()).getProtocol(this.urlString);
this.content = this.protocol.getProtocolOutput(new UTF8(this.urlString), new CrawlDatum()).getContent();
}
@@ -125,7 +126,7 @@ public class TestMSPowerPointParser extends TestCase {
*/
public void testContent() throws Exception {
- Parse parse = ParseUtil.parseByParserId("parse-mspowerpoint",this.content);
+ Parse parse = new ParseUtil(new NutchConf()).parseByParserId("parse-mspowerpoint",this.content);
ParseData data = parse.getData();
String text = parse.getText();
@@ -162,7 +163,7 @@ public class TestMSPowerPointParser extends TestCase {
*/
public void testMeta() throws Exception {
- Parse parse = ParseUtil.parseByParserId("parse-mspowerpoint",content);
+ Parse parse = new ParseUtil(new NutchConf()).parseByParserId("parse-mspowerpoint",content);
ParseData data = parse.getData();
diff --git a/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java b/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java
index e009b739b..3ee78b738 100644
--- a/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java
+++ b/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java
@@ -19,6 +19,7 @@ package org.apache.nutch.parse.msword;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.Parse;
@@ -50,6 +51,8 @@ import java.io.ByteArrayInputStream;
*/
public class MSWordParser implements Parser {
+ private NutchConf nutchConf;
+
// public static final Logger LOG =
// LogFormatter.getLogger("org.apache.nutch.parse.msword");
@@ -70,7 +73,7 @@ public class MSWordParser implements Parser {
&& raw.length != Integer.parseInt(contentLength)) {
return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
"Content truncated at " + raw.length
- +" bytes. Parser can't handle incomplete msword file.").getEmptyParse();
+ +" bytes. Parser can't handle incomplete msword file.").getEmptyParse(this.nutchConf);
}
WordExtractor extractor = new WordExtractor();
@@ -84,14 +87,14 @@ public class MSWordParser implements Parser {
extractor = null;
} catch (ParseException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(this.nutchConf);
} catch (FastSavedException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(this.nutchConf);
} catch (PasswordProtectedException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(this.nutchConf);
} catch (Exception e) { // run time exception
return new ParseStatus(ParseStatus.FAILED,
- "Can't be handled as msword document. " + e).getEmptyParse();
+ "Can't be handled as msword document. " + e).getEmptyParse(this.nutchConf);
} finally {
// nothing so far
}
@@ -113,12 +116,21 @@ public class MSWordParser implements Parser {
title = "";
// collect outlink
- Outlink[] outlinks = OutlinkExtractor.getOutlinks(text);
+ Outlink[] outlinks = OutlinkExtractor.getOutlinks(text, this.nutchConf);
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metadata);
+ parseData.setConf(this.nutchConf);
return new ParseImpl(text, parseData);
// any filter?
//return HtmlParseFilters.filter(content, parse, root);
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java b/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java
index bba3ca675..62a65c00f 100644
--- a/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java
+++ b/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java
@@ -24,6 +24,7 @@ import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseUtil;
import org.apache.nutch.parse.ParseException;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.crawl.CrawlDatum;
@@ -61,12 +62,13 @@ public class TestMSWordParser extends TestCase {
Content content;
Parse parse;
+ NutchConf nutchConf = new NutchConf();
for (int i=0; i<sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
- protocol = ProtocolFactory.getProtocol(urlString);
+ protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);
content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();
- parse = ParseUtil.parseByParserId("parse-msword",content);
+ parse = new ParseUtil(nutchConf).parseByParserId("parse-msword",content);
assertTrue(parse.getText().startsWith(expectedText));
}
diff --git a/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java b/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java
index bc83439f5..8978d85ea 100644
--- a/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java
+++ b/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java
@@ -28,6 +28,7 @@ import org.pdfbox.exceptions.InvalidPasswordException;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.Parse;
@@ -62,6 +63,7 @@ import java.io.IOException;
public class PdfParser implements Parser {
public static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.parse.pdf");
+ private NutchConf nutchConf;
public PdfParser () {
// redirect org.apache.log4j.Logger to java's native logger, in order
@@ -99,7 +101,7 @@ public class PdfParser implements Parser {
&& raw.length != Integer.parseInt(contentLength)) {
return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
"Content truncated at "+raw.length
- +" bytes. Parser can't handle incomplete pdf file.").getEmptyParse();
+ +" bytes. Parser can't handle incomplete pdf file.").getEmptyParse(getConf());
}
PDFParser parser = new PDFParser(
@@ -134,13 +136,13 @@ public class PdfParser implements Parser {
} catch (CryptographyException e) {
return new ParseStatus(ParseStatus.FAILED,
- "Error decrypting document. " + e).getEmptyParse();
+ "Error decrypting document. " + e).getEmptyParse(getConf());
} catch (InvalidPasswordException e) {
return new ParseStatus(ParseStatus.FAILED,
- "Can't decrypt document - invalid password. " + e).getEmptyParse();
+ "Can't decrypt document - invalid password. " + e).getEmptyParse(getConf());
} catch (Exception e) { // run time exception
return new ParseStatus(ParseStatus.FAILED,
- "Can't be handled as pdf document. " + e).getEmptyParse();
+ "Can't be handled as pdf document. " + e).getEmptyParse(getConf());
} finally {
try {
if (pdf != null)
@@ -157,13 +159,14 @@ public class PdfParser implements Parser {
title = "";
// collect outlink
- Outlink[] outlinks = OutlinkExtractor.getOutlinks(text);
+ Outlink[] outlinks = OutlinkExtractor.getOutlinks(text, getConf());
// collect meta data
ContentProperties metadata = new ContentProperties();
metadata.putAll(content.getMetadata()); // copy through
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metadata);
+ parseData.setConf(this.nutchConf);
return new ParseImpl(text, parseData);
// any filter?
//return HtmlParseFilters.filter(content, parse, root);
@@ -180,4 +183,12 @@ public class PdfParser implements Parser {
return retval;
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java b/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java
index 9253816f3..13b1f9bec 100644
--- a/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java
+++ b/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java
@@ -24,6 +24,7 @@ import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseUtil;
import org.apache.nutch.parse.ParseException;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.crawl.CrawlDatum;
@@ -64,9 +65,10 @@ public class TestPdfParser extends TestCase {
for (int i=0; i<sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
- protocol = ProtocolFactory.getProtocol(urlString);
+ NutchConf nutchConf = new NutchConf();
+ protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);
content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();
- parse = ParseUtil.parseByParserId("parse-pdf",content);
+ parse = new ParseUtil(nutchConf).parseByParserId("parse-pdf",content);
int index = parse.getText().indexOf(expectedText);
assertTrue(index > 0);
diff --git a/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java b/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java
index c0d9f8f89..31ff12050 100644
--- a/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java
+++ b/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java
@@ -18,6 +18,7 @@ package org.apache.nutch.parse.rss;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseStatus;
@@ -63,6 +64,7 @@ import org.apache.commons.feedparser.network.ResourceRequest;
public class RSSParser implements Parser {
public static final Logger LOG = LogFormatter
.getLogger("org.apache.nutch.parse.rss");
+ private NutchConf nutchConf;
/**
* <p>
@@ -122,7 +124,7 @@ public class RSSParser implements Parser {
e.printStackTrace();
LOG.fine("nutch:parse-rss:RSSParser Exception: " + e.getMessage());
return new ParseStatus(ParseStatus.FAILED,
- "Can't be handled as rss document. " + e).getEmptyParse();
+ "Can't be handled as rss document. " + e).getEmptyParse(getConf());
}
StringBuffer contentTitle = new StringBuffer(), indexText = new StringBuffer();
@@ -149,9 +151,9 @@ public class RSSParser implements Parser {
try {
// get the outlink
if (r.getDescription()!= null ) {
- theOutlinks.add(new Outlink(r.getLink(), r.getDescription()));
+ theOutlinks.add(new Outlink(r.getLink(), r.getDescription(), getConf()));
} else {
- theOutlinks.add(new Outlink(r.getLink(), ""));
+ theOutlinks.add(new Outlink(r.getLink(), "", getConf()));
}
} catch (MalformedURLException e) {
LOG.info("nutch:parse-rss:RSSParser Exception: MalformedURL: "
@@ -179,9 +181,9 @@ public class RSSParser implements Parser {
if (whichLink != null) {
try {
if (theRSSItem.getDescription()!=null) {
- theOutlinks.add(new Outlink(whichLink, theRSSItem.getDescription()));
+ theOutlinks.add(new Outlink(whichLink, theRSSItem.getDescription(), getConf()));
} else {
- theOutlinks.add(new Outlink(whichLink, ""));
+ theOutlinks.add(new Outlink(whichLink, "", getConf()));
}
} catch (MalformedURLException e) {
LOG.info("nutch:parse-rss:RSSParser Exception: MalformedURL: "
@@ -211,7 +213,16 @@ public class RSSParser implements Parser {
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS,
contentTitle.toString(), outlinks, content.getMetadata());
+ parseData.setConf(this.nutchConf);
return new ParseImpl(indexText.toString(), parseData);
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.java b/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.java
index d5ccec59e..eed306783 100644
--- a/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.java
+++ b/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.java
@@ -26,6 +26,7 @@ import org.apache.nutch.parse.ParseUtil;
import org.apache.nutch.parse.ParseException;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.crawl.CrawlDatum;
@@ -79,12 +80,13 @@ public class TestRSSParser extends TestCase {
Content content;
Parse parse;
+ NutchConf nutchConf = new NutchConf();
for (int i = 0; i < sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
- protocol = ProtocolFactory.getProtocol(urlString);
+ protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);
content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();
- parse = ParseUtil.parseByParserId("parse-rss",content);
+ parse = new ParseUtil(nutchConf).parseByParserId("parse-rss",content);
//check that there are 3 outlinks:
//http://test.channel.com
diff --git a/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.java b/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.java
index 13fcf7c10..91672ac4c 100644
--- a/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.java
+++ b/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.java
@@ -17,9 +17,8 @@
package org.apache.nutch.parse.rtf;
import org.apache.nutch.parse.*;
-import org.apache.nutch.parse.ParseException;
import org.apache.nutch.protocol.Content;
-
+import org.apache.nutch.util.NutchConf;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
@@ -29,10 +28,13 @@ import com.etranslate.tm.processing.rtf.RTFParser;
/**
* A parser for RTF documents
+ *
* @author Andy Hedges
*/
public class RTFParseFactory implements Parser {
+ private NutchConf nutchConf;
+
public Parse getParse(Content content) throws ParseException {
byte[] raw = content.getContent();
Reader reader = new InputStreamReader(new ByteArrayInputStream(raw));
@@ -53,7 +55,7 @@ public class RTFParseFactory implements Parser {
metadata.putAll(delegate.getMetaData());
String title = metadata.getProperty("title");
- if(title != null){
+ if (title != null) {
metadata.remove(title);
} else {
title = "";
@@ -61,11 +63,15 @@ public class RTFParseFactory implements Parser {
String text = delegate.getText();
- return new ParseImpl(text,
- new ParseData(title,
- OutlinkExtractor.getOutlinks(text),
- metadata));
+ return new ParseImpl(text, new ParseData(title, OutlinkExtractor
+ .getOutlinks(text, this.nutchConf), metadata));
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.java b/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.java
index 5ba1aafe0..8b4f3a812 100644
--- a/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.java
+++ b/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.java
@@ -25,6 +25,7 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.protocol.ProtocolFactory;
+import org.apache.nutch.util.NutchConf;
import java.util.Properties;
@@ -60,11 +61,12 @@ public class TestRTFParser extends TestCase {
Content content;
Parse parse;
+ NutchConf nutchConf = new NutchConf();
urlString = "file:" + sampleDir + fileSeparator + rtfFile;
- protocol = ProtocolFactory.getProtocol(urlString);
+ protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);
content = protocol.getContent(urlString);
- parse = ParseUtil.parseByParserId("parse-rtf",content);
+ parse = new ParseUtil(nutchConf).parseByParserId("parse-rtf", content);
String text = parse.getText();
assertEquals("The quick brown fox jumps over the lazy dog", text.trim());
diff --git a/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java b/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java
index bd11a1c3d..5cee59078 100644
--- a/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java
+++ b/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java
@@ -24,31 +24,42 @@ import org.apache.nutch.parse.*;
import org.apache.nutch.util.*;
public class TextParser implements Parser {
+ private NutchConf nutchConf;
+
public Parse getParse(Content content) {
// copy content meta data through
ContentProperties metadata = new ContentProperties();
metadata.putAll(content.getMetadata());
- //ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "", new Outlink[0], metadata);
+ // ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "", new
+ // Outlink[0], metadata);
- String encoding =
- StringUtil.parseCharacterEncoding(content.getContentType());
+ String encoding = StringUtil.parseCharacterEncoding(content
+ .getContentType());
String text;
- if (encoding != null) { // found an encoding header
- try { // try to use named encoding
+ if (encoding != null) { // found an encoding header
+ try { // try to use named encoding
text = new String(content.getContent(), encoding);
} catch (java.io.UnsupportedEncodingException e) {
- return new ParseStatus(e).getEmptyParse();
+ return new ParseStatus(e).getEmptyParse(getConf());
}
} else {
- // FIXME: implement charset detector. This code causes problem when
- // character set isn't specified in HTTP header.
- text = new String(content.getContent()); // use default encoding
+ // FIXME: implement charset detector. This code causes problem when
+ // character set isn't specified in HTTP header.
+ text = new String(content.getContent()); // use default encoding
}
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "",
+ OutlinkExtractor.getOutlinks(text, getConf()), metadata);
+ parseData.setConf(this.nutchConf);
+ return new ParseImpl(text, parseData);
+
+ }
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
- return new ParseImpl(text,
- new ParseData(ParseStatus.STATUS_SUCCESS, "",
- OutlinkExtractor.getOutlinks(text),
- metadata));
+ public NutchConf getConf() {
+ return this.nutchConf;
}
}
diff --git a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java
index e1709a7a4..9465d7b26 100644
--- a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java
+++ b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java
@@ -33,73 +33,87 @@ import org.apache.nutch.parse.Parser;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/**
* ZipParser class based on MSPowerPointParser class by Stephan Strittmatter.
* Nutch parse plugin for zip files - Content Type : application/zip
+ *
* @author Rohit Kulkarni & Ashish Vaidya
*/
-public class ZipParser implements Parser{
-
- private static final Logger LOG = LogFormatter.getLogger(ZipParser.class.getName());
- /** Creates a new instance of ZipParser */
- public ZipParser() {
+public class ZipParser implements Parser {
+
+ private static final Logger LOG = LogFormatter.getLogger(ZipParser.class
+ .getName());
+ private NutchConf nutchConf;
+
+ /** Creates a new instance of ZipParser */
+ public ZipParser() {
+ }
+
+ public Parse getParse(final Content content) {
+
+ String resultText = null;
+ String resultTitle = null;
+ Outlink[] outlinks = null;
+ List outLinksList = new ArrayList();
+ Properties properties = null;
+
+ try {
+ final String contentLen = content.get("Content-Length");
+ final int len = Integer.parseInt(contentLen);
+ System.out.println("ziplen: " + len);
+ final byte[] contentInBytes = content.getContent();
+ final ByteArrayInputStream bainput = new ByteArrayInputStream(
+ contentInBytes);
+ final InputStream input = bainput;
+
+ if (contentLen != null && contentInBytes.length != len) {
+ return new ParseStatus(ParseStatus.FAILED,
+ ParseStatus.FAILED_TRUNCATED, "Content truncated at "
+ + contentInBytes.length
+ + " bytes. Parser can't handle incomplete pdf file.")
+ .getEmptyParse(getConf());
+ }
+
+ ZipTextExtractor extractor = new ZipTextExtractor(getConf());
+
+ // extract text
+ resultText = extractor.extractText(new ByteArrayInputStream(
+ contentInBytes), content.getUrl(), outLinksList);
+
+ } catch (Exception e) {
+ return new ParseStatus(ParseStatus.FAILED,
+ "Can't be handled as Zip document. " + e).getEmptyParse(getConf());
}
-
- public Parse getParse(final Content content) {
-
- String resultText = null;
- String resultTitle = null;
- Outlink[] outlinks = null;
- List outLinksList = new ArrayList();
- Properties properties = null;
-
- try {
- final String contentLen = content.get("Content-Length");
- final int len = Integer.parseInt(contentLen);
- System.out.println("ziplen: " + len);
- final byte[] contentInBytes = content.getContent();
- final ByteArrayInputStream bainput = new ByteArrayInputStream(contentInBytes);
- final InputStream input = bainput;
-
- if (contentLen != null && contentInBytes.length != len) {
- return new ParseStatus(ParseStatus.FAILED,
- ParseStatus.FAILED_TRUNCATED,
- "Content truncated at " + contentInBytes.length +
- " bytes. Parser can't handle incomplete pdf file.").getEmptyParse();
- }
-
- ZipTextExtractor extractor = new ZipTextExtractor();
-
- // extract text
- resultText = extractor.extractText(new ByteArrayInputStream(contentInBytes),
- content.getUrl(), outLinksList);
-
- } catch (Exception e) {
- return new ParseStatus(ParseStatus.FAILED,
- "Can't be handled as Zip document. " + e).getEmptyParse();
- }
-
- // collect meta data
- final ContentProperties metadata = new ContentProperties();
- metadata.putAll(content.getMetadata()); // copy through
-
- if (resultText == null) {
- resultText = "";
- }
-
- if (resultTitle == null) {
- resultTitle = "";
- }
-
- outlinks = (Outlink[])outLinksList.toArray(new Outlink[0]);
- final ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS,
- resultTitle,
- outlinks,
- metadata);
-
- LOG.finest("Zip file parsed sucessfully !!");
- return new ParseImpl(resultText, parseData);
+
+ // collect meta data
+ final ContentProperties metadata = new ContentProperties();
+ metadata.putAll(content.getMetadata()); // copy through
+
+ if (resultText == null) {
+ resultText = "";
}
-
+
+ if (resultTitle == null) {
+ resultTitle = "";
+ }
+
+ outlinks = (Outlink[]) outLinksList.toArray(new Outlink[0]);
+ final ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS,
+ resultTitle, outlinks, metadata);
+ parseData.setConf(this.nutchConf);
+
+ LOG.finest("Zip file parsed sucessfully !!");
+ return new ParseImpl(resultText, parseData);
+ }
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java
index 527271529..8db5d47e0 100644
--- a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java
+++ b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java
@@ -46,14 +46,17 @@ import org.apache.nutch.util.mime.MimeTypes;
public class ZipTextExtractor {
/** Get the MimeTypes resolver instance. */
- private final static MimeTypes MIME =
- MimeTypes.get(NutchConf.get().get("mime.types.file"));
+ private MimeTypes MIME;
public static final Logger LOG = LogFormatter.getLogger(ZipTextExtractor.class.getName());
+
+private NutchConf nutchConf;
/** Creates a new instance of ZipTextExtractor */
- public ZipTextExtractor() {
+ public ZipTextExtractor(NutchConf nutchConf) {
+ this.nutchConf = nutchConf;
+ this.MIME = MimeTypes.get(nutchConf.get("mime.types.file"));
}
public String extractText(InputStream input, String url, List outLinksList) throws IOException {
@@ -88,13 +91,13 @@ public class ZipTextExtractor {
ContentProperties metadata = new ContentProperties();
metadata.setProperty("Content-Length", Long.toString(entry.getSize()));
metadata.setProperty("Content-Type", contentType);
- Content content = new Content(newurl, base, b, contentType, metadata);
- Parse parse = ParseUtil.parse(content);
+ Content content = new Content(newurl, base, b, contentType, metadata, this.nutchConf);
+ Parse parse = new ParseUtil(this.nutchConf).parse(content);
ParseData theParseData = parse.getData();
Outlink[] theOutlinks = theParseData.getOutlinks();
for(int count = 0; count < theOutlinks.length; count++) {
- outLinksList.add(new Outlink(theOutlinks[count].getToUrl(), theOutlinks[count].getAnchor()));
+ outLinksList.add(new Outlink(theOutlinks[count].getToUrl(), theOutlinks[count].getAnchor(), this.nutchConf));
}
resultText += entry.getName() + " " + parse.getText() + " ";
diff --git a/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.java b/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.java
index 1dc67dbad..856cdd6f0 100644
--- a/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.java
+++ b/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.java
@@ -24,6 +24,7 @@ import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseUtil;
import org.apache.nutch.parse.ParseException;
+import org.apache.nutch.util.NutchConf;
import org.apache.nutch.io.UTF8;
import org.apache.nutch.crawl.CrawlDatum;
@@ -61,12 +62,13 @@ public class TestZipParser extends TestCase {
Content content;
Parse parse;
+ NutchConf conf = new NutchConf();
for (int i = 0; i < sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
- protocol = ProtocolFactory.getProtocol(urlString);
+ protocol = new ProtocolFactory(conf).getProtocol(urlString);
content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();
- parse = ParseUtil.parseByParserId("parse-zip",content);
+ parse = new ParseUtil(conf).parseByParserId("parse-zip",content);
assertTrue(parse.getText().equals(expectedText));
}
}
diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
index e0a471cbb..3b4c4d3f5 100644
--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
@@ -50,7 +50,7 @@ public class File implements Protocol {
static final int MAX_REDIRECTS = 5;
- static int maxContentLength = NutchConf.get().getInt("file.content.limit", 64 * 1024);
+ int maxContentLength;
// 20040412, xing
// the following three: HttpDateFormat, MimetypesFileTypeMap, MagicFile
@@ -59,6 +59,8 @@ public class File implements Protocol {
// http date format
HttpDateFormat httpDateFormat = null;
+ private NutchConf nutchConf;
+
// constructor
public File() {
this.httpDateFormat = new HttpDateFormat();
@@ -76,7 +78,7 @@ public class File implements Protocol {
while (true) {
FileResponse response;
- response = new FileResponse(u, datum, this); // make a request
+ response = new FileResponse(u, datum, this, getConf()); // make a request
int code = response.getCode();
@@ -152,4 +154,12 @@ public class File implements Protocol {
file = null;
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.maxContentLength = conf.getInt("file.content.limit", 64 * 1024);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java
index 4398f3b10..d63dc7b67 100644
--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java
+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java
@@ -26,6 +26,7 @@ import java.io.IOException;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
+import org.apache.nutch.util.NutchConf;
/************************************
@@ -63,6 +64,7 @@ public class FileResponse {
private ContentProperties headers = new ContentProperties();
private final File file;
+ private NutchConf nutchConf;
/** Returns the response code. */
public int getCode() { return code; }
@@ -77,15 +79,16 @@ public class FileResponse {
public Content toContent() {
return new Content(orig, base, content,
getHeader("Content-Type"),
- headers);
+ headers, this.nutchConf);
}
- public FileResponse(URL url, CrawlDatum datum, File file)
+ public FileResponse(URL url, CrawlDatum datum, File file, NutchConf nutchConf)
throws FileException, IOException {
this.orig = url.toString();
this.base = url.toString();
this.file = file;
+ this.nutchConf = nutchConf;
if (!"file".equals(url.getProtocol()))
throw new FileException("Not a file url:" + url);
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java
index 58b835718..d2d31b2a8 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java
@@ -56,23 +56,23 @@ public class Ftp implements Protocol {
static final int MAX_REDIRECTS = 5;
- static int timeout = NutchConf.get().getInt("ftp.timeout", 10000);
+ int timeout;
- static int maxContentLength = NutchConf.get().getInt("ftp.content.limit",64*1024);
+ int maxContentLength;
- String userName = NutchConf.get().get("ftp.username", "anonymous");
- String passWord = NutchConf.get().get("ftp.password", "[email protected]");
+ String userName;
+ String passWord;
// typical/default server timeout is 120*1000 millisec.
// better be conservative here
- int serverTimeout = NutchConf.get().getInt("ftp.server.timeout", 60*1000);
+ int serverTimeout;
// when to have client start anew
long renewalTime = -1;
- boolean keepConnection = NutchConf.get().getBoolean("ftp.keep.connection", false);
+ boolean keepConnection;
- boolean followTalk = NutchConf.get().getBoolean("ftp.follow.talk", false);
+ boolean followTalk;
// ftp client
Client client = null;
@@ -86,6 +86,8 @@ public class Ftp implements Protocol {
// http date format
HttpDateFormat httpDateFormat = null;
+ private NutchConf nutchConf;
+
// constructor
public Ftp() {
@@ -121,7 +123,7 @@ public class Ftp implements Protocol {
while (true) {
FtpResponse response;
- response = new FtpResponse(u, datum, this); // make a request
+ response = new FtpResponse(u, datum, this, getConf()); // make a request
int code = response.getCode();
@@ -220,4 +222,20 @@ public class Ftp implements Protocol {
ftp = null;
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.maxContentLength = conf.getInt("ftp.content.limit", 64 * 1024);
+ this.timeout = conf.getInt("ftp.timeout", 10000);
+ this.userName = conf.get("ftp.username", "anonymous");
+ this.passWord = conf.get("ftp.password", "[email protected]");
+ this.serverTimeout = conf.getInt("ftp.server.timeout", 60 * 1000);
+ this.keepConnection = conf.getBoolean("ftp.keep.connection", false);
+ this.followTalk = conf.getBoolean("ftp.follow.talk", false);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java
index 402896cde..d80a19692 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java
@@ -27,6 +27,7 @@ import org.apache.commons.net.ftp.parser.ParserInitializationException;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.ContentProperties;
+import org.apache.nutch.util.NutchConf;
import java.net.InetAddress;
import java.net.URL;
@@ -64,6 +65,7 @@ public class FtpResponse {
private ContentProperties headers = new ContentProperties();
private final Ftp ftp;
+ private NutchConf nutchConf;
/** Returns the response code. */
public int getCode() { return code; }
@@ -78,15 +80,16 @@ public class FtpResponse {
public Content toContent() {
return new Content(orig, base, content,
getHeader("Content-Type"),
- headers);
+ headers, this.nutchConf);
}
- public FtpResponse(URL url, CrawlDatum datum, Ftp ftp)
+ public FtpResponse(URL url, CrawlDatum datum, Ftp ftp, NutchConf nutchConf)
throws FtpException, IOException {
this.orig = url.toString();
this.base = url.toString();
this.ftp = ftp;
+ this.nutchConf = nutchConf;
if (!"ftp".equals(url.getProtocol()))
throw new FtpException("Not a ftp url:" + url);
diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
index c9d038ffe..d9eed3176 100755
--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
@@ -33,25 +33,29 @@ import org.apache.nutch.util.NutchConf;
public class Http extends HttpBase {
public static final Logger LOG =
- LogFormatter.getLogger("org.apache.nutch.net.Http");
-
- static {
- if (NutchConf.get().getBoolean("http.verbose", false))
- LOG.setLevel(Level.FINE);
- }
+ LogFormatter.getLogger(Http.class.getName());
public Http() {
super(LOG);
}
+ public void setConf(NutchConf conf) {
+ super.setConf(conf);
+ Level logLevel = Level.WARNING;
+ if (conf.getBoolean("http.verbose", false)) {
+ logLevel = Level.FINE;
+ }
+ LOG.setLevel(logLevel);
+ }
+
public static void main(String[] args) throws Exception {
main(new Http(), args);
}
protected Response getResponse(URL url, CrawlDatum datum, boolean redirect)
throws ProtocolException, IOException {
- return new HttpResponse(url, datum);
+ return new HttpResponse(this, url, datum);
}
}
diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
index f209b6885..1cc6adb40 100644
--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
@@ -35,13 +35,15 @@ import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.protocol.ProtocolException;
+import org.apache.nutch.protocol.http.api.HttpBase;
import org.apache.nutch.protocol.http.api.HttpException;
import org.apache.nutch.util.GZIPUtils;
/** An HTTP response. */
public class HttpResponse implements Response {
-
+
+ private HttpBase http;
private URL url;
private String orig;
private String base;
@@ -50,9 +52,10 @@ public class HttpResponse implements Response {
private ContentProperties headers = new ContentProperties();
- public HttpResponse(URL url, CrawlDatum datum)
+ public HttpResponse(HttpBase http, URL url, CrawlDatum datum)
throws ProtocolException, IOException {
+ this.http = http;
this.url = url;
this.orig = url.toString();
this.base = url.toString();
@@ -83,20 +86,20 @@ public class HttpResponse implements Response {
try {
socket = new Socket(); // create the socket
- socket.setSoTimeout(Http.TIMEOUT);
+ socket.setSoTimeout(http.getTimeout());
// connect
- String sockHost = Http.PROXY ? Http.PROXY_HOST : host;
- int sockPort = Http.PROXY ? Http.PROXY_PORT : port;
+ String sockHost = http.useProxy() ? http.getProxyHost() : host;
+ int sockPort = http.useProxy() ? http.getProxyPort() : port;
InetSocketAddress sockAddr= new InetSocketAddress(sockHost, sockPort);
- socket.connect(sockAddr, Http.TIMEOUT);
+ socket.connect(sockAddr, http.getTimeout());
// make request
OutputStream req = socket.getOutputStream();
StringBuffer reqStr = new StringBuffer("GET ");
- if(Http.PROXY){
+ if (http.useProxy()) {
reqStr.append(url.getProtocol()+"://"+host+portString+path);
} else {
reqStr.append(path);
@@ -111,11 +114,12 @@ public class HttpResponse implements Response {
reqStr.append("Accept-Encoding: x-gzip, gzip\r\n");
- if ((Http.AGENT_STRING == null) || (Http.AGENT_STRING.length() == 0)) {
+ String userAgent = http.getUserAgent();
+ if ((userAgent == null) || (userAgent.length() == 0)) {
Http.LOG.severe("User-agent is not set!");
} else {
reqStr.append("User-Agent: ");
- reqStr.append(Http.AGENT_STRING);
+ reqStr.append(userAgent);
reqStr.append("\r\n");
}
@@ -148,7 +152,7 @@ public class HttpResponse implements Response {
Http.LOG.fine("uncompressing....");
byte[] compressed = content;
- content = GZIPUtils.unzipBestEffort(compressed, Http.MAX_CONTENT);
+ content = GZIPUtils.unzipBestEffort(compressed, http.getMaxContent());
if (content == null)
throw new HttpException("unzipBestEffort returned null");
@@ -212,9 +216,9 @@ public class HttpResponse implements Response {
throw new HttpException("bad content length: "+contentLengthString);
}
}
- if (Http.MAX_CONTENT >= 0
- && contentLength > Http.MAX_CONTENT) // limit download size
- contentLength = Http.MAX_CONTENT;
+ if (http.getMaxContent() >= 0
+ && contentLength > http.getMaxContent()) // limit download size
+ contentLength = http.getMaxContent();
ByteArrayOutputStream out = new ByteArrayOutputStream(Http.BUFFER_SIZE);
byte[] bytes = new byte[Http.BUFFER_SIZE];
@@ -265,8 +269,8 @@ public class HttpResponse implements Response {
break;
}
- if ( (contentBytesRead + chunkLen) > Http.MAX_CONTENT )
- chunkLen= Http.MAX_CONTENT - contentBytesRead;
+ if ( (contentBytesRead + chunkLen) > http.getMaxContent() )
+ chunkLen= http.getMaxContent() - contentBytesRead;
// read one chunk
int chunkBytesRead= 0;
@@ -295,7 +299,7 @@ public class HttpResponse implements Response {
}
if (!doneChunks) {
- if (contentBytesRead != Http.MAX_CONTENT)
+ if (contentBytesRead != http.getMaxContent())
throw new HttpException("chunk eof: !doneChunk && didn't max out");
return;
}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
index 2c3bb5bf5..f3089022f 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
@@ -46,70 +46,70 @@ public class Http extends HttpBase {
public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.net.Http");
- static {
- if (NutchConf.get().getBoolean("http.verbose", false)) {
- LOG.setLevel(Level.FINE);
- } else { // shush about redirects
- Logger.getLogger("org.apache.commons.httpclient.HttpMethodDirector")
- .setLevel(Level.WARNING);
- }
- }
-
private static MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
-
- private static HttpClient client;
+
+ // Since the NutchConf has not yet been setted,
+ // then an unconfigured client is returned.
+ private static HttpClient client = new HttpClient(connectionManager);
static synchronized HttpClient getClient() {
- if (client != null) return client;
- configureClient();
return client;
}
- static int MAX_THREADS_TOTAL = NutchConf.get().getInt("fetcher.threads.fetch", 10);
- static String NTLM_USERNAME = NutchConf.get().get("http.auth.ntlm.username", "");
- static String NTLM_PASSWORD = NutchConf.get().get("http.auth.ntlm.password", "");
- static String NTLM_DOMAIN = NutchConf.get().get("http.auth.ntlm.domain", "");
- static String NTLM_HOST = NutchConf.get().get("http.auth.ntlm.host", "");
-
- static {
- LOG.info("http.auth.ntlm.username = " + NTLM_USERNAME);
- }
-
+ boolean verbose = false;
+ int maxThreadsTotal = 10;
+ String ntlmUsername = "";
+ String ntlmPassword = "";
+ String ntlmDomain = "";
+ String ntlmHost = "";
public Http() {
super(LOG);
}
+ public void setConf(NutchConf conf) {
+ super.setConf(conf);
+ this.maxThreadsTotal = conf.getInt("fetcher.threads.fetch", 10);
+ this.ntlmUsername = conf.get("http.auth.ntlm.username", "");
+ this.ntlmPassword = conf.get("http.auth.ntlm.password", "");
+ this.ntlmDomain = conf.get("http.auth.ntlm.domain", "");
+ this.ntlmHost = conf.get("http.auth.ntlm.host", "");
+ Level logLevel = Level.WARNING;
+ if (conf.getBoolean("http.verbose", false)) {
+ logLevel = Level.FINE;
+ }
+ LOG.setLevel(logLevel);
+ Logger.getLogger("org.apache.commons.httpclient.HttpMethodDirector")
+ .setLevel(logLevel);
+ configureClient();
+ }
+
public static void main(String[] args) throws Exception {
main(new Http(), args);
}
protected Response getResponse(URL url, CrawlDatum datum, boolean redirect)
throws ProtocolException, IOException {
- return new HttpResponse(url, datum, redirect);
+ return new HttpResponse(this, url, datum, redirect);
}
- private static void configureClient() {
-
- // get a client isntance -- we just need one.
-
- client = new HttpClient(connectionManager);
+ private void configureClient() {
// Set up an HTTPS socket factory that accepts self-signed certs.
Protocol dummyhttps = new Protocol("https", new DummySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", dummyhttps);
HttpConnectionManagerParams params = connectionManager.getParams();
- params.setConnectionTimeout(TIMEOUT);
- params.setSoTimeout(TIMEOUT);
+ params.setConnectionTimeout(timeout);
+ params.setSoTimeout(timeout);
params.setSendBufferSize(BUFFER_SIZE);
params.setReceiveBufferSize(BUFFER_SIZE);
- params.setMaxTotalConnections(MAX_THREADS_TOTAL);
- if (MAX_THREADS_TOTAL > MAX_THREADS_PER_HOST) {
- params.setDefaultMaxConnectionsPerHost(MAX_THREADS_PER_HOST);
+ params.setMaxTotalConnections(maxThreadsTotal);
+ if (maxThreadsTotal > maxThreadsPerHost) {
+ params.setDefaultMaxConnectionsPerHost(maxThreadsPerHost);
} else {
- params.setDefaultMaxConnectionsPerHost(MAX_THREADS_TOTAL);
+ params.setDefaultMaxConnectionsPerHost(maxThreadsTotal);
}
HostConfiguration hostConf = client.getHostConfiguration();
@@ -122,15 +122,15 @@ public class Http extends HttpBase {
headers.add(new Header("Accept",
"text/html,application/xml;q=0.9,application/xhtml+xml,text/xml;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"));
hostConf.getParams().setParameter("http.default-headers", headers);
- if (PROXY) {
- hostConf.setProxy(PROXY_HOST, PROXY_PORT);
+ if (useProxy) {
+ hostConf.setProxy(proxyHost, proxyPort);
}
- if (NTLM_USERNAME.length() > 0) {
- Credentials ntCreds = new NTCredentials(NTLM_USERNAME, NTLM_PASSWORD, NTLM_HOST, NTLM_DOMAIN);
- client.getState().setCredentials(new AuthScope(NTLM_HOST, AuthScope.ANY_PORT), ntCreds);
+ if (ntlmUsername.length() > 0) {
+ Credentials ntCreds = new NTCredentials(ntlmUsername, ntlmPassword, ntlmHost, ntlmDomain);
+ client.getState().setCredentials(new AuthScope(ntlmHost, AuthScope.ANY_PORT), ntCreds);
- LOG.info("Added NTLM credentials for " + NTLM_USERNAME);
+ LOG.info("Added NTLM credentials for " + ntlmUsername);
}
LOG.info("Configured Client");
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java
index fc848bcc7..463164da1 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java
@@ -15,6 +15,8 @@ import java.util.logging.Logger;
import org.apache.nutch.protocol.ContentProperties;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
+
/**
* Provides the Http protocol implementation
@@ -28,25 +30,50 @@ import org.apache.nutch.util.NutchConf;
*
* @author Matt Tencati
*/
-public class HttpAuthenticationFactory {
- /** The HTTP Authentication (WWW-Authenticate) header which is returned
+public class HttpAuthenticationFactory implements NutchConfigurable {
+
+ /**
+ * The HTTP Authentication (WWW-Authenticate) header which is returned
* by a webserver requiring authentication.
*/
public static final String AUTH_HEADER = "WWW-Authenticate";
- public static final Logger LOG =
- LogFormatter.getLogger("net.nutch.protocol.http.HttpAuthenticationFactory");
+ public static final Logger LOG =
+ LogFormatter.getLogger(HttpAuthenticationFactory.class.getName());
- static {
- if (NutchConf.get().getBoolean("http.auth.verbose", false))
- LOG.setLevel(Level.FINE);
- }
-
private static Map auths = new TreeMap();
+
+ private NutchConf conf = null;
- private HttpAuthenticationFactory() { }
- public static HttpAuthentication findAuthentication(ContentProperties header) {
+ public HttpAuthenticationFactory(NutchConf conf) {
+ setConf(conf);
+ }
+
+
+ /* ---------------------------------- *
+ * <implementation:NutchConfigurable> *
+ * ---------------------------------- */
+
+ public void setConf(NutchConf conf) {
+ this.conf = conf;
+ if (conf.getBoolean("http.auth.verbose", false)) {
+ LOG.setLevel(Level.FINE);
+ } else {
+ LOG.setLevel(Level.WARNING);
+ }
+ }
+
+ public NutchConf getConf() {
+ return conf;
+ }
+
+ /* ---------------------------------- *
+ * <implementation:NutchConfigurable> *
+ * ---------------------------------- */
+
+
+ public HttpAuthentication findAuthentication(ContentProperties header) {
if (header == null) return null;
try {
@@ -80,7 +107,7 @@ public class HttpAuthenticationFactory {
}
LOG.fine("Checking challengeString=" + challengeString);
- auth = HttpBasicAuthentication.getAuthentication(challengeString);
+ auth = HttpBasicAuthentication.getAuthentication(challengeString, conf);
if (auth != null) return auth;
//TODO Add additional Authentication lookups here
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java
index 8a26450e0..465368931 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java
@@ -16,6 +16,7 @@ import org.apache.commons.codec.binary.Base64;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.NutchConfigurable;
/**
* Implementation of RFC 2617 Basic Authentication. Usernames and passwords are stored
@@ -25,23 +26,21 @@ import org.apache.nutch.util.NutchConf;
*
* @author Matt Tencati
*/
-public class HttpBasicAuthentication implements HttpAuthentication {
- public static final Logger LOG =
- LogFormatter.getLogger("net.nutch.net.HttpBasicAuthentication");
+public class HttpBasicAuthentication implements HttpAuthentication, NutchConfigurable {
- static {
- if (NutchConf.get().getBoolean("http.auth.verbose", false))
- LOG.setLevel(Level.FINE);
- }
+ public static final Logger LOG =
+ LogFormatter.getLogger(HttpBasicAuthentication.class.getName());
- private static Pattern basic = Pattern.compile("[bB][aA][sS][iI][cC] [rR][eE][aA][lL][mM]=\"(\\w*)\"");
+ private static Pattern basic = Pattern.compile("[bB][aA][sS][iI][cC] [rR][eE][aA][lL][mM]=\"(\\w*)\"");
private static Map authMap = new TreeMap();
-
+
+ private NutchConf conf = null;
private String challenge = null;
private ArrayList credentials = null;
private String realm = null;
+
/**
* Construct an HttpBasicAuthentication for the given challenge
* parameters. The challenge parameters are returned by the web
@@ -50,14 +49,16 @@ public class HttpBasicAuthentication implements HttpAuthentication {
*
* @param challenge WWW-Authenticate header from web server
*/
- protected HttpBasicAuthentication(String challenge) throws HttpAuthenticationException {
+ protected HttpBasicAuthentication(String challenge, NutchConf nutchConf) throws HttpAuthenticationException {
+
+ setConf(nutchConf);
this.challenge = challenge;
LOG.fine("BasicAuthentication challenge is " + challenge);
credentials = new ArrayList();
- String username = NutchConf.get().get("http.auth.basic." + challenge + ".user");
+ String username = this.conf.get("http.auth.basic." + challenge + ".user");
LOG.fine("BasicAuthentication username=" + username);
- String password = NutchConf.get().get("http.auth.basic." + challenge + ".password");
+ String password = this.conf.get("http.auth.basic." + challenge + ".password");
LOG.fine("BasicAuthentication password=" + password);
if (username == null) {
@@ -73,6 +74,29 @@ public class HttpBasicAuthentication implements HttpAuthentication {
LOG.fine("Basic credentials: " + credentials);
}
+
+ /* ---------------------------------- *
+ * <implementation:NutchConfigurable> *
+ * ---------------------------------- */
+
+ public void setConf(NutchConf conf) {
+ this.conf = conf;
+ if (conf.getBoolean("http.auth.verbose", false)) {
+ LOG.setLevel(Level.FINE);
+ } else {
+ LOG.setLevel(Level.WARNING);
+ }
+ }
+
+ public NutchConf getConf() {
+ return this.conf;
+ }
+
+ /* ---------------------------------- *
+ * <implementation:NutchConfigurable> *
+ * ---------------------------------- */
+
+
/**
* Gets the Basic credentials generated by this
* HttpBasicAuthentication object
@@ -105,7 +129,7 @@ public class HttpBasicAuthentication implements HttpAuthentication {
* @return An HttpBasicAuthentication object or null
* if unable to generate appropriate credentials.
*/
- public static HttpBasicAuthentication getAuthentication(String challenge) {
+ public static HttpBasicAuthentication getAuthentication(String challenge, NutchConf conf) {
if (challenge == null) return null;
Matcher basicMatcher = basic.matcher(challenge);
if (basicMatcher.matches()) {
@@ -114,7 +138,7 @@ public class HttpBasicAuthentication implements HttpAuthentication {
if (auth == null) {
HttpBasicAuthentication newAuth = null;
try {
- newAuth = new HttpBasicAuthentication(realm);
+ newAuth = new HttpBasicAuthentication(realm, conf);
} catch (HttpAuthenticationException hae) {
LOG.fine("HttpBasicAuthentication failed for " + challenge);
}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java
index 13789f992..308481511 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java
@@ -32,6 +32,7 @@ import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.ContentProperties;
+import org.apache.nutch.protocol.http.api.HttpBase;
/**
@@ -47,24 +48,26 @@ public class HttpResponse implements Response {
private byte[] content;
+ private HttpBase http;
private int code;
private ContentProperties headers = new ContentProperties();
- public HttpResponse(URL url, CrawlDatum datum) throws IOException {
- this(url, datum, false);
+ public HttpResponse(HttpBase http, URL url, CrawlDatum datum) throws IOException {
+ this(http, url, datum, false);
}
- HttpResponse(URL url, CrawlDatum datum, boolean followRedirects) throws IOException {
+ HttpResponse(HttpBase http, URL url, CrawlDatum datum, boolean followRedirects) throws IOException {
+ this.http = http;
this.url = url;
this.base = url.toString();
this.orig = url.toString();
GetMethod get = new GetMethod(this.orig);
get.setFollowRedirects(followRedirects);
- get.setRequestHeader("User-Agent", Http.AGENT_STRING);
+ get.setRequestHeader("User-Agent", http.getUserAgent());
HttpMethodParams params = get.getParams();
// some servers cannot digest the new protocol
params.setVersion(HttpVersion.HTTP_1_0);
@@ -88,7 +91,7 @@ public class HttpResponse implements Response {
// for error.
try {
InputStream in = get.getResponseBodyAsStream();
- byte[] buffer = new byte[Http.BUFFER_SIZE];
+ byte[] buffer = new byte[http.BUFFER_SIZE];
int bufferFilled = 0;
int totalRead = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -147,10 +150,10 @@ public class HttpResponse implements Response {
private int calculateTryToRead(int totalRead) {
int tryToRead = Http.BUFFER_SIZE;
- if (Http.MAX_CONTENT <= 0) {
- return Http.BUFFER_SIZE;
- } else if (Http.MAX_CONTENT - totalRead < Http.BUFFER_SIZE) {
- tryToRead = Http.MAX_CONTENT - totalRead;
+ if (http.getMaxContent() <= 0) {
+ return http.BUFFER_SIZE;
+ } else if (http.getMaxContent() - totalRead < http.BUFFER_SIZE) {
+ tryToRead = http.getMaxContent() - totalRead;
}
return tryToRead;
}
diff --git a/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.java b/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.java
index db670775f..a7a7fdeb7 100644
--- a/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.java
+++ b/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.java
@@ -35,46 +35,43 @@ import java.util.HashSet;
* expanded to search the url, anchor and content document fields.*/
public class BasicQueryFilter implements QueryFilter {
- private static float URL_BOOST =
- NutchConf.get().getFloat("query.url.boost", 4.0f);
+ private float URL_BOOST;
- private static float ANCHOR_BOOST =
- NutchConf.get().getFloat("query.anchor.boost", 2.0f);
+ private float ANCHOR_BOOST ;
- private static float TITLE_BOOST =
- NutchConf.get().getFloat("query.title.boost", 1.5f);
+ private float TITLE_BOOST;
- private static float HOST_BOOST =
- NutchConf.get().getFloat("query.host.boost", 2.0f);
+ private float HOST_BOOST;
private static int SLOP = Integer.MAX_VALUE;
- private static float PHRASE_BOOST =
- NutchConf.get().getFloat("query.phrase.boost", 1.0f);
+ private float PHRASE_BOOST;
private static final String[] FIELDS =
{ "url", "anchor", "content", "title", "host" };
- private static final float[] FIELD_BOOSTS =
+ private final float[] FIELD_BOOSTS =
{ URL_BOOST, ANCHOR_BOOST, 1.0f, TITLE_BOOST, HOST_BOOST };
/**
* Set the boost factor for url matches, relative to content and anchor
* matches
*/
- public static void setUrlBoost(float boost) { URL_BOOST = boost; }
+ public void setUrlBoost(float boost) { URL_BOOST = boost; }
/** Set the boost factor for title/anchor matches, relative to url and
* content matches. */
- public static void setAnchorBoost(float boost) { ANCHOR_BOOST = boost; }
+ public void setAnchorBoost(float boost) { ANCHOR_BOOST = boost; }
/** Set the boost factor for sloppy phrase matches relative to unordered term
* matches. */
- public static void setPhraseBoost(float boost) { PHRASE_BOOST = boost; }
+ public void setPhraseBoost(float boost) { PHRASE_BOOST = boost; }
/** Set the maximum number of terms permitted between matching terms in a
* sloppy phrase match. */
- public static void setSlop(int slop) { SLOP = slop; }
+ public void setSlop(int slop) { SLOP = slop; }
+
+ private NutchConf nutchConf;
public BooleanQuery filter(Query input, BooleanQuery output) {
addTerms(input, output);
@@ -82,7 +79,7 @@ public class BasicQueryFilter implements QueryFilter {
return output;
}
- private static void addTerms(Query input, BooleanQuery output) {
+ private void addTerms(Query input, BooleanQuery output) {
Clause[] clauses = input.getClauses();
for (int i = 0; i < clauses.length; i++) {
Clause c = clauses[i];
@@ -95,11 +92,11 @@ public class BasicQueryFilter implements QueryFilter {
Clause o = c;
if (c.isPhrase()) { // optimize phrase clauses
- String[] opt = CommonGrams.optimizePhrase(c.getPhrase(), FIELDS[f]);
+ String[] opt = new CommonGrams(getConf()).optimizePhrase(c.getPhrase(), FIELDS[f]);
if (opt.length==1) {
- o = new Clause(new Term(opt[0]), c.isRequired(), c.isProhibited());
+ o = new Clause(new Term(opt[0]), c.isRequired(), c.isProhibited(), getConf());
} else {
- o = new Clause(new Phrase(opt), c.isRequired(), c.isProhibited());
+ o = new Clause(new Phrase(opt), c.isRequired(), c.isProhibited(), getConf());
}
}
@@ -112,7 +109,7 @@ public class BasicQueryFilter implements QueryFilter {
}
}
- private static void addSloppyPhrases(Query input, BooleanQuery output) {
+ private void addSloppyPhrases(Query input, BooleanQuery output) {
Clause[] clauses = input.getClauses();
for (int f = 0; f < FIELDS.length; f++) {
@@ -145,7 +142,7 @@ public class BasicQueryFilter implements QueryFilter {
}
- private static org.apache.lucene.search.Query
+ private org.apache.lucene.search.Query
termQuery(String field, Term term, float boost) {
TermQuery result = new TermQuery(luceneTerm(field, term));
result.setBoost(boost);
@@ -153,7 +150,7 @@ public class BasicQueryFilter implements QueryFilter {
}
/** Utility to construct a Lucene exact phrase query for a Nutch phrase. */
- private static org.apache.lucene.search.Query
+ private org.apache.lucene.search.Query
exactPhrase(Phrase nutchPhrase,
String field, float boost) {
Term[] terms = nutchPhrase.getTerms();
@@ -170,4 +167,17 @@ public class BasicQueryFilter implements QueryFilter {
Term term) {
return new org.apache.lucene.index.Term(field, term.toString());
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ this.URL_BOOST = conf.getFloat("query.url.boost", 4.0f);
+ this.ANCHOR_BOOST = conf.getFloat("query.anchor.boost", 2.0f);
+ this.TITLE_BOOST = conf.getFloat("query.title.boost", 1.5f);
+ this.HOST_BOOST = conf.getFloat("query.host.boost", 2.0f);
+ this.PHRASE_BOOST = conf.getFloat("query.phrase.boost", 1.0f);
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.java b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.java
index 3bbd99194..d319c22ba 100644
--- a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.java
+++ b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.java
@@ -22,6 +22,7 @@ import org.apache.nutch.searcher.QueryFilter;
import org.apache.nutch.searcher.QueryException;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.RangeQuery;
@@ -47,6 +48,8 @@ public class DateQueryFilter implements QueryFilter {
// query syntax is defined as date:yyyymmdd-yyyymmdd
private static final Pattern pattern = Pattern.compile("^(\\d{8})-(\\d{8})$");
+
+ private NutchConf nutchConf;
public BooleanQuery filter(Query input, BooleanQuery output)
throws QueryException {
@@ -84,4 +87,11 @@ public class DateQueryFilter implements QueryFilter {
return output;
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.java b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.java
index d86ce30a0..150cf0c9f 100644
--- a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.java
+++ b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.java
@@ -17,6 +17,7 @@
package org.apache.nutch.searcher.more;
import org.apache.nutch.searcher.RawFieldQueryFilter;
+import org.apache.nutch.util.NutchConf;
/**
* Handles "type:" query clauses, causing them to search the field
@@ -26,7 +27,17 @@ import org.apache.nutch.searcher.RawFieldQueryFilter;
*/
public class TypeQueryFilter extends RawFieldQueryFilter {
+ private NutchConf nutchConf;
+
public TypeQueryFilter() {
super("type");
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.java b/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.java
index 1fe63dc91..68fc66e1e 100644
--- a/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.java
+++ b/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.java
@@ -17,11 +17,22 @@
package org.apache.nutch.searcher.site;
import org.apache.nutch.searcher.RawFieldQueryFilter;
+import org.apache.nutch.util.NutchConf;
/** Handles "site:" query clauses, causing them to search the field indexed by
* SiteIndexingFilter. */
public class SiteQueryFilter extends RawFieldQueryFilter {
+ private NutchConf nutchConf;
+
public SiteQueryFilter() {
super("site");
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.java b/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.java
index a4f8c51a8..7850c363c 100644
--- a/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.java
+++ b/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.java
@@ -17,11 +17,24 @@
package org.apache.nutch.searcher.url;
import org.apache.nutch.searcher.FieldQueryFilter;
+import org.apache.nutch.util.NutchConf;
-/** Handles "url:" query clauses, causing them to search the field indexed by
- * BasicIndexingFilter. */
+/**
+ * Handles "url:" query clauses, causing them to search the field indexed by
+ * BasicIndexingFilter.
+ */
public class URLQueryFilter extends FieldQueryFilter {
+ private NutchConf nutchConf;
+
public URLQueryFilter() {
super("url");
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.java b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.java
index eaf7540ee..d11abebf1 100644
--- a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.java
+++ b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.java
@@ -52,40 +52,13 @@ public class PrefixURLFilter implements URLFilter {
// read in attribute "file" of this plugin.
private static String attributeFile = null;
- static {
- String pluginName = "urlfilter-prefix";
- Extension[] extensions = PluginRepository.getInstance()
- .getExtensionPoint(URLFilter.class.getName()).getExtensions();
- for (int i=0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- if (extension.getDescriptor().getPluginId().equals(pluginName)) {
- attributeFile = extension.getAttribute("file");
- break;
- }
- }
- if (attributeFile != null && attributeFile.trim().equals(""))
- attributeFile = null;
- if (attributeFile != null) {
- LOG.info("Attribute \"file\" is defined for plugin "+pluginName+" as "+attributeFile);
- } else {
- //LOG.warning("Attribute \"file\" is not defined in plugin.xml for plugin "+pluginName);
- }
- }
private TrieStringMatcher trie;
- public PrefixURLFilter() throws IOException {
- String file = NutchConf.get().get("urlfilter.prefix.file");
- // attribute "file" takes precedence if defined
- if (attributeFile != null)
- file = attributeFile;
- Reader reader = NutchConf.get().getConfResourceAsReader(file);
+ private NutchConf nutchConf;
- if (reader == null) {
- trie = new PrefixStringMatcher(new String[0]);
- } else {
- trie = readConfigurationFile(reader);
- }
+ public PrefixURLFilter() throws IOException {
+
}
public PrefixURLFilter(String filename) throws IOException {
@@ -99,7 +72,7 @@ public class PrefixURLFilter implements URLFilter {
return url;
}
- private static TrieStringMatcher readConfigurationFile(Reader reader)
+ private TrieStringMatcher readConfigurationFile(Reader reader)
throws IOException {
BufferedReader in=new BufferedReader(reader);
@@ -140,5 +113,51 @@ public class PrefixURLFilter implements URLFilter {
}
}
}
+
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+
+ String pluginName = "urlfilter-prefix";
+ Extension[] extensions = conf.getPluginRepository().getExtensionPoint(
+ URLFilter.class.getName()).getExtensions();
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ if (extension.getDescriptor().getPluginId().equals(pluginName)) {
+ attributeFile = extension.getAttribute("file");
+ break;
+ }
+ }
+ if (attributeFile != null && attributeFile.trim().equals(""))
+ attributeFile = null;
+ if (attributeFile != null) {
+ LOG.info("Attribute \"file\" is defined for plugin " + pluginName
+ + " as " + attributeFile);
+ } else {
+ // LOG.warning("Attribute \"file\" is not defined in plugin.xml for
+ // plugin "+pluginName);
+ }
+
+ String file = conf.get("urlfilter.prefix.file");
+ // attribute "file" takes precedence if defined
+ if (attributeFile != null)
+ file = attributeFile;
+ Reader reader = conf.getConfResourceAsReader(file);
+
+ if (reader == null) {
+ trie = new PrefixStringMatcher(new String[0]);
+ } else {
+ try {
+ trie = readConfigurationFile(reader);
+ } catch (IOException e) {
+ LOG.severe(e.getMessage());
+ // TODO [email protected]: throw Exception? Because broken api.
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
}
diff --git a/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.java b/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.java
index 5cca4c6fd..1a5e21c18 100644
--- a/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.java
+++ b/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.java
@@ -21,6 +21,7 @@ import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
+import org.apache.oro.text.regex.MalformedPatternException;
import java.io.Reader;
import java.io.FileReader;
@@ -54,25 +55,6 @@ public class RegexURLFilter implements URLFilter {
// read in attribute "file" of this plugin.
private static String attributeFile = null;
- static {
- String pluginName = "urlfilter-regex";
- Extension[] extensions = PluginRepository.getInstance()
- .getExtensionPoint(URLFilter.class.getName()).getExtensions();
- for (int i=0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- if (extension.getDescriptor().getPluginId().equals(pluginName)) {
- attributeFile = extension.getAttribute("file");
- break;
- }
- }
- if (attributeFile != null && attributeFile.trim().equals(""))
- attributeFile = null;
- if (attributeFile != null) {
- LOG.info("Attribute \"file\" is defined for plugin "+pluginName+" as "+attributeFile);
- } else {
- //LOG.warning("Attribute \"file\" is not defined in plugin.xml for plugin "+pluginName);
- }
- }
private static class Rule {
public Pattern pattern;
@@ -82,18 +64,9 @@ public class RegexURLFilter implements URLFilter {
private List rules;
- public RegexURLFilter() throws IOException, PatternSyntaxException {
- String file = NutchConf.get().get("urlfilter.regex.file");
- // attribute "file" takes precedence if defined
- if (attributeFile != null)
- file = attributeFile;
- Reader reader = NutchConf.get().getConfResourceAsReader(file);
+ private NutchConf nutchConf;
- if (reader == null) {
- LOG.severe("Can't find resource: " + file);
- } else {
- rules=readConfigurationFile(reader);
- }
+ public RegexURLFilter() {
}
public RegexURLFilter(String filename)
@@ -179,4 +152,47 @@ public class RegexURLFilter implements URLFilter {
}
}
+ public void setConf(NutchConf conf) {
+ this.nutchConf = conf;
+ String pluginName = "urlfilter-regex";
+ Extension[] extensions = conf.getPluginRepository().getExtensionPoint(
+ URLFilter.class.getName()).getExtensions();
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ if (extension.getDescriptor().getPluginId().equals(pluginName)) {
+ attributeFile = extension.getAttribute("file");
+ break;
+ }
+ }
+ if (attributeFile != null && attributeFile.trim().equals(""))
+ attributeFile = null;
+ if (attributeFile != null) {
+ LOG.info("Attribute \"file\" is defined for plugin " + pluginName
+ + " as " + attributeFile);
+ } else {
+ //LOG.warning("Attribute \"file\" is not defined in plugin.xml for plugin "+pluginName);
+ }
+ String file = conf.get("urlfilter.regex.file");
+ // attribute "file" takes precedence if defined
+ if (attributeFile != null)
+ file = attributeFile;
+ Reader reader = conf.getConfResourceAsReader(file);
+
+ if (reader == null) {
+ LOG.severe("Can't find resource: " + file);
+ } else {
+ try {
+ rules = readConfigurationFile(reader);
+ } catch (IOException e) {
+ LOG.severe(e.getMessage());
+ //TODO [email protected]: throw Exception? Because broken api.
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+ }
+
+ public NutchConf getConf() {
+ return this.nutchConf;
+ }
+
}
diff --git a/src/test/org/apache/nutch/analysis/TestQueryParser.java b/src/test/org/apache/nutch/analysis/TestQueryParser.java
index eff9ba96a..3786072da 100644
--- a/src/test/org/apache/nutch/analysis/TestQueryParser.java
+++ b/src/test/org/apache/nutch/analysis/TestQueryParser.java
@@ -17,6 +17,7 @@
package org.apache.nutch.analysis;
import org.apache.nutch.searcher.Query;
+import org.apache.nutch.util.NutchConf;
import junit.framework.TestCase;
@@ -26,9 +27,10 @@ import junit.framework.TestCase;
*/
public class TestQueryParser extends TestCase {
+ private static NutchConf nutchConf = new NutchConf();
public void assertQueryEquals(String query, String result) throws Exception {
try {
- Query q = NutchAnalysis.parseQuery(query);
+ Query q = NutchAnalysis.parseQuery(query, nutchConf);
String s = q.toString();
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
diff --git a/src/test/org/apache/nutch/fs/TestNutchFileSystem.java b/src/test/org/apache/nutch/fs/TestNutchFileSystem.java
index 3f415ded5..0dc02b923 100644
--- a/src/test/org/apache/nutch/fs/TestNutchFileSystem.java
+++ b/src/test/org/apache/nutch/fs/TestNutchFileSystem.java
@@ -30,8 +30,8 @@ import org.apache.nutch.util.*;
public class TestNutchFileSystem extends TestCase {
private static final Logger LOG = InputFormatBase.LOG;
- private static int BUFFER_SIZE =
- NutchConf.get().getInt("io.file.buffer.size", 4096);
+ private static NutchConf nutchConf = new NutchConf();
+ private static int BUFFER_SIZE = nutchConf.getInt("io.file.buffer.size", 4096);
private static final long MEGA = 1024 * 1024;
private static final int SEEKS_PER_FILE = 4;
@@ -49,7 +49,7 @@ public class TestNutchFileSystem extends TestCase {
public static void testFs(long megaBytes, int numFiles, long seed)
throws Exception {
- NutchFileSystem fs = NutchFileSystem.get();
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
if (seed == 0)
seed = new Random().nextLong();
@@ -107,7 +107,7 @@ public class TestNutchFileSystem extends TestCase {
{
try {
- fs = NutchFileSystem.get();
+ fs = NutchFileSystem.get(nutchConf);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -164,7 +164,7 @@ public class TestNutchFileSystem extends TestCase {
fs.delete(DATA_DIR);
fs.delete(WRITE_DIR);
- JobConf job = new JobConf(NutchConf.get());
+ JobConf job = new JobConf(nutchConf);
job.setBoolean("fs.test.fastCheck", fastCheck);
job.setInputDir(CONTROL_DIR);
@@ -191,7 +191,7 @@ public class TestNutchFileSystem extends TestCase {
{
try {
- fs = NutchFileSystem.get();
+ fs = NutchFileSystem.get(nutchConf);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -255,7 +255,7 @@ public class TestNutchFileSystem extends TestCase {
fs.delete(READ_DIR);
- JobConf job = new JobConf(NutchConf.get());
+ JobConf job = new JobConf(nutchConf);
job.setBoolean("fs.test.fastCheck", fastCheck);
@@ -283,7 +283,7 @@ public class TestNutchFileSystem extends TestCase {
{
try {
- fs = NutchFileSystem.get();
+ fs = NutchFileSystem.get(nutchConf);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -347,7 +347,7 @@ public class TestNutchFileSystem extends TestCase {
fs.delete(READ_DIR);
- JobConf job = new JobConf(NutchConf.get());
+ JobConf job = new JobConf(nutchConf);
job.setBoolean("fs.test.fastCheck", fastCheck);
job.setInputDir(CONTROL_DIR);
@@ -401,7 +401,7 @@ public class TestNutchFileSystem extends TestCase {
LOG.info("files = " + files);
LOG.info("megaBytes = " + megaBytes);
- NutchFileSystem fs = NutchFileSystem.get();
+ NutchFileSystem fs = NutchFileSystem.get(nutchConf);
if (!noWrite) {
createControlFile(fs, megaBytes*MEGA, files, seed);
diff --git a/src/test/org/apache/nutch/io/TestArrayFile.java b/src/test/org/apache/nutch/io/TestArrayFile.java
index 49f34f613..6acb84260 100644
--- a/src/test/org/apache/nutch/io/TestArrayFile.java
+++ b/src/test/org/apache/nutch/io/TestArrayFile.java
@@ -35,16 +35,18 @@ public class TestArrayFile extends TestCase {
}
public void testArrayFile() throws Exception {
- NutchFileSystem nfs = new LocalFileSystem();
+ NutchConf nutchConf = new NutchConf();
+ NutchFileSystem nfs = new LocalFileSystem(nutchConf);
RandomDatum[] data = generate(10000);
writeTest(nfs, data, FILE);
- readTest(nfs, data, FILE);
+ readTest(nfs, data, FILE, nutchConf);
}
public void testEmptyFile() throws Exception {
- NutchFileSystem nfs = new LocalFileSystem();
+ NutchConf nutchConf = new NutchConf();
+ NutchFileSystem nfs = new LocalFileSystem(nutchConf);
writeTest(nfs, new RandomDatum[0], FILE);
- ArrayFile.Reader reader = new ArrayFile.Reader(nfs, FILE);
+ ArrayFile.Reader reader = new ArrayFile.Reader(nfs, FILE, nutchConf);
assertNull(reader.get(0, new RandomDatum()));
reader.close();
}
@@ -71,11 +73,11 @@ public class TestArrayFile extends TestCase {
writer.close();
}
- private static void readTest(NutchFileSystem nfs, RandomDatum[] data, String file)
+ private static void readTest(NutchFileSystem nfs, RandomDatum[] data, String file, NutchConf nutchConf)
throws IOException {
RandomDatum v = new RandomDatum();
LOG.fine("reading " + data.length + " records");
- ArrayFile.Reader reader = new ArrayFile.Reader(nfs, file);
+ ArrayFile.Reader reader = new ArrayFile.Reader(nfs, file, nutchConf);
for (int i = 0; i < data.length; i++) { // try forwards
reader.get(i, v);
if (!v.equals(data[i])) {
@@ -106,8 +108,9 @@ public class TestArrayFile extends TestCase {
System.exit(-1);
}
+ NutchConf nutchConf = new NutchConf();
int i = 0;
- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i);
+ NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i, nutchConf);
try {
for (; i < args.length; i++) { // parse command line
if (args[i] == null) {
@@ -138,7 +141,7 @@ public class TestArrayFile extends TestCase {
}
if (check) {
- readTest(nfs, data, file);
+ readTest(nfs, data, file, nutchConf);
}
} finally {
nfs.close();
diff --git a/src/test/org/apache/nutch/io/TestSequenceFile.java b/src/test/org/apache/nutch/io/TestSequenceFile.java
index 6678c2db5..147b3fdf1 100644
--- a/src/test/org/apache/nutch/io/TestSequenceFile.java
+++ b/src/test/org/apache/nutch/io/TestSequenceFile.java
@@ -28,6 +28,8 @@ import org.apache.nutch.util.*;
public class TestSequenceFile extends TestCase {
private static Logger LOG = SequenceFile.LOG;
+ private static NutchConf nutchConf = new NutchConf();
+
public TestSequenceFile(String name) { super(name); }
/** Unit tests for SequenceFile. */
@@ -39,7 +41,7 @@ public class TestSequenceFile extends TestCase {
int seed = new Random().nextInt();
- NutchFileSystem nfs = new LocalFileSystem();
+ NutchFileSystem nfs = new LocalFileSystem(new NutchConf());
try {
//LOG.setLevel(Level.FINE);
writeTest(nfs, count, seed, file, false);
@@ -85,7 +87,7 @@ public class TestSequenceFile extends TestCase {
RandomDatum k = new RandomDatum();
RandomDatum v = new RandomDatum();
LOG.fine("reading " + count + " records");
- SequenceFile.Reader reader = new SequenceFile.Reader(nfs, file);
+ SequenceFile.Reader reader = new SequenceFile.Reader(nfs, file, nutchConf);
RandomDatum.Generator generator = new RandomDatum.Generator(seed);
for (int i = 0; i < count; i++) {
generator.next();
@@ -129,7 +131,7 @@ public class TestSequenceFile extends TestCase {
RandomDatum k = new RandomDatum();
RandomDatum v = new RandomDatum();
Iterator iterator = map.entrySet().iterator();
- SequenceFile.Reader reader = new SequenceFile.Reader(nfs, file + ".sorted");
+ SequenceFile.Reader reader = new SequenceFile.Reader(nfs, file + ".sorted", nutchConf);
for (int i = 0; i < count; i++) {
Map.Entry entry = (Map.Entry)iterator.next();
RandomDatum key = (RandomDatum)entry.getKey();
@@ -195,8 +197,8 @@ public class TestSequenceFile extends TestCase {
int megabytes, int factor) {
SequenceFile.Sorter sorter =
fast
- ? new SequenceFile.Sorter(nfs, new RandomDatum.Comparator(),RandomDatum.class)
- : new SequenceFile.Sorter(nfs, RandomDatum.class, RandomDatum.class);
+ ? new SequenceFile.Sorter(nfs, new RandomDatum.Comparator(),RandomDatum.class, nutchConf)
+ : new SequenceFile.Sorter(nfs, RandomDatum.class, RandomDatum.class, nutchConf);
sorter.setMemory(megabytes * 1024*1024);
sorter.setFactor(factor);
return sorter;
@@ -221,7 +223,7 @@ public class TestSequenceFile extends TestCase {
System.exit(-1);
}
int i = 0;
- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i);
+ NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i, nutchConf);
try {
for (; i < args.length; i++) { // parse command line
if (args[i] == null) {
diff --git a/src/test/org/apache/nutch/io/TestSetFile.java b/src/test/org/apache/nutch/io/TestSetFile.java
index d3d5be250..be2d0f33a 100644
--- a/src/test/org/apache/nutch/io/TestSetFile.java
+++ b/src/test/org/apache/nutch/io/TestSetFile.java
@@ -30,10 +30,12 @@ public class TestSetFile extends TestCase {
private static String FILE =
System.getProperty("test.build.data",".") + "/test.set";
+ private static NutchConf nutchConf = new NutchConf();
+
public TestSetFile(String name) { super(name); }
public void testSetFile() throws Exception {
- NutchFileSystem nfs = new LocalFileSystem();
+ NutchFileSystem nfs = new LocalFileSystem(nutchConf);
try {
RandomDatum[] data = generate(10000);
writeTest(nfs, data, FILE);
@@ -70,7 +72,7 @@ public class TestSetFile extends TestCase {
throws IOException {
RandomDatum v = new RandomDatum();
LOG.fine("reading " + data.length + " records");
- SetFile.Reader reader = new SetFile.Reader(nfs, file);
+ SetFile.Reader reader = new SetFile.Reader(nfs, file, nutchConf);
for (int i = 0; i < data.length; i++) {
if (!reader.seek(data[i]))
throw new RuntimeException("wrong value at " + i);
@@ -94,7 +96,7 @@ public class TestSetFile extends TestCase {
}
int i = 0;
- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i);
+ NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i, nutchConf);
try {
for (; i < args.length; i++) { // parse command line
if (args[i] == null) {
diff --git a/src/test/org/apache/nutch/io/TestWritable.java b/src/test/org/apache/nutch/io/TestWritable.java
index 83765506a..968acbd0c 100644
--- a/src/test/org/apache/nutch/io/TestWritable.java
+++ b/src/test/org/apache/nutch/io/TestWritable.java
@@ -20,6 +20,8 @@ import java.io.*;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.nutch.io.*;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.util.NutchConf;
/** Unit tests for Writable. */
public class TestWritable extends TestCase {
@@ -68,6 +70,10 @@ public class TestWritable extends TestCase {
dib.reset(dob.getData(), dob.getLength());
Writable after = (Writable)before.getClass().newInstance();
+ if(after instanceof ParseData) {
+ ParseData parseData = (ParseData) after;
+ parseData.setConf(new NutchConf());
+ }
after.readFields(dib);
assertEquals(before, after);
diff --git a/src/test/org/apache/nutch/ipc/TestIPC.java b/src/test/org/apache/nutch/ipc/TestIPC.java
index a227a1548..88f6edda5 100644
--- a/src/test/org/apache/nutch/ipc/TestIPC.java
+++ b/src/test/org/apache/nutch/ipc/TestIPC.java
@@ -29,12 +29,15 @@ import java.util.logging.Logger;
import java.util.logging.Level;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/** Unit tests for IPC. */
public class TestIPC extends TestCase {
public static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.ipc.TestIPC");
+ private static NutchConf nutchConf = new NutchConf();
+
// quiet during testing, since output ends up on console
static {
LOG.setLevel(Level.WARNING);
@@ -52,7 +55,7 @@ public class TestIPC extends TestCase {
private boolean sleep;
public TestServer(int port, int handlerCount, boolean sleep) {
- super(port, LongWritable.class, handlerCount);
+ super(port, LongWritable.class, handlerCount, nutchConf);
this.setTimeout(1000);
this.sleep = sleep;
}
@@ -145,7 +148,7 @@ public class TestIPC extends TestCase {
Client[] clients = new Client[clientCount];
for (int i = 0; i < clientCount; i++) {
- clients[i] = new Client(LongWritable.class);
+ clients[i] = new Client(LongWritable.class, nutchConf);
}
SerialCaller[] callers = new SerialCaller[callerCount];
@@ -184,7 +187,7 @@ public class TestIPC extends TestCase {
Client[] clients = new Client[clientCount];
for (int i = 0; i < clientCount; i++) {
- clients[i] = new Client(LongWritable.class);
+ clients[i] = new Client(LongWritable.class, nutchConf);
}
ParallelCaller[] callers = new ParallelCaller[callerCount];
diff --git a/src/test/org/apache/nutch/ipc/TestRPC.java b/src/test/org/apache/nutch/ipc/TestRPC.java
index d5493652f..ccd724dc0 100644
--- a/src/test/org/apache/nutch/ipc/TestRPC.java
+++ b/src/test/org/apache/nutch/ipc/TestRPC.java
@@ -27,6 +27,7 @@ import java.util.logging.Level;
import java.util.Arrays;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
/** Unit tests for RPC. */
public class TestRPC extends TestCase {
@@ -34,6 +35,8 @@ public class TestRPC extends TestCase {
public static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.ipc.TestRPC");
+
+ private static NutchConf nutchConf = new NutchConf();
// quiet during testing, since output ends up on console
static {
@@ -80,12 +83,12 @@ public class TestRPC extends TestCase {
}
public void testCalls() throws Exception {
- Server server = RPC.getServer(new TestImpl(), PORT);
+ Server server = RPC.getServer(new TestImpl(), PORT, nutchConf);
server.start();
InetSocketAddress addr = new InetSocketAddress(PORT);
TestProtocol proxy =
- (TestProtocol)RPC.getProxy(TestProtocol.class, addr);
+ (TestProtocol)RPC.getProxy(TestProtocol.class, addr, nutchConf);
proxy.ping();
@@ -114,12 +117,12 @@ public class TestRPC extends TestCase {
Method echo =
TestProtocol.class.getMethod("echo", new Class[] { String.class });
String[] strings = (String[])RPC.call(echo, new String[][]{{"a"},{"b"}},
- new InetSocketAddress[] {addr, addr});
+ new InetSocketAddress[] {addr, addr}, nutchConf);
assertTrue(Arrays.equals(strings, new String[]{"a","b"}));
Method ping = TestProtocol.class.getMethod("ping", new Class[] {});
Object[] voids = (Object[])RPC.call(ping, new Object[][]{{},{}},
- new InetSocketAddress[] {addr, addr});
+ new InetSocketAddress[] {addr, addr}, nutchConf);
assertEquals(voids, null);
server.stop();
diff --git a/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java b/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java
index f0242209c..c4a6c1e6f 100644
--- a/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java
+++ b/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java
@@ -29,10 +29,11 @@ public class TestSequenceFileInputFormat extends TestCase {
private static final Logger LOG = InputFormatBase.LOG;
private static int MAX_LENGTH = 10000;
+ private static NutchConf nutchConf = new NutchConf();
public void testFormat() throws Exception {
- JobConf job = new JobConf(NutchConf.get());
- NutchFileSystem fs = NutchFileSystem.getNamed("local");
+ JobConf job = new JobConf(nutchConf);
+ NutchFileSystem fs = NutchFileSystem.getNamed("local", nutchConf);
File dir = new File(System.getProperty("test.build.data",".") + "/mapred");
File file = new File(dir, "test.seq");
diff --git a/src/test/org/apache/nutch/mapred/TestTextInputFormat.java b/src/test/org/apache/nutch/mapred/TestTextInputFormat.java
index 0b60eedc7..0b71bf531 100644
--- a/src/test/org/apache/nutch/mapred/TestTextInputFormat.java
+++ b/src/test/org/apache/nutch/mapred/TestTextInputFormat.java
@@ -29,10 +29,11 @@ public class TestTextInputFormat extends TestCase {
private static final Logger LOG = InputFormatBase.LOG;
private static int MAX_LENGTH = 10000;
-
+ private static NutchConf nutchConf = new NutchConf();
+
public void testFormat() throws Exception {
- JobConf job = new JobConf(NutchConf.get());
- NutchFileSystem fs = NutchFileSystem.getNamed("local");
+ JobConf job = new JobConf(nutchConf);
+ NutchFileSystem fs = NutchFileSystem.getNamed("local", nutchConf);
File dir = new File(System.getProperty("test.build.data",".") + "/mapred");
File file = new File(dir, "test.txt");
diff --git a/src/test/org/apache/nutch/ndfs/TestNDFS.java b/src/test/org/apache/nutch/ndfs/TestNDFS.java
index 5cce29859..1b39311b4 100644
--- a/src/test/org/apache/nutch/ndfs/TestNDFS.java
+++ b/src/test/org/apache/nutch/ndfs/TestNDFS.java
@@ -72,8 +72,9 @@ public class TestNDFS extends TestCase implements FSConstants {
private static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.ndfs.TestNDFS");
+ private static NutchConf nutchConf = new NutchConf();
private static int BUFFER_SIZE =
- NutchConf.get().getInt("io.file.buffer.size", 4096);
+ nutchConf.getInt("io.file.buffer.size", 4096);
private static int testCycleNumber = 0;
@@ -124,7 +125,7 @@ public class TestNDFS extends TestCase implements FSConstants {
protected void setUp() throws Exception {
super.setUp();
- NutchConf.get().setBoolean("test.ndfs.same.host.targets.allowed", true);
+ nutchConf.setBoolean("test.ndfs.same.host.targets.allowed", true);
}
/**
@@ -134,7 +135,7 @@ public class TestNDFS extends TestCase implements FSConstants {
protected void prepareTempFileSpace() {
if (baseDir.exists()) {
try { // start from a blank slate
- FileUtil.fullyDelete(baseDir);
+ FileUtil.fullyDelete(baseDir, nutchConf);
} catch (Exception ignored) {
}
}
@@ -192,17 +193,17 @@ public class TestNDFS extends TestCase implements FSConstants {
//
// set given config param to override other config settings
- NutchConf.get().setInt("test.ndfs.block_size", blockSize);
+ nutchConf.setInt("test.ndfs.block_size", blockSize);
// verify that config changed
- assertTrue(blockSize == NutchConf.get().getInt("test.ndfs.block_size", 2)); // 2 is an intentional obviously-wrong block size
+ assertTrue(blockSize == nutchConf.getInt("test.ndfs.block_size", 2)); // 2 is an intentional obviously-wrong block size
// downsize for testing (just to save resources)
- NutchConf.get().setInt("ndfs.namenode.handler.count", 3);
+ nutchConf.setInt("ndfs.namenode.handler.count", 3);
if (false) { // use MersenneTwister, if present
- NutchConf.get().set("nutch.random.class",
+ nutchConf.set("nutch.random.class",
"org.apache.nutch.util.MersenneTwister");
}
- NutchConf.get().setLong("ndfs.blockreport.intervalMsec", 50*1000L);
- NutchConf.get().setLong("ndfs.datanode.startupMsec", 15*1000L);
+ nutchConf.setLong("ndfs.blockreport.intervalMsec", 50*1000L);
+ nutchConf.setLong("ndfs.datanode.startupMsec", 15*1000L);
String nameFSDir = baseDirSpecified + "/name";
msg("----Start Test Cycle=" + currentTestCycleNumber +
@@ -216,20 +217,19 @@ public class TestNDFS extends TestCase implements FSConstants {
int nameNodePort = 9000 + testCycleNumber++; // ToDo: settable base port
String nameNodeSocketAddr = "localhost:" + nameNodePort;
- NameNode nameNodeDaemon = new NameNode(new File(nameFSDir), nameNodePort);
+ NameNode nameNodeDaemon = new NameNode(new File(nameFSDir), nameNodePort, nutchConf);
NDFSClient ndfsClient = null;
try {
//
// start some DataNodes
//
ArrayList listOfDataNodeDaemons = new ArrayList();
- NutchConf conf = NutchConf.get();
- conf.set("fs.default.name", nameNodeSocketAddr);
+ nutchConf.set("fs.default.name", nameNodeSocketAddr);
for (int i = 0; i < initialDNcount; i++) {
// uniquely config real fs path for data storage for this datanode
String dataDir = baseDirSpecified + "/datanode" + i;
- conf.set("ndfs.data.dir", dataDir);
- DataNode dn = DataNode.makeInstanceForDir(dataDir, conf);
+ nutchConf.set("ndfs.data.dir", dataDir);
+ DataNode dn = DataNode.makeInstanceForDir(dataDir, nutchConf);
if (dn != null) {
listOfDataNodeDaemons.add(dn);
(new Thread(dn, "DataNode" + i + ": " + dataDir)).start();
@@ -244,7 +244,7 @@ public class TestNDFS extends TestCase implements FSConstants {
awaitQuiescence();
// act as if namenode is a remote process
- ndfsClient = new NDFSClient(new InetSocketAddress("localhost", nameNodePort));
+ ndfsClient = new NDFSClient(new InetSocketAddress("localhost", nameNodePort), nutchConf);
//
// write nBytes of data using randomDataGenerator to numFiles
@@ -431,12 +431,12 @@ public class TestNDFS extends TestCase implements FSConstants {
* testing (a default is set here if property is not set.)
*/
private Random makeRandomDataGenerator() {
- long seed = NutchConf.get().getLong("test.ndfs.random.seed", 0xB437EF);
+ long seed = nutchConf.getLong("test.ndfs.random.seed", 0xB437EF);
try {
if (randomDataGeneratorCtor == null) {
// lazy init
String rndDataGenClassname =
- NutchConf.get().get("nutch.random.class", "java.util.Random");
+ nutchConf.get("nutch.random.class", "java.util.Random");
Class clazz = Class.forName(rndDataGenClassname);
randomDataGeneratorCtor = clazz.getConstructor(new Class[]{Long.TYPE});
}
diff --git a/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java b/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java
index 9f595aaf3..181448291 100644
--- a/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java
+++ b/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java
@@ -17,6 +17,9 @@
package org.apache.nutch.net;
import java.net.URL;
+
+import org.apache.nutch.util.NutchConf;
+
import junit.framework.TestCase;
/** Unit tests for BasicUrlNormalizer. */
@@ -81,7 +84,7 @@ public class TestBasicUrlNormalizer extends TestCase {
}
private void normalizeTest(String weird, String normal) throws Exception {
- assertEquals(normal, UrlNormalizerFactory.getNormalizer().normalize(weird));
+ assertEquals(normal, new UrlNormalizerFactory(new NutchConf()).getNormalizer().normalize(weird));
}
public static void main(String[] args) throws Exception {
diff --git a/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java b/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java
index 9429d1a5a..4ad51d359 100644
--- a/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java
+++ b/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java
@@ -18,6 +18,7 @@ package org.apache.nutch.parse;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.parse.OutlinkExtractor;
+import org.apache.nutch.util.NutchConf;
import junit.framework.TestCase;
@@ -30,14 +31,15 @@ import junit.framework.TestCase;
*/
public class TestOutlinkExtractor extends TestCase {
+ private static NutchConf nutchConf = new NutchConf();
public void testGetNoOutlinks() {
Outlink[] outlinks = null;
- outlinks = OutlinkExtractor.getOutlinks(null);
+ outlinks = OutlinkExtractor.getOutlinks(null, nutchConf);
assertNotNull(outlinks);
assertEquals(0, outlinks.length);
- outlinks = OutlinkExtractor.getOutlinks("");
+ outlinks = OutlinkExtractor.getOutlinks("", nutchConf);
assertNotNull(outlinks);
assertEquals(0, outlinks.length);
}
@@ -46,7 +48,7 @@ public class TestOutlinkExtractor extends TestCase {
Outlink[] outlinks = OutlinkExtractor.getOutlinks(
"Test with http://www.nutch.org/index.html is it found? " +
"What about www.google.com at http://www.google.de " +
- "A longer URL could be http://www.sybit.com/solutions/portals.html");
+ "A longer URL could be http://www.sybit.com/solutions/portals.html", nutchConf);
assertTrue("Url not found!", outlinks.length == 3);
assertEquals("Wrong URL", "http://www.nutch.org/index.html", outlinks[0].getToUrl());
@@ -58,7 +60,7 @@ public class TestOutlinkExtractor extends TestCase {
Outlink[] outlinks = OutlinkExtractor.getOutlinks(
"Test with http://www.nutch.org/index.html is it found? " +
"What about www.google.com at http://www.google.de " +
- "A longer URL could be http://www.sybit.com/solutions/portals.html", "http://www.sybit.de");
+ "A longer URL could be http://www.sybit.com/solutions/portals.html", "http://www.sybit.de", nutchConf);
assertTrue("Url not found!", outlinks.length == 3);
assertEquals("Wrong URL", "http://www.nutch.org/index.html", outlinks[0].getToUrl());
@@ -68,7 +70,7 @@ public class TestOutlinkExtractor extends TestCase {
public void testGetOutlinksFtp() {
Outlink[] outlinks = OutlinkExtractor.getOutlinks(
"Test with ftp://www.nutch.org is it found? " +
- "What about www.google.com at ftp://www.google.de");
+ "What about www.google.com at ftp://www.google.de", nutchConf);
assertTrue("Url not found!", outlinks.length >1);
assertEquals("Wrong URL", "ftp://www.nutch.org/", outlinks[0].getToUrl());
diff --git a/src/test/org/apache/nutch/parse/TestParseData.java b/src/test/org/apache/nutch/parse/TestParseData.java
index 85e9419c2..fa7b29c0b 100644
--- a/src/test/org/apache/nutch/parse/TestParseData.java
+++ b/src/test/org/apache/nutch/parse/TestParseData.java
@@ -18,11 +18,16 @@ package org.apache.nutch.parse;
import org.apache.nutch.io.*;
import org.apache.nutch.protocol.ContentProperties;
+import org.apache.nutch.util.NutchConf;
+
import junit.framework.TestCase;
/** Unit tests for ParseData. */
public class TestParseData extends TestCase {
+
+ private NutchConf nutchConf = new NutchConf();
+
public TestParseData(String name) { super(name); }
public void testParseData() throws Exception {
@@ -30,8 +35,8 @@ public class TestParseData extends TestCase {
String title = "The Foo Page";
Outlink[] outlinks = new Outlink[] {
- new Outlink("http://foo.com/", "Foo"),
- new Outlink("http://bar.com/", "Bar")
+ new Outlink("http://foo.com/", "Foo", nutchConf),
+ new Outlink("http://bar.com/", "Bar", nutchConf)
};
ContentProperties metaData = new ContentProperties();
@@ -39,6 +44,7 @@ public class TestParseData extends TestCase {
metaData.put("Charset", "UTF-8");
ParseData r = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);
+ r.setConf(nutchConf);
TestWritable.testWritable(r);
}
diff --git a/src/test/org/apache/nutch/parse/TestParserFactory.java b/src/test/org/apache/nutch/parse/TestParserFactory.java
index 1daf65482..92f899769 100644
--- a/src/test/org/apache/nutch/parse/TestParserFactory.java
+++ b/src/test/org/apache/nutch/parse/TestParserFactory.java
@@ -27,6 +27,7 @@ import org.apache.nutch.util.NutchConf;
import java.io.File;
import java.net.MalformedURLException;
+import java.util.Arrays;
/**
@@ -37,69 +38,74 @@ import java.net.MalformedURLException;
*/
public class TestParserFactory extends TestCase {
-
+ private NutchConf nutchConf;
+ private ParserFactory parserFactory;
+
public TestParserFactory(String name) { super(name); }
/** Inits the Test Case with the test parse-plugin file */
protected void setUp() throws Exception {
- NutchConf.get().set("parse.plugin.file",
+ nutchConf = new NutchConf();
+ nutchConf.set("plugin.includes", ".*");
+ nutchConf.set("parse.plugin.file",
"org/apache/nutch/parse/parse-plugin-test.xml");
+ parserFactory = new ParserFactory(nutchConf);
}
/** Unit test for <code>getParser(String, String)</code> method. */
public void testGetParser() throws Exception {
- Parser parser = ParserFactory.getParser("text/html", "http://foo.com/");
+ Parser parser = parserFactory.getParser("text/html", "http://foo.com/");
assertNotNull(parser);
- parser = ParserFactory.getParser("foo/bar", "http://foo.com/");
+ parser = parserFactory.getParser("foo/bar", "http://foo.com/");
assertNotNull(parser);
}
/** Unit test for <code>getExtensions(String)</code> method. */
public void testGetExtensions() throws Exception {
- Extension ext = (Extension)ParserFactory.getExtensions("text/html").get(0);
+ Extension ext = (Extension)parserFactory.getExtensions("text/html").get(0);
assertEquals("parse-html", ext.getDescriptor().getPluginId());
- ext = (Extension) ParserFactory.getExtensions("text/html; charset=ISO-8859-1").get(0);
+ ext = (Extension) parserFactory.getExtensions("text/html; charset=ISO-8859-1").get(0);
assertEquals("parse-html", ext.getDescriptor().getPluginId());
- ext = (Extension)ParserFactory.getExtensions("foo/bar").get(0);
+ ext = (Extension)parserFactory.getExtensions("foo/bar").get(0);
assertEquals("parse-text", ext.getDescriptor().getPluginId());
}
/** Unit test to check <code>getParsers</code> method */
public void testGetParsers() throws Exception {
- Parser [] parsers = ParserFactory.getParsers("text/html", "http://foo.com");
+ Parser [] parsers = parserFactory.getParsers("text/html", "http://foo.com");
assertNotNull(parsers);
assertEquals(1, parsers.length);
assertEquals("org.apache.nutch.parse.html.HtmlParser",
parsers[0].getClass().getName());
- parsers = ParserFactory.getParsers("text/html; charset=ISO-8859-1", "http://foo.com");
+ parsers = parserFactory.getParsers("text/html; charset=ISO-8859-1", "http://foo.com");
assertNotNull(parsers);
assertEquals(1, parsers.length);
assertEquals("org.apache.nutch.parse.html.HtmlParser",
parsers[0].getClass().getName());
- parsers = ParserFactory.getParsers("application/x-javascript",
+ parsers = parserFactory.getParsers("application/x-javascript",
"http://foo.com");
assertNotNull(parsers);
assertEquals(1, parsers.length);
assertEquals("org.apache.nutch.parse.js.JSParseFilter",
parsers[0].getClass().getName());
- parsers = ParserFactory.getParsers("text/plain", "http://foo.com");
+ parsers = parserFactory.getParsers("text/plain", "http://foo.com");
assertNotNull(parsers);
assertEquals(1, parsers.length);
assertEquals("org.apache.nutch.parse.text.TextParser",
parsers[0].getClass().getName());
- Parser parser1 = ParserFactory.getParsers("text/plain", "http://foo.com")[0];
- Parser parser2 = ParserFactory.getParsers("*", "http://foo.com")[0];
+ Parser parser1 = parserFactory.getParsers("text/plain", "http://foo.com")[0];
+ Parser parser2 = parserFactory.getParsers("*", "http://foo.com")[0];
assertEquals("Different instances!", parser1.hashCode(), parser2.hashCode());
//test and make sure that the rss parser is loaded even though its plugin.xml
//doesn't claim to support text/rss, only application/rss+xml
- parsers = ParserFactory.getParsers("text/rss","http://foo.com");
+ parsers = parserFactory.getParsers("text/rss","http://foo.com");
assertNotNull(parsers);
assertEquals(1,parsers.length);
assertEquals("org.apache.nutch.parse.rss.RSSParser",parsers[0].getClass().getName());
diff --git a/src/test/org/apache/nutch/plugin/TestPluginSystem.java b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
index 15195b43a..3359cbca6 100644
--- a/src/test/org/apache/nutch/plugin/TestPluginSystem.java
+++ b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
@@ -38,10 +38,17 @@ public class TestPluginSystem extends TestCase {
private int fPluginCount;
private LinkedList fFolders = new LinkedList();
+ private NutchConf nutchConf ;
+ private PluginRepository repository;
protected void setUp() throws Exception {
+ this.nutchConf = new NutchConf();
+ nutchConf.set("plugin.includes", ".*");
+// String string = this.nutchConf.get("plugin.includes", "");
+// nutchConf.set("plugin.includes", string + "|Dummy*");
fPluginCount = 5;
createDummyPlugins(fPluginCount);
+ this.repository = nutchConf.getPluginRepository();
}
/*
@@ -72,7 +79,7 @@ public class TestPluginSystem extends TestCase {
/**
*/
public void testLoadPlugins() {
- PluginDescriptor[] descriptors = PluginRepository.getInstance()
+ PluginDescriptor[] descriptors = repository
.getPluginDescriptors();
int k = descriptors.length;
assertTrue(fPluginCount <= k);
@@ -91,10 +98,10 @@ public class TestPluginSystem extends TestCase {
*/
public void testGetExtensionAndAttributes() {
String xpId = " sdsdsd";
- ExtensionPoint extensionPoint = PluginRepository.getInstance()
+ ExtensionPoint extensionPoint =repository
.getExtensionPoint(xpId);
assertEquals(extensionPoint, null);
- Extension[] extension1 = PluginRepository.getInstance()
+ Extension[] extension1 = repository
.getExtensionPoint(getGetExtensionId()).getExtensions();
assertEquals(extension1.length, fPluginCount);
for (int i = 0; i < extension1.length; i++) {
@@ -108,7 +115,7 @@ public class TestPluginSystem extends TestCase {
* @throws PluginRuntimeException
*/
public void testGetExtensionInstances() throws PluginRuntimeException {
- Extension[] extensions = PluginRepository.getInstance()
+ Extension[] extensions = repository
.getExtensionPoint(getGetExtensionId()).getExtensions();
assertEquals(extensions.length, fPluginCount);
for (int i = 0; i < extensions.length; i++) {
@@ -127,7 +134,7 @@ public class TestPluginSystem extends TestCase {
*
*/
public void testGetClassLoader() {
- PluginDescriptor[] descriptors = PluginRepository.getInstance()
+ PluginDescriptor[] descriptors = repository
.getPluginDescriptors();
for (int i = 0; i < descriptors.length; i++) {
PluginDescriptor descriptor = descriptors[i];
@@ -139,7 +146,7 @@ public class TestPluginSystem extends TestCase {
* @throws IOException
*/
public void testGetResources() throws IOException {
- PluginDescriptor[] descriptors = PluginRepository.getInstance()
+ PluginDescriptor[] descriptors = repository
.getPluginDescriptors();
for (int i = 0; i < descriptors.length; i++) {
PluginDescriptor descriptor = descriptors[i];
@@ -159,12 +166,12 @@ public class TestPluginSystem extends TestCase {
* @return a PluginFolderPath
*/
private String getPluginFolder() {
- String[] strings = NutchConf.get().getStrings("plugin.folders");
+ String[] strings = nutchConf.getStrings("plugin.folders");
if (strings == null || strings.length == 0)
fail("no plugin directory setuped..");
String name = strings[0];
- return PluginManifestParser.getPluginFolder(name).toString();
+ return new PluginManifestParser(nutchConf, this.repository).getPluginFolder(name).toString();
}
/**
diff --git a/src/test/org/apache/nutch/protocol/TestContent.java b/src/test/org/apache/nutch/protocol/TestContent.java
index 152d3980b..9d15aae81 100644
--- a/src/test/org/apache/nutch/protocol/TestContent.java
+++ b/src/test/org/apache/nutch/protocol/TestContent.java
@@ -17,11 +17,16 @@
package org.apache.nutch.protocol;
import org.apache.nutch.io.*;
+import org.apache.nutch.util.NutchConf;
+
import junit.framework.TestCase;
/** Unit tests for Content. */
public class TestContent extends TestCase {
+
+ private static NutchConf nutchConf = new NutchConf();
+
public TestContent(String name) { super(name); }
public void testContent() throws Exception {
@@ -35,7 +40,7 @@ public class TestContent extends TestCase {
metaData.put("Content-Type", "text/html");
Content r = new Content(url, url, page.getBytes("UTF8"), "text/html",
- metaData);
+ metaData, nutchConf);
TestWritable.testWritable(r);
assertEquals("text/html", r.getMetadata().get("Content-Type"));
@@ -50,49 +55,49 @@ public class TestContent extends TestCase {
c = new Content("http://www.foo.com/",
"http://www.foo.com/",
"".getBytes("UTF8"),
- "text/html; charset=UTF-8", p);
+ "text/html; charset=UTF-8", p, nutchConf);
assertEquals("text/html", c.getContentType());
c = new Content("http://www.foo.com/foo.html",
"http://www.foo.com/",
"".getBytes("UTF8"),
- "", p);
+ "", p, nutchConf);
assertEquals("text/html", c.getContentType());
c = new Content("http://www.foo.com/foo.html",
"http://www.foo.com/",
"".getBytes("UTF8"),
- null, p);
+ null, p, nutchConf);
assertEquals("text/html", c.getContentType());
c = new Content("http://www.foo.com/",
"http://www.foo.com/",
"<html></html>".getBytes("UTF8"),
- "", p);
+ "", p, nutchConf);
assertEquals("text/html", c.getContentType());
c = new Content("http://www.foo.com/foo.html",
"http://www.foo.com/",
"<html></html>".getBytes("UTF8"),
- "text/plain", p);
+ "text/plain", p, nutchConf);
assertEquals("text/html", c.getContentType());
c = new Content("http://www.foo.com/foo.png",
"http://www.foo.com/",
"<html></html>".getBytes("UTF8"),
- "text/plain", p);
+ "text/plain", p, nutchConf);
assertEquals("text/html", c.getContentType());
c = new Content("http://www.foo.com/",
"http://www.foo.com/",
"".getBytes("UTF8"),
- "", p);
+ "", p, nutchConf);
assertEquals("", c.getContentType());
c = new Content("http://www.foo.com/",
"http://www.foo.com/",
"".getBytes("UTF8"),
- null, p);
+ null, p, nutchConf);
assertNull(c.getContentType());
}
diff --git a/src/test/org/apache/nutch/protocol/TestContentProperties.java b/src/test/org/apache/nutch/protocol/TestContentProperties.java
index 05bd35d6f..99f8f1e21 100644
--- a/src/test/org/apache/nutch/protocol/TestContentProperties.java
+++ b/src/test/org/apache/nutch/protocol/TestContentProperties.java
@@ -17,6 +17,7 @@
package org.apache.nutch.protocol;
import org.apache.nutch.io.TestWritable;
+import org.apache.nutch.util.NutchConf;
import junit.framework.TestCase;
@@ -53,7 +54,7 @@ public class TestContentProperties extends TestCase {
}
TestWritable.testWritable(properties);
Content content = new Content("url", "url", new byte[0], "text/html",
- new ContentProperties());
+ new ContentProperties(), new NutchConf());
ContentProperties metadata = content.getMetadata();
for (int i = 0; i < 100; i++) {
metadata.setProperty("aKey", "" + i);
diff --git a/src/test/org/apache/nutch/searcher/TestQuery.java b/src/test/org/apache/nutch/searcher/TestQuery.java
index 3fb446f3a..98c2bdecf 100644
--- a/src/test/org/apache/nutch/searcher/TestQuery.java
+++ b/src/test/org/apache/nutch/searcher/TestQuery.java
@@ -20,36 +20,40 @@ import java.io.*;
import junit.framework.TestCase;
import java.util.Arrays;
import org.apache.nutch.analysis.NutchAnalysis;
+import org.apache.nutch.util.NutchConf;
public class TestQuery extends TestCase {
+
+ private static NutchConf nutchConf = new NutchConf();
+
public TestQuery(String name) { super(name); }
public void testRequiredTerm() throws Exception {
- Query query = new Query();
+ Query query = new Query(nutchConf);
query.addRequiredTerm("bobo");
testQuery(query, "bobo");
}
public void testProhibitedTerm() throws Exception {
- Query query = new Query();
+ Query query = new Query(nutchConf);
query.addProhibitedTerm("bobo");
testQuery(query, "-bobo");
}
public void testRequiredPhrase() throws Exception {
- Query query = new Query();
+ Query query = new Query(nutchConf);
query.addRequiredPhrase(new String[] {"bobo", "bogo"});
testQuery(query, "\"bobo bogo\"");
}
public void testProhibitedPhrase() throws Exception {
- Query query = new Query();
+ Query query = new Query(nutchConf);
query.addProhibitedPhrase(new String[] {"bobo", "bogo"});
testQuery(query, "-\"bobo bogo\"");
}
public void testComplex() throws Exception {
- Query query = new Query();
+ Query query = new Query(nutchConf);
query.addRequiredTerm("bobo");
query.addProhibitedTerm("bono");
query.addRequiredPhrase(new String[] {"bobo", "bogo"});
@@ -69,7 +73,7 @@ public class TestQuery extends TestCase {
public static void testQueryParser(Query query, String string)
throws Exception {
- Query after = NutchAnalysis.parseQuery(string);
+ Query after = NutchAnalysis.parseQuery(string, nutchConf);
assertEquals(after, query);
assertEquals(after.toString(), string);
}
@@ -82,7 +86,7 @@ public class TestQuery extends TestCase {
ByteArrayInputStream iBuf = new ByteArrayInputStream(oBuf.toByteArray());
DataInputStream in = new DataInputStream(iBuf);
- Query after = Query.read(in);
+ Query after = Query.read(in, nutchConf);
assertEquals(after, query);
}
@@ -95,7 +99,7 @@ public class TestQuery extends TestCase {
public static void testQueryTerms(String query, String[] terms)
throws Exception {
- assertTrue(Arrays.equals(NutchAnalysis.parseQuery(query).getTerms(),
+ assertTrue(Arrays.equals(NutchAnalysis.parseQuery(query, nutchConf).getTerms(),
terms));
}
diff --git a/src/web/jsp/anchors.jsp b/src/web/jsp/anchors.jsp
index 84f5aebed..3a66a13cc 100644
--- a/src/web/jsp/anchors.jsp
+++ b/src/web/jsp/anchors.jsp
@@ -9,8 +9,14 @@
import="org.apache.nutch.html.Entities"
import="org.apache.nutch.searcher.*"
+ import="org.apache.nutch.util.NutchConf"
%><%
- NutchBean bean = NutchBean.get(application);
+ NutchConf nutchConf = (NutchConf) application.getAttribute(NutchConf.class.getName());
+ if (nutchConf == null) {
+ nutchConf = new NutchConf();
+ application.setAttribute(NutchConf.class.getName(), nutchConf);
+ }
+ NutchBean bean = NutchBean.get(application, nutchConf);
// set the character encoding to use when interpreting request values
request.setCharacterEncoding("UTF-8");
bean.LOG.info("anchors request from " + request.getRemoteAddr());
diff --git a/src/web/jsp/cached.jsp b/src/web/jsp/cached.jsp
index 07b12eebb..34e3f6f25 100644
--- a/src/web/jsp/cached.jsp
+++ b/src/web/jsp/cached.jsp
@@ -8,8 +8,14 @@
import="org.apache.nutch.searcher.*"
import="org.apache.nutch.parse.ParseData"
import="org.apache.nutch.protocol.ContentProperties"
+ import="org.apache.nutch.util.NutchConf"
%><%
- NutchBean bean = NutchBean.get(application);
+ NutchConf nutchConf = (NutchConf) application.getAttribute(NutchConf.class.getName());
+ if (nutchConf == null) {
+ nutchConf = new NutchConf();
+ application.setAttribute(NutchConf.class.getName(), nutchConf);
+ }
+ NutchBean bean = NutchBean.get(application, nutchConf);
bean.LOG.info("cache request from " + request.getRemoteAddr());
Hit hit = new Hit(Integer.parseInt(request.getParameter("idx")),
Integer.parseInt(request.getParameter("id")));
diff --git a/src/web/jsp/explain.jsp b/src/web/jsp/explain.jsp
index 88f567236..803fc81dc 100644
--- a/src/web/jsp/explain.jsp
+++ b/src/web/jsp/explain.jsp
@@ -7,15 +7,21 @@
import="java.io.*"
import="java.util.*"
import="org.apache.nutch.searcher.*"
+ import="org.apache.nutch.util.NutchConf"
%><%
- NutchBean bean = NutchBean.get(application);
+ NutchConf nutchConf = (NutchConf) application.getAttribute(NutchConf.class.getName());
+ if (nutchConf == null) {
+ nutchConf = new NutchConf();
+ application.setAttribute(NutchConf.class.getName(), nutchConf);
+ }
+ NutchBean bean = NutchBean.get(application, nutchConf);
// set the character encoding to use when interpreting request values
request.setCharacterEncoding("UTF-8");
bean.LOG.info("explain request from " + request.getRemoteAddr());
Hit hit = new Hit(Integer.parseInt(request.getParameter("idx")),
Integer.parseInt(request.getParameter("id")));
HitDetails details = bean.getDetails(hit);
- Query query = Query.parse(request.getParameter("query"));
+ Query query = Query.parse(request.getParameter("query"), nutchConf);
String language =
ResourceBundle.getBundle("org.nutch.jsp.explain", request.getLocale())
.getLocale().getLanguage();
diff --git a/src/web/jsp/refine-query-init.jsp b/src/web/jsp/refine-query-init.jsp
index 2ac7a5165..ac8b2c8a2 100644
--- a/src/web/jsp/refine-query-init.jsp
+++ b/src/web/jsp/refine-query-init.jsp
@@ -1,4 +1,4 @@
-<%!
+<%
// 20041129, Mike Pan and John Xing
// Initiates Ontology ontology and loads in all owl files.
@@ -6,16 +6,20 @@
// siliently ignored.
// Please check ./refine-query.jsp, which provides query-refinement hypertext.
-private static org.apache.nutch.ontology.Ontology ontology;
+org.apache.nutch.ontology.Ontology ontology = null;
// note: should we ignore plugin exceptions, or rethrow it below?
// Rethrowing it effectively prevents the servlet class from
// being loaded into the JVM. Need improvement in future.
-static {
try {
- String urls = org.apache.nutch.util.NutchConf.get().get("extension.ontology.urls");
- ontology = org.apache.nutch.ontology.OntologyFactory.getOntology();
+ org.apache.nutch.util.NutchConf nutchConf = (org.apache.nutch.util.NutchConf) application.getAttribute(org.apache.nutch.util.NutchConf.class.getName());
+ if (nutchConf == null) {
+ nutchConf = new org.apache.nutch.util.NutchConf();
+ application.setAttribute(org.apache.nutch.util.NutchConf.class.getName(), nutchConf);
+ }
+ String urls = nutchConf.get("extension.ontology.urls");
+ ontology = new org.apache.nutch.ontology.OntologyFactory(nutchConf).getOntology();
if (urls==null || urls.trim().equals("")) {
// ignored siliently
} else {
@@ -24,6 +28,5 @@ static {
} catch (Exception e) {
// ignored siliently
}
-};
%>
diff --git a/src/web/jsp/search.jsp b/src/web/jsp/search.jsp
index 681a51d9e..ce2dead31 100644
--- a/src/web/jsp/search.jsp
+++ b/src/web/jsp/search.jsp
@@ -14,44 +14,43 @@
import="org.apache.nutch.clustering.*"
import="org.apache.nutch.util.NutchConf"
-%><%!
- // NOTE: Dawid Weiss
- // these are servlet's class variables. Merely to speed up access
- // to them (instead of referencing static objects).
-
+%><%
+ NutchConf nutchConf = (NutchConf) application.getAttribute(NutchConf.class.getName());
+ if (nutchConf == null) {
+ nutchConf = new NutchConf();
+ application.setAttribute(NutchConf.class.getName(), nutchConf);
+ }
+
/**
* Number of hits to retrieve and cluster if clustering extension is available
* and clustering is on. By default, 100. Configurable via nutch-conf.xml.
*/
- private final static int HITS_TO_CLUSTER =
- NutchConf.get().getInt("extension.clustering.hits-to-cluster", 100);
+ int HITS_TO_CLUSTER =
+ nutchConf.getInt("extension.clustering.hits-to-cluster", 100);
/**
* An instance of the clustering extension, if available.
*/
- private static OnlineClusterer clusterer;
-
- static {
- try {
- clusterer = OnlineClustererFactory.getOnlineClusterer();
- } catch (PluginRuntimeException e) {
- // NOTE: Dawid Weiss
- // should we ignore plugin exceptions, or rethrow it? Rethrowing
- // it effectively prevents the servlet class from being loaded into
- // the JVM
- }
+ OnlineClusterer clusterer = null;
+ try {
+ clusterer = new OnlineClustererFactory(nutchConf).getOnlineClusterer();
+ } catch (PluginRuntimeException e) {
+ // NOTE: Dawid Weiss
+ // should we ignore plugin exceptions, or rethrow it? Rethrowing
+ // it effectively prevents the servlet class from being loaded into
+ // the JVM
}
%>
<%--
// Uncomment this to enable query refinement.
-// Do the same to "refine-query.jsp" below.
+// Do the same to "refine-query.jsp" below.,
<%@ include file="./refine-query-init.jsp" %>
--%>
<%
- NutchBean bean = NutchBean.get(application);
+ NutchBean bean = NutchBean.get(application, nutchConf);
// set the character encoding to use when interpreting request values
request.setCharacterEncoding("UTF-8");
@@ -94,7 +93,7 @@
int hitsToCluster = HITS_TO_CLUSTER; // number of hits to cluster
- Query query = Query.parse(queryString);
+ Query query = Query.parse(queryString, nutchConf);
bean.LOG.info("query: " + queryString);
String language =
diff --git a/src/web/jsp/text.jsp b/src/web/jsp/text.jsp
index 9d08064b2..866767fbc 100644
--- a/src/web/jsp/text.jsp
+++ b/src/web/jsp/text.jsp
@@ -7,12 +7,17 @@
import="org.apache.nutch.searcher.*"
import="org.apache.nutch.parse.ParseText"
+ import="org.apache.nutch.util.NutchConf"
%><%
// show the content of a hit as plain text
-
- NutchBean bean = NutchBean.get(application);
+ NutchConf nutchConf = (NutchConf) application.getAttribute(NutchConf.class.getName());
+ if (nutchConf == null) {
+ nutchConf = new NutchConf();
+ application.setAttribute(NutchConf.class.getName(), nutchConf);
+ }
+ NutchBean bean = NutchBean.get(application, nutchConf);
bean.LOG.info("text request from " + request.getRemoteAddr());