Apache Nutch is an extensible and scalable web crawler
Refactor URLNormalizers (NUTCH-365). Iterative normalization has been implemented, but is not used by default.
Andrzej Bialeckide526b301d97
diff --git a/conf/nutch-default.xml b/conf/nutch-default.xmlindex 86a8b2259..3ab845dcd 100644--- a/conf/nutch-default.xml+++ b/conf/nutch-default.xml@@ -622,15 +622,29 @@<!-- URL normalizer properties --><property>- <name>urlnormalizer.class</name>- <value>org.apache.nutch.net.BasicUrlNormalizer</value>- <description>Name of the class used to normalize URLs.</description>+ <name>urlnormalizer.order</name>+ <value>org.apache.nutch.net.urlnormalizer.basic.BasicURLNormalizer org.apache.nutch.net.urlnormalizer.regex.RegexURLNormalizer</value>+ <description>Order in which normalizers will run. If any of these isn't+ activated it will be silently skipped. If other normalizers not on the+ list are activated, they will run in random order after the ones+ specified here are run.+ </description></property><property><name>urlnormalizer.regex.file</name><value>regex-normalize.xml</value>- <description>Name of the config file used by the RegexUrlNormalizer class.</description></property>+ <description>Name of the config file used by the RegexUrlNormalizer class.+ </description>+</property>++<property>+ <name>urlnormalizer.loop.count</name>+ <value>1</value>+ <description>Optionally loop through normalizers several times, to make+ sure that all transformations have been performed.+ </description>+</property><!-- mime properties -->@@ -669,7 +683,7 @@<property><name>plugin.includes</name>- <value>protocol-http|urlfilter-regex|parse-(text|html|js)|index-basic|query-(basic|site|url)|summary-basic|scoring-opic</value>+ <value>protocol-http|urlfilter-regex|parse-(text|html|js)|index-basic|query-(basic|site|url)|summary-basic|scoring-opic|urlnormalizer-(pass|regex|basic)</value><description>Regular expression naming plugin directory names toinclude. Any plugin not matching this expression is excluded.In any case you need at least include the nutch-extensionpoints plugin. Bydiff --git a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java b/src/java/org/apache/nutch/crawl/CrawlDbFilter.javaindex b11f04a9e..201e10ecb 100644--- a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java+++ b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java@@ -28,8 +28,7 @@ import org.apache.hadoop.mapred.Mapper;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reporter;import org.apache.nutch.net.URLFilters;-import org.apache.nutch.net.UrlNormalizer;-import org.apache.nutch.net.UrlNormalizerFactory;+import org.apache.nutch.net.URLNormalizers;/*** This class provides a way to separate the URL normalization@@ -40,29 +39,34 @@ import org.apache.nutch.net.UrlNormalizerFactory;public class CrawlDbFilter implements Mapper {public static final String URL_FILTERING = "crawldb.url.filters";- public static final String URL_NORMALIZING = "crawldb.url.normalizer";+ public static final String URL_NORMALIZING = "crawldb.url.normalizers";++ public static final String URL_NORMALIZING_SCOPE = "crawldb.url.normalizers.scope";private boolean urlFiltering;- private boolean urlNormalizer;+ private boolean urlNormalizers;private URLFilters filters;- private UrlNormalizer normalizer;+ private URLNormalizers normalizers;private JobConf jobConf;++ private String scope;public static final Log LOG = LogFactory.getLog(CrawlDbFilter.class);public void configure(JobConf job) {this.jobConf = job;urlFiltering = job.getBoolean(URL_FILTERING, false);- urlNormalizer = job.getBoolean(URL_NORMALIZING, false);+ urlNormalizers = job.getBoolean(URL_NORMALIZING, false);if (urlFiltering) {filters = new URLFilters(job);}- if (urlNormalizer) {- normalizer = new UrlNormalizerFactory(job).getNormalizer();+ if (urlNormalizers) {+ scope = job.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_CRAWLDB);+ normalizers = new URLNormalizers(job, scope);}}@@ -71,9 +75,9 @@ public class CrawlDbFilter implements Mapper {public void map(WritableComparable key, Writable value, OutputCollector output, Reporter reporter) throws IOException {String url = key.toString();- if (urlNormalizer) {+ if (urlNormalizers) {try {- url = normalizer.normalize(url); // normalize the url+ url = normalizers.normalize(url, scope); // normalize the url} catch (Exception e) {LOG.warn("Skipping " + url + ":" + e);url = null;diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.javaindex e3a73349e..b525d64e4 100644--- a/src/java/org/apache/nutch/crawl/Generator.java+++ b/src/java/org/apache/nutch/crawl/Generator.java@@ -33,6 +33,7 @@ import org.apache.hadoop.fs.Path;import org.apache.nutch.net.URLFilterException;import org.apache.nutch.net.URLFilters;+import org.apache.nutch.net.URLNormalizers;import org.apache.nutch.scoring.ScoringFilterException;import org.apache.nutch.scoring.ScoringFilters;import org.apache.nutch.util.NutchConfiguration;@@ -77,6 +78,7 @@ public class Generator extends ToolBase {private int maxPerHost;private Partitioner hostPartitioner = new PartitionUrlByHost();private URLFilters filters;+ private URLNormalizers normalizers;private ScoringFilters scfilters;private SelectorEntry entry = new SelectorEntry();private FloatWritable sortValue = new FloatWritable();@@ -89,7 +91,9 @@ public class Generator extends ToolBase {maxPerHost = job.getInt("generate.max.per.host", -1);byIP = job.getBoolean("generate.max.per.host.by.ip", false);filters = new URLFilters(job);+ normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_GENERATE_HOST_COUNT);scfilters = new ScoringFilters(job);+ hostPartitioner.configure(job);}public void close() {}@@ -170,6 +174,12 @@ public class Generator extends ToolBase {continue;}}+ try {+ host = normalizers.normalize(host, URLNormalizers.SCOPE_GENERATE_HOST_COUNT);+ host = new URL(host).getHost().toLowerCase();+ } catch (Exception e) {+ LOG.warn("Malformed URL: '" + host + "', skipping");+ }IntWritable hostCount = (IntWritable)hostCounts.get(host);if (hostCount == null) {hostCount = new IntWritable();diff --git a/src/java/org/apache/nutch/crawl/Injector.java b/src/java/org/apache/nutch/crawl/Injector.javaindex 81d8251c5..5b9e824d7 100644--- a/src/java/org/apache/nutch/crawl/Injector.java+++ b/src/java/org/apache/nutch/crawl/Injector.java@@ -44,16 +44,16 @@ public class Injector extends ToolBase {/** Normalize and filter injected urls. */public static class InjectMapper implements Mapper {- private UrlNormalizer urlNormalizer;+ private URLNormalizers urlNormalizers;private float interval;private float scoreInjected;private JobConf jobConf;private URLFilters filters;- private ScoringFilters scfilters;+ private ScoringFilters scfilters;public void configure(JobConf job) {this.jobConf = job;- urlNormalizer = new UrlNormalizerFactory(jobConf).getNormalizer();+ urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_INJECT);interval = jobConf.getFloat("db.default.fetch.interval", 30f);filters = new URLFilters(jobConf);scfilters = new ScoringFilters(jobConf);@@ -69,7 +69,7 @@ public class Injector extends ToolBase {String url = value.toString(); // value is line of text// System.out.println("url: " +url);try {- url = urlNormalizer.normalize(url); // normalize the url+ url = urlNormalizers.normalize(url, URLNormalizers.SCOPE_INJECT); // normalize the urlurl = filters.filter(url); // filter the url} catch (Exception e) {if (LOG.isWarnEnabled()) { LOG.warn("Skipping " +url+":"+e); }diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.javaindex 2154ac33e..3a7c682c8 100644--- a/src/java/org/apache/nutch/crawl/LinkDb.java+++ b/src/java/org/apache/nutch/crawl/LinkDb.java@@ -32,8 +32,7 @@ import org.apache.hadoop.mapred.*;import org.apache.hadoop.util.StringUtils;import org.apache.nutch.net.URLFilters;-import org.apache.nutch.net.UrlNormalizer;-import org.apache.nutch.net.UrlNormalizerFactory;+import org.apache.nutch.net.URLNormalizers;import org.apache.nutch.parse.*;import org.apache.nutch.util.NutchConfiguration;import org.apache.nutch.util.NutchJob;@@ -50,7 +49,7 @@ public class LinkDb extends ToolBase implements Mapper, Reducer {private int maxInlinks;private boolean ignoreInternalLinks;private URLFilters urlFilters;- private UrlNormalizer urlNormalizer;+ private URLNormalizers urlNormalizers;public static class Merger extends MapReduceBase implements Reducer {private int _maxInlinks;@@ -98,7 +97,7 @@ public class LinkDb extends ToolBase implements Mapper, Reducer {urlFilters = new URLFilters(job);}if (job.getBoolean(LinkDbFilter.URL_NORMALIZING, false)) {- urlNormalizer = new UrlNormalizerFactory(job).getNormalizer();+ urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_LINKDB);}}@@ -109,9 +108,9 @@ public class LinkDb extends ToolBase implements Mapper, Reducer {throws IOException {String fromUrl = key.toString();String fromHost = getHost(fromUrl);- if (urlNormalizer != null) {+ if (urlNormalizers != null) {try {- fromUrl = urlNormalizer.normalize(fromUrl); // normalize the url+ fromUrl = urlNormalizers.normalize(fromUrl, URLNormalizers.SCOPE_LINKDB); // normalize the url} catch (Exception e) {LOG.warn("Skipping " + fromUrl + ":" + e);fromUrl = null;@@ -139,9 +138,9 @@ public class LinkDb extends ToolBase implements Mapper, Reducer {continue; // skip it}}- if (urlNormalizer != null) {+ if (urlNormalizers != null) {try {- toUrl = urlNormalizer.normalize(toUrl); // normalize the url+ toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB); // normalize the url} catch (Exception e) {LOG.warn("Skipping " + toUrl + ":" + e);toUrl = null;diff --git a/src/java/org/apache/nutch/crawl/LinkDbFilter.java b/src/java/org/apache/nutch/crawl/LinkDbFilter.javaindex 03afaefd9..db0eebba1 100644--- a/src/java/org/apache/nutch/crawl/LinkDbFilter.java+++ b/src/java/org/apache/nutch/crawl/LinkDbFilter.java@@ -28,8 +28,7 @@ import org.apache.hadoop.mapred.Mapper;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reporter;import org.apache.nutch.net.URLFilters;-import org.apache.nutch.net.UrlNormalizer;-import org.apache.nutch.net.UrlNormalizerFactory;+import org.apache.nutch.net.URLNormalizers;/*** This class provides a way to separate the URL normalization@@ -42,16 +41,20 @@ public class LinkDbFilter implements Mapper {public static final String URL_NORMALIZING = "linkdb.url.normalizer";+ public static final String URL_NORMALIZING_SCOPE = "linkdb.url.normalizer.scope";+private boolean filter;private boolean normalize;private URLFilters filters;- private UrlNormalizer normalizer;+ private URLNormalizers normalizers;private JobConf jobConf;+ private String scope;+public static final Log LOG = LogFactory.getLog(LinkDbFilter.class);public void configure(JobConf job) {@@ -62,7 +65,8 @@ public class LinkDbFilter implements Mapper {filters = new URLFilters(job);}if (normalize) {- normalizer = new UrlNormalizerFactory(job).getNormalizer();+ scope = job.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_LINKDB);+ normalizers = new URLNormalizers(job, scope);}}@@ -72,7 +76,7 @@ public class LinkDbFilter implements Mapper {String url = key.toString();if (normalize) {try {- url = normalizer.normalize(url); // normalize the url+ url = normalizers.normalize(url, scope); // normalize the url} catch (Exception e) {LOG.warn("Skipping " + url + ":" + e);url = null;@@ -95,7 +99,7 @@ public class LinkDbFilter implements Mapper {fromUrl = inlink.getFromUrl();if (normalize) {try {- fromUrl = normalizer.normalize(fromUrl); // normalize the url+ fromUrl = normalizers.normalize(fromUrl, scope); // normalize the url} catch (Exception e) {LOG.warn("Skipping " + fromUrl + ":" + e);fromUrl = null;diff --git a/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java b/src/java/org/apache/nutch/crawl/PartitionUrlByHost.javaindex 9076a05cb..111263290 100644--- a/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java+++ b/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java@@ -19,15 +19,22 @@ package org.apache.nutch.crawl;import java.net.URL;import java.net.MalformedURLException;+import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;import org.apache.hadoop.io.*;import org.apache.hadoop.mapred.*;+import org.apache.nutch.net.URLNormalizers;/** Partition urls by hostname. */public class PartitionUrlByHost implements Partitioner {+ private static final Log LOG = LogFactory.getLog(PartitionUrlByHost.class);+private int seed;+ private URLNormalizers normalizers;public void configure(JobConf job) {seed = job.getInt("partition.url.by.host.seed", 0);+ normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_PARTITION);}public void close() {}@@ -36,10 +43,16 @@ public class PartitionUrlByHost implements Partitioner {public int getPartition(WritableComparable key, Writable value,int numReduceTasks) {String urlString = ((UTF8)key).toString();+ try {+ urlString = normalizers.normalize(urlString, URLNormalizers.SCOPE_PARTITION);+ } catch (Exception e) {+ LOG.warn("Malformed URL: '" + urlString + "'");+ }URL url = null;try {url = new URL(urlString);} catch (MalformedURLException e) {+ LOG.warn("Malformed URL: '" + urlString + "'");}int hashCode = (url==null ? urlString : url.getHost()).hashCode();diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.javaindex 696c6c72d..61e153e4e 100644--- a/src/java/org/apache/nutch/fetcher/Fetcher.java+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java@@ -83,7 +83,7 @@ public class Fetcher extends ToolBase implements MapRunnable {private URLFilters urlFilters;private ScoringFilters scfilters;private ParseUtil parseUtil;- private UrlNormalizer normalizer;+ private URLNormalizers normalizers;private ProtocolFactory protocolFactory;public FetcherThread(Configuration conf) {@@ -94,7 +94,7 @@ public class Fetcher extends ToolBase implements MapRunnable {this.scfilters = new ScoringFilters(conf);this.parseUtil = new ParseUtil(conf);this.protocolFactory = new ProtocolFactory(conf);- this.normalizer = new UrlNormalizerFactory(conf).getNormalizer();+ this.normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_FETCHER);}public void run() {@@ -155,7 +155,7 @@ public class Fetcher extends ToolBase implements MapRunnable {if (pstatus != null && pstatus.isSuccess() &&pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {String newUrl = pstatus.getMessage();- newUrl = normalizer.normalize(newUrl);+ newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);newUrl = this.urlFilters.filter(newUrl);if (newUrl != null && !newUrl.equals(url.toString())) {url = new UTF8(newUrl);@@ -174,7 +174,7 @@ public class Fetcher extends ToolBase implements MapRunnable {case ProtocolStatus.MOVED: // redirectcase ProtocolStatus.TEMP_MOVED:String newUrl = status.getMessage();- newUrl = normalizer.normalize(newUrl);+ newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);newUrl = this.urlFilters.filter(newUrl);if (newUrl != null && !newUrl.equals(url.toString())) {url = new UTF8(newUrl);diff --git a/src/java/org/apache/nutch/net/RegexUrlNormalizer.java b/src/java/org/apache/nutch/net/RegexUrlNormalizer.javadeleted file mode 100644index 66d1a9353..000000000--- a/src/java/org/apache/nutch/net/RegexUrlNormalizer.java+++ /dev/null@@ -1,184 +0,0 @@-/**- * 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.apache.nutch.net;--import java.net.URL;-import java.net.MalformedURLException;-import java.io.IOException;--import java.util.List;-import java.util.ArrayList;-import java.util.Iterator;--import org.apache.hadoop.conf.Configuration;--import org.apache.nutch.util.NutchConfiguration;--import javax.xml.parsers.*;-import org.w3c.dom.*;-import org.apache.oro.text.regex.*;--/** Allows users to do regex substitutions on all/any URLs that are encountered, which- * is useful for stripping session IDs from URLs.- *- * <p>This class must be specified as the URL normalizer to be used in <tt>nutch-site.xml</tt>- * or <tt>nutch-default.xml</tt>. To do this specify the <tt>urlnormalizer.class</tt> property to- * have the value: <tt>org.apache.nutch.net.RegexUrlNormalizer</tt>. The <tt>urlnormalizer.regex.file</tt>- * property should also be set to the file name of an xml file which should contain the patterns- * and substitutions to be done on encountered URLs.</p>- *- * @author Luke Baker- */-public class RegexUrlNormalizer extends BasicUrlNormalizer- implements UrlNormalizer {-- /** Class which holds a compiled pattern and its corresponding substition string. */- private static class Rule {- public Perl5Pattern pattern;- public String substitution;- }-- private List rules;- private PatternMatcher matcher = new Perl5Matcher();-- /** 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)- throws IOException, MalformedPatternException {- //URL url= Configuration.get().getResource(filename);- rules = readConfigurationFile(filename);- }--- /** This function does the replacements by iterating through all the regex patterns.- * It accepts a string url as input and returns the altered string. */- public synchronized String regexNormalize(String urlString) {- Iterator i=rules.iterator();- while(i.hasNext()) {- Rule r=(Rule) i.next();- urlString = Util.substitute(matcher, r.pattern,- new Perl5Substitution(r.substitution), urlString, Util.SUBSTITUTE_ALL); // actual substitution- }- return urlString;- }-- /** Normalizes any URLs by calling super.basicNormalize()- * and regexSub(). This is the function that gets called- * elsewhere in Nutch. */- public synchronized String normalize(String urlString)- throws MalformedURLException {- urlString = super.normalize(urlString); // run basicNormalize first to ready for regexNormalize- urlString = regexNormalize(urlString);- urlString = super.normalize(urlString); // make sure regexNormalize didn't screw up the URL- return urlString;- }---- /** Reads the configuration file and populates a List of Rules. */- private List readConfigurationFile(String filename)- throws IOException, MalformedPatternException {-- Perl5Compiler compiler=new Perl5Compiler();- List rules=new ArrayList();- try {-- if (LOG.isInfoEnabled()) { LOG.info("loading " + filename); }- // borrowed heavily from code in Configuration.java- Document doc =- DocumentBuilderFactory.newInstance().newDocumentBuilder()- .parse(filename);- Element root = doc.getDocumentElement();- if ((!"regex-normalize".equals(root.getTagName())) &&- (LOG.isFatalEnabled())) {- LOG.fatal("bad conf file: top-level element not <regex-normalize>");- }- NodeList regexes = root.getChildNodes();- for (int i = 0; i < regexes.getLength(); i++) {- Node regexNode = regexes.item(i);- if (!(regexNode instanceof Element))- continue;- Element regex = (Element)regexNode;- if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) {- LOG.warn("bad conf file: element not <regex>");- }- NodeList fields = regex.getChildNodes();- String patternValue = null;- String subValue = null;- for (int j = 0; j < fields.getLength(); j++) {- Node fieldNode = fields.item(j);- if (!(fieldNode instanceof Element))- continue;- Element field = (Element)fieldNode;- if ("pattern".equals(field.getTagName()) && field.hasChildNodes())- patternValue = ((Text)field.getFirstChild()).getData();- if ("substitution".equals(field.getTagName()) && field.hasChildNodes())- subValue = ((Text)field.getFirstChild()).getData();- if (!field.hasChildNodes())- subValue = "";- }- if (patternValue != null && subValue != null) {- Rule rule=new Rule();- rule.pattern=(Perl5Pattern) compiler.compile(patternValue);- rule.substitution=subValue;- rules.add(rule);- }- }-- } catch (Exception e) {- if (LOG.isFatalEnabled()) {- LOG.fatal("error parsing " + filename +" conf file: " + e);- }- }- return rules;- }-- public void setConf(Configuration 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(NutchConfiguration.create());- Iterator i=normalizer.rules.iterator();- while(i.hasNext()) {- Rule r=(Rule) i.next();- System.out.print(r.pattern.getPattern() + " ");- System.out.println(r.substitution);- }- }--}diff --git a/src/java/org/apache/nutch/net/UrlNormalizer.java b/src/java/org/apache/nutch/net/URLNormalizer.javasimilarity index 76%rename from src/java/org/apache/nutch/net/UrlNormalizer.javarename to src/java/org/apache/nutch/net/URLNormalizer.javaindex 344c992c5..8bc796fd2 100644--- a/src/java/org/apache/nutch/net/UrlNormalizer.java+++ b/src/java/org/apache/nutch/net/URLNormalizer.java@@ -20,10 +20,13 @@ import java.net.MalformedURLException;import org.apache.hadoop.conf.Configurable;-/** Interface used to convert URLs to normal form and optionally do regex substitutions */-public interface UrlNormalizer extends Configurable {+/** Interface used to convert URLs to normal form and optionally perform substitutions */+public interface URLNormalizer extends Configurable {++ /* Extension ID */+ public static final String X_POINT_ID = URLNormalizer.class.getName();/* Interface for URL normalization */- public String normalize(String urlString) throws MalformedURLException;+ public String normalize(String urlString, String scope) throws MalformedURLException;}diff --git a/src/java/org/apache/nutch/net/URLNormalizers.java b/src/java/org/apache/nutch/net/URLNormalizers.javanew file mode 100644index 000000000..5c4baa16d--- /dev/null+++ b/src/java/org/apache/nutch/net/URLNormalizers.java@@ -0,0 +1,288 @@+/**+ * Copyright 2006 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.apache.nutch.net;++import java.net.MalformedURLException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Iterator;+import java.util.List;+import java.util.Set;+import java.util.Vector;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.plugin.Extension;+import org.apache.nutch.plugin.ExtensionPoint;+import org.apache.nutch.plugin.PluginRepository;+import org.apache.nutch.plugin.PluginRuntimeException;++/**+ * This class uses a "chained filter" pattern to run defined normalizers.+ * Different lists of normalizers may be defined for different "scopes", or+ * contexts where they are used (note however that they need to be activated+ * first through <tt>plugin.include</tt> property).+ *+ * <p>There is one global scope defined by default, which consists of all+ * active normalizers. The order in which these normalizers+ * are executed may be defined in "urlnormalizer.order" property, which lists+ * space-separated implementation classes (if this property is missing normalizers+ * will be run in random order). If there are more+ * normalizers activated than explicitly named on this list, the remaining ones+ * will be run in random order after the ones specified on the list are executed.</p>+ * <p>You can define a set of contexts (or scopes) in which normalizers may be+ * called. Each scope can have its own list of normalizers (defined in+ * "urlnormalizer.scope.<scope_name>" property) and its own order (defined in+ * "urlnormalizer.order.<scope_name>" property). If any of these properties are+ * missing, default settings are used for the global scope.</p>+ * <p>In case no normalizers are required for any given scope, a+ * {@link org.apache.nutch.net.urlnormalizer.pass.PassURLNormalizer} should be used.</p>+ * <p>Each normalizer may further select among many configurations, depending on+ * the scope in which it is called, because the scope name is passed as a parameter+ * to each normalizer. You can also use the same normalizer for many scopes.</p>+ * <p>Several scopes have been defined, and various Nutch tools will attempt using+ * scope-specific normalizers first (and fall back to default config if scope-specific+ * configuration is missing).</p>+ * <p>Normalizers may be run several times, to ensure that modifications introduced+ * by normalizers at the end of the list can be further reduced by normalizers+ * executed at the beginning. By default this loop is executed just once - if you want+ * to ensure that all possible combinations have been applied you may want to run+ * this loop up to the number of activated normalizers. This loop count can be configured+ * through <tt>urlnormalizer.loop.count</tt> property. As soon as the url is+ * unchanged the loop will stop and return the result.</p>+ *+ * @author Andrzej Bialecki+ */+public final class URLNormalizers {++ /** Default scope. If no scope properties are defined then the configuration for+ * this scope will be used.+ */+ public static final String SCOPE_DEFAULT = "default";+ /** Scope used by {@link org.apache.nutch.crawl.PartitionUrlByHost}. */+ public static final String SCOPE_PARTITION = "partition";+ /** Scope used by {@link org.apache.nutch.crawl.Generator}. */+ public static final String SCOPE_GENERATE_HOST_COUNT = "generate_host_count";+ /** Scope used by {@link org.apache.nutch.fetcher.Fetcher} when processing+ * redirect URLs.+ */+ public static final String SCOPE_FETCHER = "fetcher";+ /** Scope used when updating the CrawlDb with new URLs. */+ public static final String SCOPE_CRAWLDB = "crawldb";+ /** Scope used when updating the LinkDb with new URLs. */+ public static final String SCOPE_LINKDB = "linkdb";+ /** Scope used by {@link org.apache.nutch.crawl.Injector}. */+ public static final String SCOPE_INJECT = "inject";+ /** Scope used when constructing new {@link org.apache.nutch.parse.Outlink} instances. */+ public static final String SCOPE_OUTLINK = "outlink";+++ public static final Log LOG = LogFactory.getLog(URLNormalizers.class);++ /* Empty extension list for caching purposes. */+ private final List EMPTY_EXTENSION_LIST = Collections.EMPTY_LIST;++ private final URLNormalizer[] EMPTY_NORMALIZERS = new URLNormalizer[0];++ private Configuration conf;++ private ExtensionPoint extensionPoint;++ private URLNormalizer[] normalizers;++ private int loopCount;++ public URLNormalizers(Configuration conf, String scope) {+ this.conf = conf;+ this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(+ URLNormalizer.X_POINT_ID);++ if (this.extensionPoint == null) {+ throw new RuntimeException("x point " + URLNormalizer.X_POINT_ID+ + " not found.");+ }++ normalizers = (URLNormalizer[])conf.getObject(URLNormalizer.X_POINT_ID + "_" + scope);+ if (normalizers == null) {+ normalizers = getURLNormalizers(scope);+ }+ if (normalizers == EMPTY_NORMALIZERS) {+ normalizers = (URLNormalizer[])conf.getObject(URLNormalizer.X_POINT_ID + "_" + SCOPE_DEFAULT);+ if (normalizers == null) {+ normalizers = getURLNormalizers(SCOPE_DEFAULT);+ }+ }++ loopCount = conf.getInt("urlnormalizer.loop.count", 1);+ }++ /**+ * Function returns an array of {@link URLNormalizer}s for a given scope,+ * with a specified order.+ *+ * @param scope+ * The scope to return the <code>Array</code> of+ * {@link URLNormalizer}s for.+ * @return An <code>Array</code> of {@link URLNormalizer}s for the given+ * scope.+ * @throws PluginRuntimeException+ */+ URLNormalizer[] getURLNormalizers(String scope) {+ List extensions = getExtensions(scope);++ if (extensions == EMPTY_EXTENSION_LIST) {+ return EMPTY_NORMALIZERS;+ }++ List normalizers = new Vector(extensions.size());++ Iterator it = extensions.iterator();+ while (it.hasNext()) {+ Extension ext = (Extension) it.next();+ URLNormalizer normalizer = null;+ try {+ // check to see if we've cached this URLNormalizer instance yet+ normalizer = (URLNormalizer) this.conf.getObject(ext.getId());+ if (normalizer == null) {+ // go ahead and instantiate it and then cache it+ normalizer = (URLNormalizer) ext.getExtensionInstance();+ this.conf.setObject(ext.getId(), normalizer);+ }+ normalizers.add(normalizer);+ } catch (PluginRuntimeException e) {+ e.printStackTrace();+ LOG.warn("URLNormalizers:PluginRuntimeException when "+ + "initializing url normalizer plugin "+ + ext.getDescriptor().getPluginId()+ + " instance in getURLNormalizers "+ + "function: attempting to continue instantiating plugins");+ }+ }+ return (URLNormalizer[]) normalizers.toArray(new URLNormalizer[normalizers+ .size()]);+ }++ /**+ * Finds the best-suited normalizer plugin for a given scope.+ *+ * @param scope+ * Scope for which we seek a normalizer plugin.+ * @return a list of extensions to be used for this scope. If none, returns+ * empty list.+ * @throws PluginRuntimeException+ */+ private List getExtensions(String scope) {++ List extensions = (List) this.conf.getObject(URLNormalizer.X_POINT_ID + "_x_"+ + scope);++ // Just compare the reference:+ // if this is the empty list, we know we will find no extension.+ if (extensions == EMPTY_EXTENSION_LIST) {+ return EMPTY_EXTENSION_LIST;+ }++ if (extensions == null) {+ extensions = findExtensions(scope);+ if (extensions != null) {+ this.conf.setObject(URLNormalizer.X_POINT_ID + "_x_" + scope, extensions);+ } else {+ // Put the empty extension list into cache+ // to remember we don't know any related extension.+ this.conf.setObject(URLNormalizer.X_POINT_ID + "_x_" + scope, EMPTY_EXTENSION_LIST);+ extensions = EMPTY_EXTENSION_LIST;+ }+ }+ return extensions;+ }++ /**+ * searches a list of suitable url normalizer plugins for the given scope.+ *+ * @param scope+ * Scope for which we seek a url normalizer plugin.+ * @return List - List of extensions to be used for this scope. If none,+ * returns null.+ * @throws PluginRuntimeException+ */+ private List findExtensions(String scope) {++ String[] orders = null;+ String orderlist = conf.get("urlnormalizer.order." + scope);+ if (orderlist == null) orderlist = conf.get("urlnormalizer.order");+ if (orderlist != null && !orderlist.trim().equals("")) {+ orders = orderlist.split("\\s+");+ }+ String scopelist = conf.get("urlnormalizer.scope." + scope);+ Set impls = null;+ if (scopelist != null && !scopelist.trim().equals("")) {+ String[] names = scopelist.split("\\s+");+ impls = new HashSet(Arrays.asList(names));+ }+ Extension[] extensions = this.extensionPoint.getExtensions();+ HashMap normalizerExtensions = new HashMap();+ for (int i = 0; i < extensions.length; i++) {+ Extension extension = extensions[i];+ if (impls != null && !impls.contains(extension.getClazz()))+ continue;+ normalizerExtensions.put(extension.getClazz(), extension);+ }+ List res = new ArrayList();+ if (orders == null) {+ res.addAll(normalizerExtensions.values());+ } else {+ // first add those explicitly named in correct order+ for (int i = 0; i < orders.length; i++) {+ Extension e = (Extension)normalizerExtensions.get(orders[i]);+ if (e != null) {+ res.add(e);+ normalizerExtensions.remove(orders[i]);+ }+ }+ // then add all others in random order+ res.addAll(normalizerExtensions.values());+ }+ return res;+ }++ /**+ * Normalize+ * @param urlString+ * @param scope+ * @return+ * @throws MalformedURLException+ */+ public String normalize(String urlString, String scope)+ throws MalformedURLException {+ // optionally loop several times, and break if no further changes+ String initialString = urlString;+ for (int k = 0; k < loopCount; k++) {+ for (int i = 0; i < this.normalizers.length; i++) {+ if (urlString == null)+ return null;+ urlString = this.normalizers[i].normalize(urlString, scope);+ }+ if (initialString.equals(urlString)) break;+ initialString = urlString;+ }+ return urlString;+ }+}diff --git a/src/java/org/apache/nutch/net/UrlNormalizerFactory.java b/src/java/org/apache/nutch/net/UrlNormalizerFactory.javadeleted file mode 100644index 2e5de54d9..000000000--- a/src/java/org/apache/nutch/net/UrlNormalizerFactory.java+++ /dev/null@@ -1,57 +0,0 @@-/**- * 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.apache.nutch.net;--// Commons Logging imports-import org.apache.commons.logging.Log;-import org.apache.commons.logging.LogFactory;--import org.apache.hadoop.conf.*;---/** Factory to create a UrlNormalizer from "urlnormalizer.class" config property. */-public class UrlNormalizerFactory {- private static final Log LOG = LogFactory.getLog(UrlNormalizerFactory.class);-- private Configuration conf;-- public UrlNormalizerFactory(Configuration conf) {- this.conf = conf;- }-- /** Return the default UrlNormalizer implementation. */- public UrlNormalizer getNormalizer() {- String urlNormalizer = null;- UrlNormalizer normalizer = (UrlNormalizer) this.conf- .getObject(UrlNormalizer.class.getName());- if (normalizer == null) {- try {- urlNormalizer = this.conf.get("urlnormalizer.class");- if (LOG.isInfoEnabled()) {- LOG.info("Using URL normalizer: " + urlNormalizer);- }- Class normalizerClass = Class.forName(urlNormalizer);- normalizer = (UrlNormalizer) normalizerClass.newInstance();- normalizer.setConf(this.conf);- this.conf.setObject(UrlNormalizer.class.getName(), normalizer);- } catch (Exception e) {- throw new RuntimeException("Couldn't create " + urlNormalizer, e);- }- }- return normalizer;- }-}diff --git a/src/java/org/apache/nutch/parse/Outlink.java b/src/java/org/apache/nutch/parse/Outlink.javaindex dbeaabfe8..a4bcddd8a 100644--- a/src/java/org/apache/nutch/parse/Outlink.java+++ b/src/java/org/apache/nutch/parse/Outlink.java@@ -20,7 +20,7 @@ import java.io.*;import java.net.MalformedURLException;import org.apache.hadoop.io.*;-import org.apache.nutch.net.UrlNormalizerFactory;+import org.apache.nutch.net.URLNormalizers;import org.apache.hadoop.conf.Configuration;/* An outgoing link from a page. */@@ -32,7 +32,7 @@ public class Outlink implements Writable {public Outlink() {}public Outlink(String toUrl, String anchor, Configuration conf) throws MalformedURLException {- this.toUrl = new UrlNormalizerFactory(conf).getNormalizer().normalize(toUrl);+ this.toUrl = new URLNormalizers(conf, URLNormalizers.SCOPE_OUTLINK).normalize(toUrl, URLNormalizers.SCOPE_OUTLINK);this.anchor = anchor;}diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.javaindex 0e53d6331..9955ea011 100644--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java@@ -40,7 +40,7 @@ import org.apache.hadoop.util.Progressable;public class ParseOutputFormat implements OutputFormat {private static final Log LOG = LogFactory.getLog(ParseOutputFormat.class);- private UrlNormalizer urlNormalizer;+ private URLNormalizers urlNormalizers;private URLFilters filters;private ScoringFilters scfilters;@@ -52,7 +52,7 @@ public class ParseOutputFormat implements OutputFormat {public RecordWriter getRecordWriter(FileSystem fs, JobConf job,String name, Progressable progress) throws IOException {- this.urlNormalizer = new UrlNormalizerFactory(job).getNormalizer();+ this.urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_OUTLINK);this.filters = new URLFilters(job);this.scfilters = new ScoringFilters(job);final float interval = job.getFloat("db.default.fetch.interval", 30f);@@ -116,7 +116,7 @@ public class ParseOutputFormat implements OutputFormat {for (int i = 0; i < links.length; i++) {String toUrl = links[i].getToUrl();try {- toUrl = urlNormalizer.normalize(toUrl); // normalize the url+ toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_OUTLINK); // normalize the urltoUrl = filters.filter(toUrl); // filter the url} catch (Exception e) {toUrl = null;diff --git a/src/plugin/build.xml b/src/plugin/build.xmlindex 568b65069..79698b28b 100755--- a/src/plugin/build.xml+++ b/src/plugin/build.xml@@ -58,6 +58,9 @@<ant dir="urlfilter-prefix" target="deploy"/><ant dir="urlfilter-regex" target="deploy"/><ant dir="urlfilter-suffix" target="deploy"/>+ <ant dir="urlnormalizer-basic" target="deploy"/>+ <ant dir="urlnormalizer-pass" target="deploy"/>+ <ant dir="urlnormalizer-regex" target="deploy"/></target><!-- ====================================================== -->@@ -85,6 +88,9 @@<ant dir="urlfilter-automaton" target="test"/><ant dir="urlfilter-regex" target="test"/><ant dir="urlfilter-suffix" target="test"/>+ <ant dir="urlnormalizer-basic" target="test"/>+ <ant dir="urlnormalizer-pass" target="test"/>+ <ant dir="urlnormalizer-regex" target="test"/></parallel></target>@@ -141,5 +147,8 @@<ant dir="urlfilter-prefix" target="clean"/><ant dir="urlfilter-regex" target="clean"/><ant dir="urlfilter-suffix" target="clean"/>+ <ant dir="urlnormalizer-basic" target="clean"/>+ <ant dir="urlnormalizer-pass" target="clean"/>+ <ant dir="urlnormalizer-regex" target="clean"/></target></project>diff --git a/src/plugin/nutch-extensionpoints/plugin.xml b/src/plugin/nutch-extensionpoints/plugin.xmlindex 4019b696a..59b0f305e 100644--- a/src/plugin/nutch-extensionpoints/plugin.xml+++ b/src/plugin/nutch-extensionpoints/plugin.xml@@ -41,6 +41,10 @@id="org.apache.nutch.net.URLFilter"name="Nutch URL Filter"/>+<extension-point+ id="org.apache.nutch.net.URLNormalizer"+ name="Nutch URL Normalizer"/>+<extension-pointid="org.apache.nutch.analysis.NutchAnalyzer"name="Nutch Analysis"/>diff --git a/src/plugin/urlnormalizer-basic/build.xml b/src/plugin/urlnormalizer-basic/build.xmlnew file mode 100644index 000000000..421cd13b5--- /dev/null+++ b/src/plugin/urlnormalizer-basic/build.xml@@ -0,0 +1,7 @@+<?xml version="1.0"?>++<project name="urlnormalizer-basic" default="jar-core">++ <import file="../build-plugin.xml"/>++</project>diff --git a/src/plugin/urlnormalizer-basic/plugin.xml b/src/plugin/urlnormalizer-basic/plugin.xmlnew file mode 100644index 000000000..5527f82b0--- /dev/null+++ b/src/plugin/urlnormalizer-basic/plugin.xml@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="UTF-8"?>++<plugin+ id="urlnormalizer-basic"+ name="Basic URL Normalizer"+ version="1.0.0"+ provider-name="nutch.org">++ <runtime>+ <library name="urlnormalizer-basic.jar">+ <export name="*"/>+ </library>+ </runtime>++ <requires>+ <import plugin="nutch-extensionpoints"/>+ </requires>++ <extension id="org.apache.nutch.net.urlnormalizer.basic"+ name="Nutch Basic URL Normalizer"+ point="org.apache.nutch.net.URLNormalizer">+ <implementation id="BasicURLNormalizer"+ class="org.apache.nutch.net.urlnormalizer.basic.BasicURLNormalizer"/>+ </extension>++</plugin>diff --git a/src/java/org/apache/nutch/net/BasicUrlNormalizer.java b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.javasimilarity index 95%rename from src/java/org/apache/nutch/net/BasicUrlNormalizer.javarename to src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.javaindex 33c2d7bb5..47c879175 100644--- a/src/java/org/apache/nutch/net/BasicUrlNormalizer.java+++ b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java@@ -14,7 +14,7 @@* limitations under the License.*/-package org.apache.nutch.net;+package org.apache.nutch.net.urlnormalizer.basic;import java.net.URL;import java.net.MalformedURLException;@@ -24,14 +24,15 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;// Nutch imports+import org.apache.nutch.net.URLNormalizer;import org.apache.nutch.util.LogUtil;import org.apache.hadoop.conf.Configuration;import org.apache.oro.text.regex.*;/** Converts URLs to a normal form . */-public class BasicUrlNormalizer implements UrlNormalizer {- public static final Log LOG = LogFactory.getLog(BasicUrlNormalizer.class);+public class BasicURLNormalizer implements URLNormalizer {+ public static final Log LOG = LogFactory.getLog(BasicURLNormalizer.class);private Perl5Compiler compiler = new Perl5Compiler();private ThreadLocal matchers = new ThreadLocal() {@@ -44,7 +45,7 @@ public class BasicUrlNormalizer implements UrlNormalizer {private Configuration conf;- public BasicUrlNormalizer() {+ public BasicURLNormalizer() {try {// this pattern tries to find spots like "/xx/../" in the url, which// could be replaced by "/" xx consists of chars, different then "/"@@ -68,7 +69,7 @@ public class BasicUrlNormalizer implements UrlNormalizer {}}- public String normalize(String urlString)+ public String normalize(String urlString, String scope)throws MalformedURLException {if ("".equals(urlString)) // permit emptyreturn urlString;diff --git a/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.javasimilarity index 84%rename from src/test/org/apache/nutch/net/TestBasicUrlNormalizer.javarename to src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.javaindex 50477223f..e12c5d951 100644--- a/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java+++ b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java@@ -14,15 +14,25 @@* limitations under the License.*/-package org.apache.nutch.net;+package org.apache.nutch.net.urlnormalizer.basic;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.net.URLNormalizers;import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;-/** Unit tests for BasicUrlNormalizer. */-public class TestBasicUrlNormalizer extends TestCase {- public TestBasicUrlNormalizer(String name) { super(name); }+/** Unit tests for BasicURLNormalizer. */+public class TestBasicURLNormalizer extends TestCase {+ private BasicURLNormalizer normalizer;+ private Configuration conf;++ public TestBasicURLNormalizer(String name) {+ super(name);+ normalizer = new BasicURLNormalizer();+ conf = NutchConfiguration.create();+ normalizer.setConf(conf);+ }public void testNormalizer() throws Exception {// check that leading and trailing spaces are removed@@ -82,11 +92,11 @@ public class TestBasicUrlNormalizer extends TestCase {}private void normalizeTest(String weird, String normal) throws Exception {- assertEquals(normal, new UrlNormalizerFactory(NutchConfiguration.create()).getNormalizer().normalize(weird));+ assertEquals(normal, normalizer.normalize(weird, URLNormalizers.SCOPE_DEFAULT));}public static void main(String[] args) throws Exception {- new TestBasicUrlNormalizer("test").testNormalizer();+ new TestBasicURLNormalizer("test").testNormalizer();}diff --git a/src/plugin/urlnormalizer-pass/build.xml b/src/plugin/urlnormalizer-pass/build.xmlnew file mode 100644index 000000000..b167be8ee--- /dev/null+++ b/src/plugin/urlnormalizer-pass/build.xml@@ -0,0 +1,7 @@+<?xml version="1.0"?>++<project name="urlnormalizer-pass" default="jar-core">++ <import file="../build-plugin.xml"/>++</project>diff --git a/src/plugin/urlnormalizer-pass/plugin.xml b/src/plugin/urlnormalizer-pass/plugin.xmlnew file mode 100644index 000000000..19cc48fd9--- /dev/null+++ b/src/plugin/urlnormalizer-pass/plugin.xml@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="UTF-8"?>++<plugin+ id="urlnormalizer-pass"+ name="Pass-through URL Normalizer"+ version="1.0.0"+ provider-name="nutch.org">++ <runtime>+ <library name="urlnormalizer-pass.jar">+ <export name="*"/>+ </library>+ </runtime>++ <requires>+ <import plugin="nutch-extensionpoints"/>+ </requires>++ <extension id="org.apache.nutch.net.urlnormalizer.pass"+ name="Nutch Pass-through URL Normalizer"+ point="org.apache.nutch.net.URLNormalizer">+ <implementation id="PassURLNormalizer"+ class="org.apache.nutch.net.urlnormalizer.pass.PassURLNormalizer"/>+ </extension>++</plugin>diff --git a/src/plugin/urlnormalizer-pass/src/java/org/apache/nutch/net/urlnormalizer/pass/PassURLNormalizer.java b/src/plugin/urlnormalizer-pass/src/java/org/apache/nutch/net/urlnormalizer/pass/PassURLNormalizer.javanew file mode 100644index 000000000..192802ccf--- /dev/null+++ b/src/plugin/urlnormalizer-pass/src/java/org/apache/nutch/net/urlnormalizer/pass/PassURLNormalizer.java@@ -0,0 +1,46 @@+/**+ * Copyright 2006 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.apache.nutch.net.urlnormalizer.pass;++import java.net.MalformedURLException;++import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.net.URLNormalizer;++/**+ * This URLNormalizer doesn't change urls. It is sometimes useful if for a given+ * scope at least one normalizer must be defined but no transformations are required.+ *+ * @author Andrzej Bialecki+ */+public class PassURLNormalizer implements URLNormalizer {++ private Configuration conf;++ public String normalize(String urlString, String scope) throws MalformedURLException {+ return urlString;+ }++ public Configuration getConf() {+ return conf;+ }++ public void setConf(Configuration conf) {+ this.conf = conf;+ }++}diff --git a/src/test/org/apache/nutch/net/TestUrlNormalizerFactory.java b/src/plugin/urlnormalizer-pass/src/test/org/apache/nutch/net/urlnormalizer/pass/TestPassURLNormalizer.javasimilarity index 54%rename from src/test/org/apache/nutch/net/TestUrlNormalizerFactory.javarename to src/plugin/urlnormalizer-pass/src/test/org/apache/nutch/net/urlnormalizer/pass/TestPassURLNormalizer.javaindex 606036d67..fb54c5516 100644--- a/src/test/org/apache/nutch/net/TestUrlNormalizerFactory.java+++ b/src/plugin/urlnormalizer-pass/src/test/org/apache/nutch/net/urlnormalizer/pass/TestPassURLNormalizer.java@@ -13,23 +13,32 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.net;+package org.apache.nutch.net.urlnormalizer.pass;+++import java.net.MalformedURLException;import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.net.URLNormalizers;import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;-public class TestUrlNormalizerFactory extends TestCase {+public class TestPassURLNormalizer extends TestCase {- public void testGetNormalizer() {- Configuration conf=NutchConfiguration.create();+ public void testPassURLNormalizer() {+ Configuration conf = NutchConfiguration.create();- UrlNormalizerFactory factory=new UrlNormalizerFactory(conf);+ PassURLNormalizer normalizer = new PassURLNormalizer();+ normalizer.setConf(conf);+ String url = "http://www.example.com/test/..//";+ String result = null;+ try {+ result = normalizer.normalize(url, URLNormalizers.SCOPE_DEFAULT);+ } catch (MalformedURLException mue) {+ fail(mue.toString());+ }- UrlNormalizer normalizer1=factory.getNormalizer();- UrlNormalizer normalizer2=factory.getNormalizer();- assertNotNull(normalizer1);- assertEquals(normalizer1, normalizer2);+ assertEquals(url, result);}}diff --git a/src/plugin/urlnormalizer-regex/build.xml b/src/plugin/urlnormalizer-regex/build.xmlnew file mode 100644index 000000000..8dec085e5--- /dev/null+++ b/src/plugin/urlnormalizer-regex/build.xml@@ -0,0 +1,19 @@+<?xml version="1.0"?>++<project name="urlnormalizer-regex" default="jar-core">++ <import file="../build-plugin.xml"/>++ <!-- Deploy Unit test dependencies -->+ <target name="deps-test">+ <ant target="deploy" inheritall="false" dir="../nutch-extensionpoints"/>+ </target>++ <!-- for junit test -->+ <mkdir dir="${build.test}/data"/>+ <copy todir="${build.test}/data">+ <fileset dir="sample" includes="**/*.xml, **/*.test"/>+ </copy>+++</project>diff --git a/src/plugin/urlnormalizer-regex/plugin.xml b/src/plugin/urlnormalizer-regex/plugin.xmlnew file mode 100644index 000000000..4c3f0c3b9--- /dev/null+++ b/src/plugin/urlnormalizer-regex/plugin.xml@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="UTF-8"?>++<plugin+ id="urlnormalizer-regex"+ name="Regex URL Normalizer"+ version="1.0.0"+ provider-name="nutch.org">++ <runtime>+ <library name="urlnormalizer-regex.jar">+ <export name="*"/>+ </library>+ </runtime>++ <requires>+ <import plugin="nutch-extensionpoints"/>+ </requires>++ <extension id="org.apache.nutch.net.urlnormalizer.regex"+ name="Nutch Regex URL Normalizer"+ point="org.apache.nutch.net.URLNormalizer">+ <implementation id="RegexURLNormalizer"+ class="org.apache.nutch.net.urlnormalizer.regex.RegexURLNormalizer"/>+ </extension>++</plugin>diff --git a/src/plugin/urlnormalizer-regex/sample/regex-normalize-default.test b/src/plugin/urlnormalizer-regex/sample/regex-normalize-default.testnew file mode 100644index 000000000..34fceda4b--- /dev/null+++ b/src/plugin/urlnormalizer-regex/sample/regex-normalize-default.test@@ -0,0 +1,11 @@+# test simple removal of session id+http://foo.com/foo.php?PHPSESSID=cdc993a493e899bed04f4d0c8a462a03 http://foo.com/foo.php++# test removal of session id, and keep parameters before+http://foo.com/foo.php?f=2&PHPSESSID=cdc993a493e899bed04f4d0c8a462a03 http://foo.com/foo.php?f=2++# test removal of session id, and keep parameters after+http://foo.com/foo.php?f=2&PHPSESSID=cdc993a493e899bed04f4d0c8a462a03&q=3 http://foo.com/foo.php?f=2&q=3++# test removal of session id, and keep parameters after+http://foo.com/foo.php?PHPSESSID=cdc993a493e899bed04f4d0c8a462a03&f=2 http://foo.com/foo.php?f=2diff --git a/src/test/org/apache/nutch/net/test-regex-normalize.xml b/src/plugin/urlnormalizer-regex/sample/regex-normalize-default.xmlsimilarity index 99%rename from src/test/org/apache/nutch/net/test-regex-normalize.xmlrename to src/plugin/urlnormalizer-regex/sample/regex-normalize-default.xmlindex 56a4e78c7..40e802ff6 100644--- a/src/test/org/apache/nutch/net/test-regex-normalize.xml+++ b/src/plugin/urlnormalizer-regex/sample/regex-normalize-default.xml@@ -20,3 +20,4 @@<substitution>$1$3</substitution></regex></regex-normalize>+diff --git a/src/plugin/urlnormalizer-regex/sample/regex-normalize-scope1.test b/src/plugin/urlnormalizer-regex/sample/regex-normalize-scope1.testnew file mode 100644index 000000000..9d928802e--- /dev/null+++ b/src/plugin/urlnormalizer-regex/sample/regex-normalize-scope1.test@@ -0,0 +1,8 @@+# test removal of subdomains+http://www.foo.bar.com/ http://bar.com/++# test removal of url path+http://www.foo.bar.com/foo.php?PHPSESSID=cdc993a493e899bed04f4d0c8a462a03 http://bar.com/++# test removal of urls in arguments+https://www.foo.bar.com/foo.php?url=http://www.example.com/test.php https://bar.com/diff --git a/src/plugin/urlnormalizer-regex/sample/regex-normalize-scope1.xml b/src/plugin/urlnormalizer-regex/sample/regex-normalize-scope1.xmlnew file mode 100644index 000000000..369896878--- /dev/null+++ b/src/plugin/urlnormalizer-regex/sample/regex-normalize-scope1.xml@@ -0,0 +1,21 @@+<?xml version="1.0"?>+<!-- This is the configuration file for the RegexUrlNormalize Class.+ This is intended so that users can specify substitutions to be+ done on URLs. The regex engine that is used is Perl5 compatible.+ The rules are applied to URLs in the order they occur in this file. -->++<!-- WATCH OUT: an xml parser reads this file an ampersands must be+ expanded to & -->++<!--+ The following rules show how to reduce urls so that+ urls from the same domain are identical. This is useful+ e.g. when calculating host counts, or splitting fetchlists.+-->+<regex-normalize>+<regex>+ <pattern>(^[a-z]{3,5}://)([\w]+\.)*?(\w+\.\w+)[/$].*</pattern>+ <substitution>$1$3/</substitution>+</regex>+</regex-normalize>+diff --git a/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.javanew file mode 100644index 000000000..f85b2c5a9--- /dev/null+++ b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java@@ -0,0 +1,292 @@+/**+ * 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.apache.nutch.net.urlnormalizer.regex;++import java.net.URL;+import java.net.MalformedURLException;+import java.io.FileInputStream;+import java.io.IOException;+import java.io.InputStream;++import java.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.ArrayList;+import java.util.Iterator;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configured;++import org.apache.nutch.net.URLNormalizer;+import org.apache.nutch.net.URLNormalizers;+import org.apache.nutch.util.NutchConfiguration;++import javax.xml.parsers.*;+import org.w3c.dom.*;+import org.apache.oro.text.regex.*;++/**+ * Allows users to do regex substitutions on all/any URLs that are encountered,+ * which is useful for stripping session IDs from URLs.+ *+ * <p>This class uses the <tt>urlnormalizer.regex.file</tt> property.+ * It should be set to the file name of an xml file which should contain the+ * patterns and substitutions to be done on encountered URLs.+ * </p>+ * <p>This class also supports different rules depending on the scope. Please see+ * the javadoc in {@link org.apache.nutch.net.URLNormalizers} for more details.</p>+ *+ * @author Luke Baker+ * @author Andrzej Bialecki+ */+public class RegexURLNormalizer extends Configured implements URLNormalizer {++ private static final Log LOG = LogFactory.getLog(RegexURLNormalizer.class);++ /**+ * Class which holds a compiled pattern and its corresponding substition+ * string.+ */+ private static class Rule {+ public Perl5Pattern pattern;++ public String substitution;+ }++ private HashMap scopedRules;++ private static final List EMPTY_RULES = Collections.EMPTY_LIST;++ private PatternMatcher matcher = new Perl5Matcher();++ /**+ * The default constructor which is called from UrlNormalizerFactory+ * (normalizerClass.newInstance()) in method: getNormalizer()*+ */+ public RegexURLNormalizer() {+ super(null);+ }++ public RegexURLNormalizer(Configuration conf) {+ super(conf);+ }++ /**+ * Constructor which can be passed the file name, so it doesn't look in the+ * configuration files for it.+ */+ public RegexURLNormalizer(Configuration conf, String filename)+ throws IOException, MalformedPatternException {+ super(conf);+ List rules = readConfigurationFile(filename);+ if (rules != null)+ scopedRules.put(URLNormalizers.SCOPE_DEFAULT, rules);+ }++ public void setConf(Configuration conf) {+ super.setConf(conf);+ if (conf == null) return;+ // the default constructor was called+ if (this.scopedRules == null) {+ String filename = getConf().get("urlnormalizer.regex.file");+ scopedRules = new HashMap();+ URL url = getConf().getResource(filename);+ List rules = null;+ if (url == null) {+ LOG.warn("Can't load the default config file! " + filename);+ rules = EMPTY_RULES;+ } else {+ try {+ rules = readConfiguration(url.openStream());+ } catch (Exception e) {+ LOG.warn("Couldn't read default config from '" + url + "': " + e);+ rules = EMPTY_RULES;+ }+ }+ scopedRules.put(URLNormalizers.SCOPE_DEFAULT, rules);+ }+ }++ // used in JUnit test.+ void setConfiguration(InputStream is, String scope) {+ List rules = readConfiguration(is);+ scopedRules.put(scope, rules);+ LOG.debug("Set config for scope '" + scope + "': " + rules.size() + " rules.");+ }++ /**+ * This function does the replacements by iterating through all the regex+ * patterns. It accepts a string url as input and returns the altered string.+ */+ public synchronized String regexNormalize(String urlString, String scope) {+ List curRules = (List)scopedRules.get(scope);+ if (curRules == null) {+ // try to populate+ String configFile = getConf().get("urlnormalizer.regex.file." + scope);+ if (configFile != null) {+ URL resource = getConf().getResource(configFile);+ LOG.debug("resource for scope '" + scope + "': " + resource);+ if (resource == null) {+ LOG.warn("Can't load resource for config file: " + configFile);+ } else {+ try {+ InputStream is = resource.openStream();+ curRules = readConfiguration(resource.openStream());+ scopedRules.put(scope, curRules);+ } catch (Exception e) {+ LOG.warn("Couldn't load resource '" + resource + "': " + e);+ }+ }+ } else {+ LOG.warn("can't load rule file for scope '" + scope + "': " + configFile);+ }+ if (curRules == EMPTY_RULES || curRules == null) {+ LOG.warn("can't find rules for scope '" + scope + "', using default");+ }+ }+ if (curRules == EMPTY_RULES || curRules == null) {+ // use global rules+ curRules = (List)scopedRules.get(URLNormalizers.SCOPE_DEFAULT);+ }+ Iterator i = curRules.iterator();+ while (i.hasNext()) {+ Rule r = (Rule) i.next();+ urlString = Util.substitute(matcher, r.pattern, new Perl5Substitution(+ r.substitution), urlString, Util.SUBSTITUTE_ALL); // actual+ // substitution+ }+ return urlString;+ }++ public synchronized String normalize(String urlString, String scope)+ throws MalformedURLException {+ return regexNormalize(urlString, scope);+ }++ /** Reads the configuration file and populates a List of Rules. */+ private List readConfigurationFile(String filename) {+ if (LOG.isInfoEnabled()) {+ LOG.info("loading " + filename);+ }+ try {+ FileInputStream fis = new FileInputStream(filename);+ return readConfiguration(fis);+ } catch (Exception e) {+ LOG.fatal("Error loading rules from '" + filename + "': " + e);+ return EMPTY_RULES;+ }+ }++ private List readConfiguration(InputStream is) {+ Perl5Compiler compiler = new Perl5Compiler();+ List rules = new ArrayList();+ try {++ // borrowed heavily from code in Configuration.java+ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()+ .parse(is);+ Element root = doc.getDocumentElement();+ if ((!"regex-normalize".equals(root.getTagName()))+ && (LOG.isFatalEnabled())) {+ LOG.fatal("bad conf file: top-level element not <regex-normalize>");+ }+ NodeList regexes = root.getChildNodes();+ for (int i = 0; i < regexes.getLength(); i++) {+ Node regexNode = regexes.item(i);+ if (!(regexNode instanceof Element))+ continue;+ Element regex = (Element) regexNode;+ if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) {+ LOG.warn("bad conf file: element not <regex>");+ }+ NodeList fields = regex.getChildNodes();+ String patternValue = null;+ String subValue = null;+ for (int j = 0; j < fields.getLength(); j++) {+ Node fieldNode = fields.item(j);+ if (!(fieldNode instanceof Element))+ continue;+ Element field = (Element) fieldNode;+ if ("pattern".equals(field.getTagName()) && field.hasChildNodes())+ patternValue = ((Text) field.getFirstChild()).getData();+ if ("substitution".equals(field.getTagName())+ && field.hasChildNodes())+ subValue = ((Text) field.getFirstChild()).getData();+ if (!field.hasChildNodes())+ subValue = "";+ }+ if (patternValue != null && subValue != null) {+ Rule rule = new Rule();+ rule.pattern = (Perl5Pattern) compiler.compile(patternValue);+ rule.substitution = subValue;+ rules.add(rule);+ }+ }+ } catch (Exception e) {+ if (LOG.isFatalEnabled()) {+ LOG.fatal("error parsing conf file: " + e);+ }+ return EMPTY_RULES;+ }+ if (rules.size() == 0) return EMPTY_RULES;+ return rules;+ }++ /** 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(NutchConfiguration.create());+ Iterator i = ((List)normalizer.scopedRules.get(URLNormalizers.SCOPE_DEFAULT)).iterator();+ System.out.println("* Rules for 'DEFAULT' scope:");+ while (i.hasNext()) {+ Rule r = (Rule) i.next();+ System.out.print(" " + r.pattern.getPattern() + " -> ");+ System.out.println(r.substitution);+ }+ // load the scope+ if (args.length > 1) {+ normalizer.normalize("http://test.com", args[1]);+ }+ if (normalizer.scopedRules.size() > 1) {+ Iterator it = normalizer.scopedRules.keySet().iterator();+ while (it.hasNext()) {+ String scope = (String)it.next();+ if (URLNormalizers.SCOPE_DEFAULT.equals(scope)) continue;+ System.out.println("* Rules for '" + scope + "' scope:");+ i = ((List)normalizer.scopedRules.get(scope)).iterator();+ while (i.hasNext()) {+ Rule r = (Rule) i.next();+ System.out.print(" " + r.pattern.getPattern() + " -> ");+ System.out.println(r.substitution);+ }+ }+ }+ if (args.length > 0) {+ System.out.println("\n---------- Normalizer test -----------");+ String scope = URLNormalizers.SCOPE_DEFAULT;+ if (args.length > 1) scope = args[1];+ System.out.println("Scope: " + scope);+ System.out.println("Input url: '" + args[0] + "'");+ System.out.println("Output url: '" + normalizer.normalize(args[0], scope) + "'");+ }+ System.exit(0);+ }++}diff --git a/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java b/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.javanew file mode 100644index 000000000..cf9a8e8aa--- /dev/null+++ b/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java@@ -0,0 +1,176 @@+/**+ * Copyright 2006 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.apache.nutch.net.urlnormalizer.regex;++import java.io.BufferedReader;+import java.io.File;+import java.io.FileFilter;+import java.io.FileInputStream;+import java.io.IOException;+import java.io.InputStreamReader;+import java.io.Reader;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.Iterator;+import java.util.List;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.net.URLNormalizers;+import org.apache.nutch.util.NutchConfiguration;++import junit.framework.TestCase;++/** Unit tests for RegexUrlNormalizer. */+public class TestRegexURLNormalizer extends TestCase {+ private static final Log LOG = LogFactory.getLog(TestRegexURLNormalizer.class);++ private RegexURLNormalizer normalizer;+ private Configuration conf;+ private HashMap testData = new HashMap();++ // This system property is defined in ./src/plugin/build-plugin.xml+ private String sampleDir = System.getProperty("test.data", ".");+ // Make sure sample files are copied to "test.data" as specified in+ // ./src/plugin/urlnormalizer-regex/build.xml during plugin compilation.++ public TestRegexURLNormalizer(String name) throws IOException {+ super(name);+ normalizer = new RegexURLNormalizer();+ conf = NutchConfiguration.create();+ normalizer.setConf(conf);+ File[] configs = new File(sampleDir).listFiles(new FileFilter() {+ public boolean accept(File f) {+ if (f.getName().endsWith(".xml") && f.getName().startsWith("regex-normalize-"))+ return true;+ return false;+ }+ });+ for (int i = 0; i < configs.length; i++) {+ try {+ FileInputStream fis = new FileInputStream(configs[i]);+ String cname = configs[i].getName();+ cname = cname.substring(16, cname.indexOf(".xml"));+ normalizer.setConfiguration(fis, cname);+ NormalizedURL[] urls = readTestFile(cname);+ testData.put(cname, urls);+ } catch (Exception e) {+ LOG.warn("Could load config from '" + configs[i] + "': " + e.toString());+ }+ }+ }++ public void testNormalizerDefault() throws Exception {+ normalizeTest((NormalizedURL[])testData.get(URLNormalizers.SCOPE_DEFAULT),+ URLNormalizers.SCOPE_DEFAULT);+ }++ public void testNormalizerScope() throws Exception {+ Iterator it = testData.keySet().iterator();+ while (it.hasNext()) {+ String scope = (String)it.next();+ normalizeTest((NormalizedURL[])testData.get(scope), scope);+ }+ }++ private void normalizeTest(NormalizedURL[] urls, String scope) throws Exception {+ for (int i = 0; i < urls.length; i++) {+ assertEquals(urls[i].expectedURL,+ normalizer.normalize(urls[i].url, scope));+ }+ }++ private void bench(int loops, String scope) {+ long start = System.currentTimeMillis();+ try {+ NormalizedURL[] expected = (NormalizedURL[])testData.get(scope);+ if (expected == null) return;+ for (int i = 0; i < loops; i++) {+ normalizeTest(expected, scope);+ }+ } catch (Exception e) {+ fail(e.toString());+ }+ LOG.info("bench time (" + loops + ") " ++ (System.currentTimeMillis() - start) + "ms");+ }++ private static class NormalizedURL {+ String url;+ String expectedURL;++ public NormalizedURL(String line) {+ String[] fields = line.split("\\s+");+ url = fields[0];+ expectedURL = fields[1];+ }+ }++ private NormalizedURL[] readTestFile(String scope) throws IOException {+ File f = new File(sampleDir, "regex-normalize-" + scope + ".test");+ BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));+ List list = new ArrayList();+ String line;+ while((line = in.readLine()) != null) {+ if ( line.trim().length() == 0 ||+ line.startsWith("#") ||+ line.startsWith(" ")) continue;+ list.add(new NormalizedURL(line));+ }+ return (NormalizedURL[]) list.toArray(new NormalizedURL[list.size()]);+ }++ public static void main(String[] args) throws Exception {+ if (args.length == 0) {+ System.err.println("TestRegexURLNormalizer [-bench <iter>] <scope>");+ System.exit(-1);+ }+ boolean bench = false;+ int iter = -1;+ String scope = null;+ for (int i = 0; i < args.length; i++) {+ if (args[i].equals("-bench")) {+ bench = true;+ iter = Integer.parseInt(args[++i]);+ } else scope = args[i];+ }+ if (scope == null) {+ System.err.println("Missing required scope name.");+ System.exit(-1);+ }+ if (bench && iter < 0) {+ System.err.println("Invalid number of iterations: " + iter);+ System.exit(-1);+ }+ TestRegexURLNormalizer test = new TestRegexURLNormalizer("test");+ NormalizedURL[] urls = (NormalizedURL[])test.testData.get(scope);+ if (urls == null) {+ LOG.warn("Missing test data for scope '" + scope + "', using default scope.");+ scope = URLNormalizers.SCOPE_DEFAULT;+ urls = (NormalizedURL[])test.testData.get(scope);+ }+ if (bench) {+ test.bench(iter, scope);+ } else {+ test.normalizeTest(urls, scope);+ }+ }++++}diff --git a/src/test/org/apache/nutch/crawl/TestInjector.java b/src/test/org/apache/nutch/crawl/TestInjector.javaindex a07a04281..ec9e40250 100644--- a/src/test/org/apache/nutch/crawl/TestInjector.java+++ b/src/test/org/apache/nutch/crawl/TestInjector.java@@ -51,7 +51,8 @@ public class TestInjector extends TestCase {urlPath=new Path(testdir,"urls");crawldbPath=new Path(testdir,"crawldb");fs=FileSystem.get(conf);-+ if (fs.exists(urlPath)) fs.delete(urlPath);+ if (fs.exists(crawldbPath)) fs.delete(crawldbPath);}protected void tearDown() throws IOException{diff --git a/src/test/org/apache/nutch/net/TestRegexUrlNormalizer.java b/src/test/org/apache/nutch/net/TestRegexUrlNormalizer.javadeleted file mode 100644index 3d345ece4..000000000--- a/src/test/org/apache/nutch/net/TestRegexUrlNormalizer.java+++ /dev/null@@ -1,50 +0,0 @@-/**- * 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.apache.nutch.net;--import org.apache.nutch.net.RegexUrlNormalizer;--/** Unit tests for RegexUrlNormalizer. */-public class TestRegexUrlNormalizer extends TestBasicUrlNormalizer {- public TestRegexUrlNormalizer(String name) { super(name); }-- public void testNormalizer() throws Exception {- normalizeTest("http://foo.com/foo.php?f=2&PHPSESSID=cdc993a493e899bed04f4d0c8a462a03",- "http://foo.com/foo.php?f=2");- normalizeTest("http://foo.com/foo.php?f=2&PHPSESSID=cdc993a493e899bed04f4d0c8a462a03&q=3",- "http://foo.com/foo.php?f=2&q=3");- normalizeTest("http://foo.com/foo.php?PHPSESSID=cdc993a493e899bed04f4d0c8a462a03&f=2",- "http://foo.com/foo.php?f=2");- normalizeTest("http://foo.com/foo.php?PHPSESSID=cdc993a493e899bed04f4d0c8a462a03",- "http://foo.com/foo.php");- }-- private void normalizeTest(String weird, String normal) throws Exception {- String testSrcDir = System.getProperty("test.src.dir");- String path = testSrcDir + "/org/apache/nutch/net/test-regex-normalize.xml";- RegexUrlNormalizer normalizer = new RegexUrlNormalizer(path);- assertEquals(normal, normalizer.normalize(weird));- }-- public static void main(String[] args) throws Exception {- new TestRegexUrlNormalizer("test").testNormalizer();- new TestBasicUrlNormalizer("test").testNormalizer(); // need to make sure it passes this test too- }----}diff --git a/src/test/org/apache/nutch/net/TestURLNormalizers.java b/src/test/org/apache/nutch/net/TestURLNormalizers.javanew file mode 100644index 000000000..5863dd00c--- /dev/null+++ b/src/test/org/apache/nutch/net/TestURLNormalizers.java@@ -0,0 +1,52 @@+/*+ * Copyright 2006 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.apache.nutch.net;++import java.net.MalformedURLException;++import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;++import junit.framework.TestCase;++public class TestURLNormalizers extends TestCase {++ public void testURLNormalizers() {+ Configuration conf = NutchConfiguration.create();+ String clazz1 = "org.apache.nutch.net.urlnormalizer.regex.RegexURLNormalizer";+ String clazz2 = "org.apache.nutch.net.urlnormalizer.basic.BasicURLNormalizer";+ conf.set("urlnormalizer.order", clazz1 + " " + clazz2);++ URLNormalizers normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);++ assertNotNull(normalizers);+ try {+ normalizers.normalize("http://www.example.com/", URLNormalizers.SCOPE_DEFAULT);+ } catch (MalformedURLException mue) {+ fail(mue.toString());+ }+ // check the order+ int pos1 = -1, pos2 = -1;+ URLNormalizer[] impls = normalizers.getURLNormalizers(URLNormalizers.SCOPE_DEFAULT);+ for (int i = 0; i < impls.length; i++) {+ if (impls[i].getClass().getName().equals(clazz1)) pos1 = i;+ if (impls[i].getClass().getName().equals(clazz2)) pos2 = i;+ }+ if (pos1 != -1 && pos2 != -1) {+ assertTrue("RegexURLNormalizer before BasicURLNormalizer", pos1 < pos2);+ }+ }+}