Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

UTCH-865 Format source code in unique style

Lewis John McGibbneybbbf310573d0
diff --git a/CHANGES.txt b/CHANGES.txt
index 26c5cf833..12643fb7f 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -2,6 +2,8 @@ Nutch Change Log
Nutch Current Development 1.10-SNAPSHOT
+* NUTCH-865 Format source code in unique style (lewismc)
+
* NUTCH-1893 Parse-tika failes to parse feed files (Mengying Wang via snagel)
* NUTCH-1920 Upgrade Nutch to use Java 1.7 (lewismc)
diff --git a/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java b/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
index 93e0f34b1..c259419b1 100755
--- a/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
@@ -30,38 +30,43 @@ import org.apache.nutch.crawl.CrawlDatum;
*
* @author Andrzej Bialecki
*/
-public abstract class AbstractFetchSchedule extends Configured implements FetchSchedule {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractFetchSchedule.class);
-
+public abstract class AbstractFetchSchedule extends Configured implements
+ FetchSchedule {
+ private static final Logger LOG = LoggerFactory
+ .getLogger(AbstractFetchSchedule.class);
+
protected int defaultInterval;
protected int maxInterval;
-
+
public AbstractFetchSchedule() {
super(null);
}
-
+
public AbstractFetchSchedule(Configuration conf) {
super(conf);
}
-
+
public void setConf(Configuration conf) {
super.setConf(conf);
- if (conf == null) return;
+ if (conf == null)
+ return;
defaultInterval = conf.getInt("db.fetch.interval.default", 0);
- maxInterval = conf.getInt("db.fetch.interval.max", 0 );
+ maxInterval = conf.getInt("db.fetch.interval.max", 0);
LOG.info("defaultInterval=" + defaultInterval);
LOG.info("maxInterval=" + maxInterval);
}
-
+
/**
- * Initialize fetch schedule related data. Implementations should at least
- * set the <code>fetchTime</code> and <code>fetchInterval</code>. The default
- * implementation sets the <code>fetchTime</code> to now, using the
- * default <code>fetchInterval</code>.
- *
- * @param url URL of the page.
- *
- * @param datum datum instance to be initialized (modified in place).
+ * Initialize fetch schedule related data. Implementations should at least set
+ * the <code>fetchTime</code> and <code>fetchInterval</code>. The default
+ * implementation sets the <code>fetchTime</code> to now, using the default
+ * <code>fetchInterval</code>.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * datum instance to be initialized (modified in place).
*/
public CrawlDatum initializeSchedule(Text url, CrawlDatum datum) {
datum.setFetchTime(System.currentTimeMillis());
@@ -69,101 +74,111 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
datum.setRetriesSinceFetch(0);
return datum;
}
-
+
/**
* Sets the <code>fetchInterval</code> and <code>fetchTime</code> on a
- * successfully fetched page. NOTE: this implementation resets the
- * retry counter - extending classes should call super.setFetchSchedule() to
+ * successfully fetched page. NOTE: this implementation resets the retry
+ * counter - extending classes should call super.setFetchSchedule() to
* preserve this behavior.
*/
public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime,
- long fetchTime, long modifiedTime, int state) {
+ long prevFetchTime, long prevModifiedTime, long fetchTime,
+ long modifiedTime, int state) {
datum.setRetriesSinceFetch(0);
return datum;
}
-
+
/**
- * This method specifies how to schedule refetching of pages
- * marked as GONE. Default implementation increases fetchInterval by 50%
- * but the value may never exceed <code>maxInterval</code>.
- *
- * @param url URL of the page.
- *
- * @param datum datum instance to be adjusted.
- *
+ * This method specifies how to schedule refetching of pages marked as GONE.
+ * Default implementation increases fetchInterval by 50% but the value may
+ * never exceed <code>maxInterval</code>.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * datum instance to be adjusted.
+ *
* @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than @see CrawlDatum, but
- * implementations should make sure that it contains at least all
- * information from @see CrawlDatum.
+ * NOTE: this may be a different instance than @see CrawlDatum, but
+ * implementations should make sure that it contains at least all
+ * information from @see CrawlDatum.
*/
public CrawlDatum setPageGoneSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime, long fetchTime) {
+ long prevFetchTime, long prevModifiedTime, long fetchTime) {
// no page is truly GONE ... just increase the interval by 50%
// and try much later.
if ((datum.getFetchInterval() * 1.5f) < maxInterval)
datum.setFetchInterval(datum.getFetchInterval() * 1.5f);
else
datum.setFetchInterval(maxInterval * 0.9f);
- datum.setFetchTime(fetchTime + (long)datum.getFetchInterval() * 1000);
+ datum.setFetchTime(fetchTime + (long) datum.getFetchInterval() * 1000);
return datum;
}
-
+
/**
- * This method adjusts the fetch schedule if fetching needs to be
- * re-tried due to transient errors. The default implementation
- * sets the next fetch time 1 day in the future and increases
- * the retry counter.
- *
- * @param url URL of the page.
- *
- * @param datum page information.
- *
- * @param prevFetchTime previous fetch time.
- *
- * @param prevModifiedTime previous modified time.
- *
- * @param fetchTime current fetch time.
- *
+ * This method adjusts the fetch schedule if fetching needs to be re-tried due
+ * to transient errors. The default implementation sets the next fetch time 1
+ * day in the future and increases the retry counter.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * page information.
+ *
+ * @param prevFetchTime
+ * previous fetch time.
+ *
+ * @param prevModifiedTime
+ * previous modified time.
+ *
+ * @param fetchTime
+ * current fetch time.
+ *
* @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than @see CrawlDatum, but
- * implementations should make sure that it contains at least all
- * information from @see CrawlDatum.
+ * NOTE: this may be a different instance than @see CrawlDatum, but
+ * implementations should make sure that it contains at least all
+ * information from @see CrawlDatum.
*/
public CrawlDatum setPageRetrySchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime, long fetchTime) {
- datum.setFetchTime(fetchTime + (long)SECONDS_PER_DAY*1000);
+ long prevFetchTime, long prevModifiedTime, long fetchTime) {
+ datum.setFetchTime(fetchTime + (long) SECONDS_PER_DAY * 1000);
datum.setRetriesSinceFetch(datum.getRetriesSinceFetch() + 1);
return datum;
}
-
+
/**
* This method return the last fetch time of the CrawlDatum
+ *
* @return the date as a long.
*/
public long calculateLastFetchTime(CrawlDatum datum) {
- return datum.getFetchTime() - (long)datum.getFetchInterval() * 1000;
+ return datum.getFetchTime() - (long) datum.getFetchInterval() * 1000;
}
/**
- * This method provides information whether the page is suitable for
- * selection in the current fetchlist. NOTE: a true return value does not
- * guarantee that the page will be fetched, it just allows it to be
- * included in the further selection process based on scores. The default
- * implementation checks <code>fetchTime</code>, if it is higher than the
- * <code>curTime</code> it returns false, and true otherwise. It will also
- * check that fetchTime is not too remote (more than <code>maxInterval</code>,
- * in which case it lowers the interval and returns true.
- *
- * @param url URL of the page.
- *
- * @param datum datum instance.
- *
- * @param curTime reference time (usually set to the time when the
- * fetchlist generation process was started).
- *
+ * This method provides information whether the page is suitable for selection
+ * in the current fetchlist. NOTE: a true return value does not guarantee that
+ * the page will be fetched, it just allows it to be included in the further
+ * selection process based on scores. The default implementation checks
+ * <code>fetchTime</code>, if it is higher than the <code>curTime</code> it
+ * returns false, and true otherwise. It will also check that fetchTime is not
+ * too remote (more than <code>maxInterval</code>, in which case it lowers the
+ * interval and returns true.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * datum instance.
+ *
+ * @param curTime
+ * reference time (usually set to the time when the fetchlist
+ * generation process was started).
+ *
* @return true, if the page should be considered for inclusion in the current
- * fetchlist, otherwise false.
+ * fetchlist, otherwise false.
*/
public boolean shouldFetch(Text url, CrawlDatum datum, long curTime) {
// pages are never truly GONE - we have to check them from time to time.
@@ -176,24 +191,27 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
datum.setFetchTime(curTime);
}
if (datum.getFetchTime() > curTime) {
- return false; // not time yet
+ return false; // not time yet
}
return true;
}
-
+
/**
* This method resets fetchTime, fetchInterval, modifiedTime,
* retriesSinceFetch and page signature, so that it forces refetching.
- *
- * @param url URL of the page.
- *
- * @param datum datum instance.
- *
- * @param asap if true, force refetch as soon as possible - this sets
- * the fetchTime to now. If false, force refetch whenever the next fetch
- * time is set.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * datum instance.
+ *
+ * @param asap
+ * if true, force refetch as soon as possible - this sets the
+ * fetchTime to now. If false, force refetch whenever the next fetch
+ * time is set.
*/
- public CrawlDatum forceRefetch(Text url, CrawlDatum datum, boolean asap) {
+ public CrawlDatum forceRefetch(Text url, CrawlDatum datum, boolean asap) {
// reduce fetchInterval so that it fits within the max value
if (datum.getFetchInterval() > maxInterval)
datum.setFetchInterval(maxInterval * 0.9f);
@@ -201,7 +219,8 @@ public abstract class AbstractFetchSchedule extends Configured implements FetchS
datum.setRetriesSinceFetch(0);
datum.setSignature(null);
datum.setModifiedTime(0L);
- if (asap) datum.setFetchTime(System.currentTimeMillis());
+ if (asap)
+ datum.setFetchTime(System.currentTimeMillis());
return datum;
}
diff --git a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
index f9730f061..ee536a6bb 100755
--- a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
@@ -37,11 +37,12 @@ import org.slf4j.LoggerFactory;
* If SYNC_DELTA property is true, then:
* <ul>
* <li>calculate a <code>delta = fetchTime - modifiedTime</code></li>
- * <li>try to synchronize with the time of change, by shifting the next fetchTime
- * by a fraction of the difference between the last modification time and the last
- * fetch time. I.e. the next fetch time will be set to
+ * <li>try to synchronize with the time of change, by shifting the next
+ * fetchTime by a fraction of the difference between the last modification time
+ * and the last fetch time. I.e. the next fetch time will be set to
* <code>fetchTime + fetchInterval - delta * SYNC_DELTA_RATE</code></li>
- * <li>if the adjusted fetch interval is bigger than the delta, then <code>fetchInterval = delta</code>.</li>
+ * <li>if the adjusted fetch interval is bigger than the delta, then
+ * <code>fetchInterval = delta</code>.</li>
* </ul>
* </li>
* <li>the minimum value of fetchInterval may not be smaller than MIN_INTERVAL
@@ -49,17 +50,21 @@ import org.slf4j.LoggerFactory;
* <li>the maximum value of fetchInterval may not be bigger than MAX_INTERVAL
* (default is 365 days).</li>
* </ul>
- * <p>NOTE: values of DEC_FACTOR and INC_FACTOR higher than 0.4f may destabilize the algorithm,
- * so that the fetch interval either increases or decreases infinitely, with little
- * relevance to the page changes. Please use {@link #main(String[])} method to
- * test the values before applying them in a production system.</p>
+ * <p>
+ * NOTE: values of DEC_FACTOR and INC_FACTOR higher than 0.4f may destabilize
+ * the algorithm, so that the fetch interval either increases or decreases
+ * infinitely, with little relevance to the page changes. Please use
+ * {@link #main(String[])} method to test the values before applying them in a
+ * production system.
+ * </p>
*
* @author Andrzej Bialecki
*/
public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
// Loggg
- public static final Logger LOG = LoggerFactory.getLogger(AbstractFetchSchedule.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(AbstractFetchSchedule.class);
protected float INC_RATE;
@@ -68,26 +73,29 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
private int MAX_INTERVAL;
private int MIN_INTERVAL;
-
+
private boolean SYNC_DELTA;
private double SYNC_DELTA_RATE;
-
+
public void setConf(Configuration conf) {
super.setConf(conf);
- if (conf == null) return;
+ if (conf == null)
+ return;
INC_RATE = conf.getFloat("db.fetch.schedule.adaptive.inc_rate", 0.2f);
DEC_RATE = conf.getFloat("db.fetch.schedule.adaptive.dec_rate", 0.2f);
MIN_INTERVAL = conf.getInt("db.fetch.schedule.adaptive.min_interval", 60);
- MAX_INTERVAL = conf.getInt("db.fetch.schedule.adaptive.max_interval", SECONDS_PER_DAY * 365 ); // 1 year
+ MAX_INTERVAL = conf.getInt("db.fetch.schedule.adaptive.max_interval",
+ SECONDS_PER_DAY * 365); // 1 year
SYNC_DELTA = conf.getBoolean("db.fetch.schedule.adaptive.sync_delta", true);
- SYNC_DELTA_RATE = conf.getFloat("db.fetch.schedule.adaptive.sync_delta_rate", 0.2f);
+ SYNC_DELTA_RATE = conf.getFloat(
+ "db.fetch.schedule.adaptive.sync_delta_rate", 0.2f);
}
@Override
public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime,
- long fetchTime, long modifiedTime, int state) {
+ long prevFetchTime, long prevModifiedTime, long fetchTime,
+ long modifiedTime, int state) {
super.setFetchSchedule(url, datum, prevFetchTime, prevModifiedTime,
fetchTime, modifiedTime, state);
@@ -99,24 +107,27 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
if (datum.getMetaData().containsKey(Nutch.WRITABLE_FIXED_INTERVAL_KEY)) {
// Is fetch interval preset in CrawlDatum MD? Then use preset interval
- FloatWritable customIntervalWritable= (FloatWritable)(datum.getMetaData().get(Nutch.WRITABLE_FIXED_INTERVAL_KEY));
+ FloatWritable customIntervalWritable = (FloatWritable) (datum
+ .getMetaData().get(Nutch.WRITABLE_FIXED_INTERVAL_KEY));
interval = customIntervalWritable.get();
} else {
- if (modifiedTime <= 0) modifiedTime = fetchTime;
+ if (modifiedTime <= 0)
+ modifiedTime = fetchTime;
switch (state) {
- case FetchSchedule.STATUS_MODIFIED:
- interval *= (1.0f - DEC_RATE);
- break;
- case FetchSchedule.STATUS_NOTMODIFIED:
- interval *= (1.0f + INC_RATE);
- break;
- case FetchSchedule.STATUS_UNKNOWN:
- break;
+ case FetchSchedule.STATUS_MODIFIED:
+ interval *= (1.0f - DEC_RATE);
+ break;
+ case FetchSchedule.STATUS_NOTMODIFIED:
+ interval *= (1.0f + INC_RATE);
+ break;
+ case FetchSchedule.STATUS_UNKNOWN:
+ break;
}
if (SYNC_DELTA) {
// try to synchronize with the time of change
long delta = (fetchTime - modifiedTime) / 1000L;
- if (delta > interval) interval = delta;
+ if (delta > interval)
+ interval = delta;
refTime = fetchTime - Math.round(delta * SYNC_DELTA_RATE * 1000);
}
if (interval < MIN_INTERVAL) {
@@ -154,30 +165,39 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
// let's move the timeline a couple of deltas
for (int i = 0; i < 10000; i++) {
if (lastModified + update < curTime) {
- //System.out.println("i=" + i + ", lastModified=" + lastModified + ", update=" + update + ", curTime=" + curTime);
+ // System.out.println("i=" + i + ", lastModified=" + lastModified +
+ // ", update=" + update + ", curTime=" + curTime);
changed = true;
changeCnt++;
lastModified = curTime;
}
- LOG.info(i + ". " + changed + "\twill fetch at " + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY ) + " days" + "\t missed " + miss);
+ LOG.info(i + ". " + changed + "\twill fetch at "
+ + (p.getFetchTime() / delta) + "\tinterval "
+ + (p.getFetchInterval() / SECONDS_PER_DAY) + " days" + "\t missed "
+ + miss);
if (p.getFetchTime() <= curTime) {
fetchCnt++;
- fs.setFetchSchedule(new Text("http://www.example.com"), p,
- p.getFetchTime(), p.getModifiedTime(), curTime, lastModified,
- changed ? FetchSchedule.STATUS_MODIFIED : FetchSchedule.STATUS_NOTMODIFIED);
- LOG.info("\tfetched & adjusted: " + "\twill fetch at " + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY ) + " days");
- if (!changed) miss++;
- if (miss > maxMiss) maxMiss = miss;
+ fs.setFetchSchedule(new Text("http://www.example.com"), p, p
+ .getFetchTime(), p.getModifiedTime(), curTime, lastModified,
+ changed ? FetchSchedule.STATUS_MODIFIED
+ : FetchSchedule.STATUS_NOTMODIFIED);
+ LOG.info("\tfetched & adjusted: " + "\twill fetch at "
+ + (p.getFetchTime() / delta) + "\tinterval "
+ + (p.getFetchInterval() / SECONDS_PER_DAY) + " days");
+ if (!changed)
+ miss++;
+ if (miss > maxMiss)
+ maxMiss = miss;
changed = false;
totalMiss += miss;
miss = 0;
}
- if (changed) miss++;
+ if (changed)
+ miss++;
curTime += delta;
}
LOG.info("Total missed: " + totalMiss + ", max miss: " + maxMiss);
- LOG.info("Page changed " + changeCnt + " times, fetched " + fetchCnt + " times.");
+ LOG.info("Page changed " + changeCnt + " times, fetched " + fetchCnt
+ + " times.");
}
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDatum.java b/src/java/org/apache/nutch/crawl/CrawlDatum.java
index ec3d407e0..8e12eedf1 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDatum.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDatum.java
@@ -41,52 +41,51 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
private static final byte OLD_STATUS_FETCH_SUCCESS = 5;
private static final byte OLD_STATUS_FETCH_RETRY = 6;
private static final byte OLD_STATUS_FETCH_GONE = 7;
-
+
private static HashMap<Byte, Byte> oldToNew = new HashMap<Byte, Byte>();
-
+
/** Page was not fetched yet. */
- public static final byte STATUS_DB_UNFETCHED = 0x01;
+ public static final byte STATUS_DB_UNFETCHED = 0x01;
/** Page was successfully fetched. */
- public static final byte STATUS_DB_FETCHED = 0x02;
+ public static final byte STATUS_DB_FETCHED = 0x02;
/** Page no longer exists. */
- public static final byte STATUS_DB_GONE = 0x03;
+ public static final byte STATUS_DB_GONE = 0x03;
/** Page temporarily redirects to other page. */
- public static final byte STATUS_DB_REDIR_TEMP = 0x04;
+ public static final byte STATUS_DB_REDIR_TEMP = 0x04;
/** Page permanently redirects to other page. */
- public static final byte STATUS_DB_REDIR_PERM = 0x05;
+ public static final byte STATUS_DB_REDIR_PERM = 0x05;
/** Page was successfully fetched and found not modified. */
- public static final byte STATUS_DB_NOTMODIFIED = 0x06;
- public static final byte STATUS_DB_DUPLICATE = 0x07;
-
+ public static final byte STATUS_DB_NOTMODIFIED = 0x06;
+ public static final byte STATUS_DB_DUPLICATE = 0x07;
+
/** Maximum value of DB-related status. */
- public static final byte STATUS_DB_MAX = 0x1f;
-
+ public static final byte STATUS_DB_MAX = 0x1f;
+
/** Fetching was successful. */
- public static final byte STATUS_FETCH_SUCCESS = 0x21;
+ public static final byte STATUS_FETCH_SUCCESS = 0x21;
/** Fetching unsuccessful, needs to be retried (transient errors). */
- public static final byte STATUS_FETCH_RETRY = 0x22;
+ public static final byte STATUS_FETCH_RETRY = 0x22;
/** Fetching temporarily redirected to other page. */
- public static final byte STATUS_FETCH_REDIR_TEMP = 0x23;
+ public static final byte STATUS_FETCH_REDIR_TEMP = 0x23;
/** Fetching permanently redirected to other page. */
- public static final byte STATUS_FETCH_REDIR_PERM = 0x24;
+ public static final byte STATUS_FETCH_REDIR_PERM = 0x24;
/** Fetching unsuccessful - page is gone. */
- public static final byte STATUS_FETCH_GONE = 0x25;
+ public static final byte STATUS_FETCH_GONE = 0x25;
/** Fetching successful - page is not modified. */
public static final byte STATUS_FETCH_NOTMODIFIED = 0x26;
-
+
/** Maximum value of fetch-related status. */
- public static final byte STATUS_FETCH_MAX = 0x3f;
-
+ public static final byte STATUS_FETCH_MAX = 0x3f;
+
/** Page signature. */
- public static final byte STATUS_SIGNATURE = 0x41;
+ public static final byte STATUS_SIGNATURE = 0x41;
/** Page was newly injected. */
- public static final byte STATUS_INJECTED = 0x42;
+ public static final byte STATUS_INJECTED = 0x42;
/** Page discovered through a link. */
- public static final byte STATUS_LINKED = 0x43;
+ public static final byte STATUS_LINKED = 0x43;
/** Page got metadata from a parser */
- public static final byte STATUS_PARSE_META = 0x44;
-
-
+ public static final byte STATUS_PARSE_META = 0x44;
+
public static final HashMap<Byte, String> statNames = new HashMap<Byte, String>();
static {
statNames.put(STATUS_DB_UNFETCHED, "db_unfetched");
@@ -106,7 +105,7 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
statNames.put(STATUS_FETCH_GONE, "fetch_gone");
statNames.put(STATUS_FETCH_NOTMODIFIED, "fetch_notmodified");
statNames.put(STATUS_PARSE_META, "parse_metadata");
-
+
oldToNew.put(OLD_STATUS_DB_UNFETCHED, STATUS_DB_UNFETCHED);
oldToNew.put(OLD_STATUS_DB_FETCHED, STATUS_DB_FETCHED);
oldToNew.put(OLD_STATUS_DB_GONE, STATUS_DB_GONE);
@@ -125,22 +124,25 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
private byte[] signature = null;
private long modifiedTime;
private org.apache.hadoop.io.MapWritable metaData;
-
+
public static boolean hasDbStatus(CrawlDatum datum) {
- if (datum.status <= STATUS_DB_MAX) return true;
+ if (datum.status <= STATUS_DB_MAX)
+ return true;
return false;
}
public static boolean hasFetchStatus(CrawlDatum datum) {
- if (datum.status > STATUS_DB_MAX && datum.status <= STATUS_FETCH_MAX) return true;
+ if (datum.status > STATUS_DB_MAX && datum.status <= STATUS_FETCH_MAX)
+ return true;
return false;
}
- public CrawlDatum() { }
+ public CrawlDatum() {
+ }
public CrawlDatum(int status, int fetchInterval) {
this();
- this.status = (byte)status;
+ this.status = (byte) status;
this.fetchInterval = fetchInterval;
}
@@ -153,26 +155,36 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
// accessor methods
//
- public byte getStatus() { return status; }
-
+ public byte getStatus() {
+ return status;
+ }
+
public static String getStatusName(byte value) {
String res = statNames.get(value);
- if (res == null) res = "unknown";
+ if (res == null)
+ res = "unknown";
return res;
}
-
- public void setStatus(int status) { this.status = (byte)status; }
+
+ public void setStatus(int status) {
+ this.status = (byte) status;
+ }
/**
* Returns either the time of the last fetch, or the next fetch time,
* depending on whether Fetcher or CrawlDbReducer set the time.
*/
- public long getFetchTime() { return fetchTime; }
+ public long getFetchTime() {
+ return fetchTime;
+ }
+
/**
- * Sets either the time of the last fetch or the next fetch time,
- * depending on whether Fetcher or CrawlDbReducer set the time.
+ * Sets either the time of the last fetch or the next fetch time, depending on
+ * whether Fetcher or CrawlDbReducer set the time.
*/
- public void setFetchTime(long fetchTime) { this.fetchTime = fetchTime; }
+ public void setFetchTime(long fetchTime) {
+ this.fetchTime = fetchTime;
+ }
public long getModifiedTime() {
return modifiedTime;
@@ -181,20 +193,34 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
public void setModifiedTime(long modifiedTime) {
this.modifiedTime = modifiedTime;
}
-
- public byte getRetriesSinceFetch() { return retries; }
- public void setRetriesSinceFetch(int retries) {this.retries = (byte)retries;}
- public int getFetchInterval() { return fetchInterval; }
+ public byte getRetriesSinceFetch() {
+ return retries;
+ }
+
+ public void setRetriesSinceFetch(int retries) {
+ this.retries = (byte) retries;
+ }
+
+ public int getFetchInterval() {
+ return fetchInterval;
+ }
+
public void setFetchInterval(int fetchInterval) {
this.fetchInterval = fetchInterval;
}
+
public void setFetchInterval(float fetchInterval) {
this.fetchInterval = Math.round(fetchInterval);
}
- public float getScore() { return score; }
- public void setScore(float score) { this.score = score; }
+ public float getScore() {
+ return score;
+ }
+
+ public void setScore(float score) {
+ this.score = score;
+ }
public byte[] getSignature() {
return signature;
@@ -202,33 +228,37 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
public void setSignature(byte[] signature) {
if (signature != null && signature.length > 256)
- throw new RuntimeException("Max signature length (256) exceeded: " + signature.length);
+ throw new RuntimeException("Max signature length (256) exceeded: "
+ + signature.length);
this.signature = signature;
}
-
- public void setMetaData(org.apache.hadoop.io.MapWritable mapWritable) {
- this.metaData = new org.apache.hadoop.io.MapWritable(mapWritable);
- }
-
- /** Add all metadata from other CrawlDatum to this CrawlDatum.
- *
- * @param other CrawlDatum
- */
- public void putAllMetaData(CrawlDatum other) {
- for (Entry<Writable, Writable> e : other.getMetaData().entrySet()) {
- getMetaData().put(e.getKey(), e.getValue());
- }
- }
+
+ public void setMetaData(org.apache.hadoop.io.MapWritable mapWritable) {
+ this.metaData = new org.apache.hadoop.io.MapWritable(mapWritable);
+ }
/**
- * returns a MapWritable if it was set or read in @see readFields(DataInput),
- * returns empty map in case CrawlDatum was freshly created (lazily instantiated).
+ * Add all metadata from other CrawlDatum to this CrawlDatum.
+ *
+ * @param other
+ * CrawlDatum
+ */
+ public void putAllMetaData(CrawlDatum other) {
+ for (Entry<Writable, Writable> e : other.getMetaData().entrySet()) {
+ getMetaData().put(e.getKey(), e.getValue());
+ }
+ }
+
+ /**
+ * returns a MapWritable if it was set or read in @see readFields(DataInput),
+ * returns empty map in case CrawlDatum was freshly created (lazily
+ * instantiated).
*/
public org.apache.hadoop.io.MapWritable getMetaData() {
- if (this.metaData == null) this.metaData = new org.apache.hadoop.io.MapWritable();
+ if (this.metaData == null)
+ this.metaData = new org.apache.hadoop.io.MapWritable();
return this.metaData;
}
-
//
// writable methods
@@ -241,8 +271,8 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
}
public void readFields(DataInput in) throws IOException {
- byte version = in.readByte(); // read version
- if (version > CUR_VERSION) // check version
+ byte version = in.readByte(); // read version
+ if (version > CUR_VERSION) // check version
throw new VersionMismatchException(CUR_VERSION, version);
status = in.readByte();
@@ -250,7 +280,8 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
retries = in.readByte();
if (version > 5) {
fetchInterval = in.readInt();
- } else fetchInterval = Math.round(in.readFloat());
+ } else
+ fetchInterval = Math.round(in.readFloat());
score = in.readFloat();
if (version > 2) {
modifiedTime = in.readLong();
@@ -258,9 +289,10 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
if (cnt > 0) {
signature = new byte[cnt];
in.readFully(signature);
- } else signature = null;
+ } else
+ signature = null;
}
-
+
if (version > 3) {
boolean hasMetadata = false;
if (version < 7) {
@@ -280,7 +312,8 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
metaData.readFields(in);
}
}
- if (hasMetadata==false) metaData = null;
+ if (hasMetadata == false)
+ metaData = null;
}
// translate status codes
if (version < 5) {
@@ -288,7 +321,7 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
status = oldToNew.get(status);
else
status = STATUS_DB_UNFETCHED;
-
+
}
}
@@ -297,7 +330,7 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
private static final int SIG_OFFSET = SCORE_OFFSET + 4 + 8;
public void write(DataOutput out) throws IOException {
- out.writeByte(CUR_VERSION); // store current version
+ out.writeByte(CUR_VERSION); // store current version
out.writeByte(status);
out.writeLong(fetchTime);
out.writeByte(retries);
@@ -328,17 +361,19 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
this.modifiedTime = that.modifiedTime;
this.signature = that.signature;
if (that.metaData != null) {
- this.metaData = new org.apache.hadoop.io.MapWritable(that.metaData); // make a deep copy
+ this.metaData = new org.apache.hadoop.io.MapWritable(that.metaData); // make
+ // a
+ // deep
+ // copy
} else {
this.metaData = null;
}
}
-
//
// compare methods
//
-
+
/** Sort by decreasing score. */
public int compareTo(CrawlDatum that) {
if (that.score != this.score)
@@ -356,47 +391,49 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
return SignatureComparator._compare(this, that);
}
- /** A Comparator optimized for CrawlDatum. */
+ /** A Comparator optimized for CrawlDatum. */
public static class Comparator extends WritableComparator {
- public Comparator() { super(CrawlDatum.class); }
+ public Comparator() {
+ super(CrawlDatum.class);
+ }
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
- float score1 = readFloat(b1,s1+SCORE_OFFSET);
- float score2 = readFloat(b2,s2+SCORE_OFFSET);
+ float score1 = readFloat(b1, s1 + SCORE_OFFSET);
+ float score2 = readFloat(b2, s2 + SCORE_OFFSET);
if (score2 != score1) {
return (score2 - score1) > 0 ? 1 : -1;
}
- int status1 = b1[s1+1];
- int status2 = b2[s2+1];
+ int status1 = b1[s1 + 1];
+ int status2 = b2[s2 + 1];
if (status2 != status1)
return status1 - status2;
- long fetchTime1 = readLong(b1, s1+1+1);
- long fetchTime2 = readLong(b2, s2+1+1);
+ long fetchTime1 = readLong(b1, s1 + 1 + 1);
+ long fetchTime2 = readLong(b2, s2 + 1 + 1);
if (fetchTime2 != fetchTime1)
return (fetchTime2 - fetchTime1) > 0 ? 1 : -1;
- int retries1 = b1[s1+1+1+8];
- int retries2 = b2[s2+1+1+8];
+ int retries1 = b1[s1 + 1 + 1 + 8];
+ int retries2 = b2[s2 + 1 + 1 + 8];
if (retries2 != retries1)
return retries2 - retries1;
- int fetchInterval1 = readInt(b1, s1+1+1+8+1);
- int fetchInterval2 = readInt(b2, s2+1+1+8+1);
+ int fetchInterval1 = readInt(b1, s1 + 1 + 1 + 8 + 1);
+ int fetchInterval2 = readInt(b2, s2 + 1 + 1 + 8 + 1);
if (fetchInterval2 != fetchInterval1)
return (fetchInterval2 - fetchInterval1) > 0 ? 1 : -1;
long modifiedTime1 = readLong(b1, s1 + SCORE_OFFSET + 4);
long modifiedTime2 = readLong(b2, s2 + SCORE_OFFSET + 4);
if (modifiedTime2 != modifiedTime1)
return (modifiedTime2 - modifiedTime1) > 0 ? 1 : -1;
- int sigl1 = b1[s1+SIG_OFFSET];
- int sigl2 = b2[s2+SIG_OFFSET];
- return SignatureComparator._compare(b1, SIG_OFFSET, sigl1, b2, SIG_OFFSET, sigl2);
+ int sigl1 = b1[s1 + SIG_OFFSET];
+ int sigl2 = b2[s2 + SIG_OFFSET];
+ return SignatureComparator._compare(b1, SIG_OFFSET, sigl1, b2,
+ SIG_OFFSET, sigl2);
}
}
- static { // register this comparator
+ static { // register this comparator
WritableComparator.define(CrawlDatum.class, new Comparator());
}
-
//
// basic methods
//
@@ -404,12 +441,13 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("Version: " + CUR_VERSION + "\n");
- buf.append("Status: " + getStatus() + " (" + getStatusName(getStatus()) + ")\n");
+ buf.append("Status: " + getStatus() + " (" + getStatusName(getStatus())
+ + ")\n");
buf.append("Fetch time: " + new Date(getFetchTime()) + "\n");
buf.append("Modified time: " + new Date(getModifiedTime()) + "\n");
buf.append("Retries since fetch: " + getRetriesSinceFetch() + "\n");
- buf.append("Retry interval: " + getFetchInterval() + " seconds (" +
- (getFetchInterval() / FetchSchedule.SECONDS_PER_DAY) + " days)\n");
+ buf.append("Retry interval: " + getFetchInterval() + " seconds ("
+ + (getFetchInterval() / FetchSchedule.SECONDS_PER_DAY) + " days)\n");
buf.append("Score: " + getScore() + "\n");
buf.append("Signature: " + StringUtil.toHexString(getSignature()) + "\n");
buf.append("Metadata: \n ");
@@ -424,35 +462,35 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
}
return buf.toString();
}
-
+
private boolean metadataEquals(org.apache.hadoop.io.MapWritable otherMetaData) {
- if (metaData==null || metaData.size() ==0) {
+ if (metaData == null || metaData.size() == 0) {
return otherMetaData == null || otherMetaData.size() == 0;
}
if (otherMetaData == null) {
// we already know that the current object is not null or empty
return false;
}
- HashSet<Entry<Writable, Writable>> set1 =
- new HashSet<Entry<Writable,Writable>>(metaData.entrySet());
- HashSet<Entry<Writable, Writable>> set2 =
- new HashSet<Entry<Writable,Writable>>(otherMetaData.entrySet());
+ HashSet<Entry<Writable, Writable>> set1 = new HashSet<Entry<Writable, Writable>>(
+ metaData.entrySet());
+ HashSet<Entry<Writable, Writable>> set2 = new HashSet<Entry<Writable, Writable>>(
+ otherMetaData.entrySet());
return set1.equals(set2);
}
public boolean equals(Object o) {
if (!(o instanceof CrawlDatum))
return false;
- CrawlDatum other = (CrawlDatum)o;
- boolean res =
- (this.status == other.status) &&
- (this.fetchTime == other.fetchTime) &&
- (this.modifiedTime == other.modifiedTime) &&
- (this.retries == other.retries) &&
- (this.fetchInterval == other.fetchInterval) &&
- (SignatureComparator._compare(this.signature, other.signature) == 0) &&
- (this.score == other.score);
- if (!res) return res;
+ CrawlDatum other = (CrawlDatum) o;
+ boolean res = (this.status == other.status)
+ && (this.fetchTime == other.fetchTime)
+ && (this.modifiedTime == other.modifiedTime)
+ && (this.retries == other.retries)
+ && (this.fetchInterval == other.fetchInterval)
+ && (SignatureComparator._compare(this.signature, other.signature) == 0)
+ && (this.score == other.score);
+ if (!res)
+ return res;
return metadataEquals(other.metaData);
}
@@ -460,20 +498,14 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
int res = 0;
if (signature != null) {
for (int i = 0; i < signature.length / 4; i += 4) {
- res ^= (signature[i] << 24 + signature[i+1] << 16 +
- signature[i+2] << 8 + signature[i+3]);
+ res ^= (signature[i] << 24 + signature[i + 1] << 16 + signature[i + 2] << 8 + signature[i + 3]);
}
}
if (metaData != null) {
res ^= metaData.entrySet().hashCode();
}
- return
- res ^ status ^
- ((int)fetchTime) ^
- ((int)modifiedTime) ^
- retries ^
- fetchInterval ^
- Float.floatToIntBits(score);
+ return res ^ status ^ ((int) fetchTime) ^ ((int) modifiedTime) ^ retries
+ ^ fetchInterval ^ Float.floatToIntBits(score);
}
public Object clone() {
diff --git a/src/java/org/apache/nutch/crawl/CrawlDb.java b/src/java/org/apache/nutch/crawl/CrawlDb.java
index 40e888b9f..fe45ee328 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDb.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDb.java
@@ -38,8 +38,8 @@ import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.TimingUtil;
/**
- * This class takes the output of the fetcher and updates the
- * crawldb accordingly.
+ * This class takes the output of the fetcher and updates the crawldb
+ * accordingly.
*/
public class CrawlDb extends Configured implements Tool {
public static final Logger LOG = LoggerFactory.getLogger(CrawlDb.class);
@@ -49,21 +49,26 @@ public class CrawlDb extends Configured implements Tool {
public static final String CRAWLDB_PURGE_404 = "db.update.purge.404";
public static final String CURRENT_NAME = "current";
-
+
public static final String LOCK_NAME = ".locked";
-
- public CrawlDb() {}
-
+
+ public CrawlDb() {
+ }
+
public CrawlDb(Configuration conf) {
setConf(conf);
}
- public void update(Path crawlDb, Path[] segments, boolean normalize, boolean filter) throws IOException {
- boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED, true);
+ public void update(Path crawlDb, Path[] segments, boolean normalize,
+ boolean filter) throws IOException {
+ boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED,
+ true);
update(crawlDb, segments, normalize, filter, additionsAllowed, false);
}
-
- public void update(Path crawlDb, Path[] segments, boolean normalize, boolean filter, boolean additionsAllowed, boolean force) throws IOException {
+
+ public void update(Path crawlDb, Path[] segments, boolean normalize,
+ boolean filter, boolean additionsAllowed, boolean force)
+ throws IOException {
FileSystem fs = FileSystem.get(getConf());
Path lock = new Path(crawlDb, LOCK_NAME);
LockUtil.createLockFile(fs, lock, force);
@@ -106,22 +111,24 @@ public class CrawlDb extends Configured implements Tool {
} catch (IOException e) {
LockUtil.removeLockFile(fs, lock);
Path outPath = FileOutputFormat.getOutputPath(job);
- if (fs.exists(outPath) ) fs.delete(outPath, true);
+ if (fs.exists(outPath))
+ fs.delete(outPath, true);
throw e;
}
CrawlDb.install(job, crawlDb);
long end = System.currentTimeMillis();
- LOG.info("CrawlDb update: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("CrawlDb update: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
-/*
- * Configure a new CrawlDb in a temp folder at crawlDb/<rand>
- */
+
+ /*
+ * Configure a new CrawlDb in a temp folder at crawlDb/<rand>
+ */
public static JobConf createJob(Configuration config, Path crawlDb)
- throws IOException {
- Path newCrawlDb =
- new Path(crawlDb,
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ throws IOException {
+ Path newCrawlDb = new Path(crawlDb, Integer.toString(new Random()
+ .nextInt(Integer.MAX_VALUE)));
JobConf job = new NutchJob(config);
job.setJobName("crawldb " + crawlDb);
@@ -154,12 +161,14 @@ public class CrawlDb extends Configured implements Tool {
Path old = new Path(crawlDb, "old");
Path current = new Path(crawlDb, CURRENT_NAME);
if (fs.exists(current)) {
- if (fs.exists(old)) fs.delete(old, true);
+ if (fs.exists(old))
+ fs.delete(old, true);
fs.rename(current, old);
}
fs.mkdirs(crawlDb);
fs.rename(newCrawlDb, current);
- if (!preserveBackup && fs.exists(old)) fs.delete(old, true);
+ if (!preserveBackup && fs.exists(old))
+ fs.delete(old, true);
Path lock = new Path(crawlDb, LOCK_NAME);
LockUtil.removeLockFile(fs, lock);
}
@@ -171,20 +180,29 @@ public class CrawlDb extends Configured implements Tool {
public int run(String[] args) throws Exception {
if (args.length < 1) {
- System.err.println("Usage: CrawlDb <crawldb> (-dir <segments> | <seg1> <seg2> ...) [-force] [-normalize] [-filter] [-noAdditions]");
+ System.err
+ .println("Usage: CrawlDb <crawldb> (-dir <segments> | <seg1> <seg2> ...) [-force] [-normalize] [-filter] [-noAdditions]");
System.err.println("\tcrawldb\tCrawlDb to update");
- System.err.println("\t-dir segments\tparent directory containing all segments to update from");
- System.err.println("\tseg1 seg2 ...\tlist of segment names to update from");
- System.err.println("\t-force\tforce update even if CrawlDb appears to be locked (CAUTION advised)");
- System.err.println("\t-normalize\tuse URLNormalizer on urls in CrawlDb and segment (usually not needed)");
- System.err.println("\t-filter\tuse URLFilters on urls in CrawlDb and segment");
- System.err.println("\t-noAdditions\tonly update already existing URLs, don't add any newly discovered URLs");
+ System.err
+ .println("\t-dir segments\tparent directory containing all segments to update from");
+ System.err
+ .println("\tseg1 seg2 ...\tlist of segment names to update from");
+ System.err
+ .println("\t-force\tforce update even if CrawlDb appears to be locked (CAUTION advised)");
+ System.err
+ .println("\t-normalize\tuse URLNormalizer on urls in CrawlDb and segment (usually not needed)");
+ System.err
+ .println("\t-filter\tuse URLFilters on urls in CrawlDb and segment");
+ System.err
+ .println("\t-noAdditions\tonly update already existing URLs, don't add any newly discovered URLs");
return -1;
}
- boolean normalize = getConf().getBoolean(CrawlDbFilter.URL_NORMALIZING, false);
+ boolean normalize = getConf().getBoolean(CrawlDbFilter.URL_NORMALIZING,
+ false);
boolean filter = getConf().getBoolean(CrawlDbFilter.URL_FILTERING, false);
- boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED, true);
+ boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED,
+ true);
boolean force = false;
final FileSystem fs = FileSystem.get(getConf());
HashSet<Path> dirs = new HashSet<Path>();
@@ -198,14 +216,16 @@ public class CrawlDb extends Configured implements Tool {
} else if (args[i].equals("-noAdditions")) {
additionsAllowed = false;
} else if (args[i].equals("-dir")) {
- FileStatus[] paths = fs.listStatus(new Path(args[++i]), HadoopFSUtil.getPassDirectoriesFilter(fs));
+ FileStatus[] paths = fs.listStatus(new Path(args[++i]),
+ HadoopFSUtil.getPassDirectoriesFilter(fs));
dirs.addAll(Arrays.asList(HadoopFSUtil.getPaths(paths)));
} else {
dirs.add(new Path(args[i]));
}
}
try {
- update(new Path(args[0]), dirs.toArray(new Path[dirs.size()]), normalize, filter, additionsAllowed, force);
+ update(new Path(args[0]), dirs.toArray(new Path[dirs.size()]), normalize,
+ filter, additionsAllowed, force);
return 0;
} catch (Exception e) {
LOG.error("CrawlDb update: " + StringUtils.stringifyException(e));
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
index 45c685106..de4c37be3 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
@@ -30,12 +30,13 @@ import org.apache.nutch.net.URLFilters;
import org.apache.nutch.net.URLNormalizers;
/**
- * This class provides a way to separate the URL normalization
- * and filtering steps from the rest of CrawlDb manipulation code.
+ * This class provides a way to separate the URL normalization and filtering
+ * steps from the rest of CrawlDb manipulation code.
*
* @author Andrzej Bialecki
*/
-public class CrawlDbFilter implements Mapper<Text, CrawlDatum, Text, CrawlDatum> {
+public class CrawlDbFilter implements
+ Mapper<Text, CrawlDatum, Text, CrawlDatum> {
public static final String URL_FILTERING = "crawldb.url.filters";
public static final String URL_NORMALIZING = "crawldb.url.normalizers";
@@ -51,7 +52,7 @@ public class CrawlDbFilter implements Mapper<Text, CrawlDatum, Text, CrawlDatum>
private URLFilters filters;
private URLNormalizers normalizers;
-
+
private String scope;
public static final Logger LOG = LoggerFactory.getLogger(CrawlDbFilter.class);
@@ -70,17 +71,19 @@ public class CrawlDbFilter implements Mapper<Text, CrawlDatum, Text, CrawlDatum>
}
}
- public void close() {}
-
+ public void close() {
+ }
+
private Text newKey = new Text();
public void map(Text key, CrawlDatum value,
- OutputCollector<Text, CrawlDatum> output,
- Reporter reporter) throws IOException {
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
String url = key.toString();
- // https://issues.apache.org/jira/browse/NUTCH-1101 check status first, cheaper than normalizing or filtering
+ // https://issues.apache.org/jira/browse/NUTCH-1101 check status first,
+ // cheaper than normalizing or filtering
if (url404Purging && CrawlDatum.STATUS_DB_GONE == value.getStatus()) {
url = null;
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java b/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
index b5816de28..cd775d8b0 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
@@ -39,36 +39,42 @@ import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.TimingUtil;
/**
- * This tool merges several CrawlDb-s into one, optionally filtering
- * URLs through the current URLFilters, to skip prohibited
- * pages.
+ * This tool merges several CrawlDb-s into one, optionally filtering URLs
+ * through the current URLFilters, to skip prohibited pages.
*
- * <p>It's possible to use this tool just for filtering - in that case
- * only one CrawlDb should be specified in arguments.</p>
- * <p>If more than one CrawlDb contains information about the same URL,
- * only the most recent version is retained, as determined by the
- * value of {@link org.apache.nutch.crawl.CrawlDatum#getFetchTime()}.
- * However, all metadata information from all versions is accumulated,
- * with newer values taking precedence over older values.
+ * <p>
+ * It's possible to use this tool just for filtering - in that case only one
+ * CrawlDb should be specified in arguments.
+ * </p>
+ * <p>
+ * If more than one CrawlDb contains information about the same URL, only the
+ * most recent version is retained, as determined by the value of
+ * {@link org.apache.nutch.crawl.CrawlDatum#getFetchTime()}. However, all
+ * metadata information from all versions is accumulated, with newer values
+ * taking precedence over older values.
*
* @author Andrzej Bialecki
*/
public class CrawlDbMerger extends Configured implements Tool {
- private static final Logger LOG = LoggerFactory.getLogger(CrawlDbMerger.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(CrawlDbMerger.class);
- public static class Merger extends MapReduceBase implements Reducer<Text, CrawlDatum, Text, CrawlDatum> {
+ public static class Merger extends MapReduceBase implements
+ Reducer<Text, CrawlDatum, Text, CrawlDatum> {
private org.apache.hadoop.io.MapWritable meta;
private CrawlDatum res = new CrawlDatum();
private FetchSchedule schedule;
- public void close() throws IOException {}
+ public void close() throws IOException {
+ }
public void configure(JobConf conf) {
schedule = FetchScheduleFactory.getFetchSchedule(conf);
}
- public void reduce(Text key, Iterator<CrawlDatum> values, OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ public void reduce(Text key, Iterator<CrawlDatum> values,
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
long resTime = 0L;
boolean resSet = false;
meta = new org.apache.hadoop.io.MapWritable();
@@ -91,7 +97,7 @@ public class CrawlDbMerger extends Configured implements Tool {
meta.put(e.getKey(), e.getValue());
}
res.set(val);
- resTime = valTime ;
+ resTime = valTime;
} else {
// insert older metadata before newer
for (Entry<Writable, Writable> e : meta.entrySet()) {
@@ -104,37 +110,44 @@ public class CrawlDbMerger extends Configured implements Tool {
output.collect(key, res);
}
}
-
+
public CrawlDbMerger() {
-
+
}
-
+
public CrawlDbMerger(Configuration conf) {
setConf(conf);
}
- public void merge(Path output, Path[] dbs, boolean normalize, boolean filter) throws Exception {
+ public void merge(Path output, Path[] dbs, boolean normalize, boolean filter)
+ throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
LOG.info("CrawlDb merge: starting at " + sdf.format(start));
JobConf job = createMergeJob(getConf(), output, normalize, filter);
for (int i = 0; i < dbs.length; i++) {
- if (LOG.isInfoEnabled()) { LOG.info("Adding " + dbs[i]); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Adding " + dbs[i]);
+ }
FileInputFormat.addInputPath(job, new Path(dbs[i], CrawlDb.CURRENT_NAME));
}
JobClient.runJob(job);
FileSystem fs = FileSystem.get(getConf());
- if(fs.exists(output))
- fs.delete(output,true);
+ if (fs.exists(output))
+ fs.delete(output, true);
fs.mkdirs(output);
- fs.rename(FileOutputFormat.getOutputPath(job), new Path(output, CrawlDb.CURRENT_NAME));
+ fs.rename(FileOutputFormat.getOutputPath(job), new Path(output,
+ CrawlDb.CURRENT_NAME));
long end = System.currentTimeMillis();
- LOG.info("CrawlDb merge: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("CrawlDb merge: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- public static JobConf createMergeJob(Configuration conf, Path output, boolean normalize, boolean filter) {
- Path newCrawlDb = new Path("crawldb-merge-" + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ public static JobConf createMergeJob(Configuration conf, Path output,
+ boolean normalize, boolean filter) {
+ Path newCrawlDb = new Path("crawldb-merge-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
JobConf job = new NutchJob(conf);
job.setJobName("crawldb merge " + output);
@@ -158,16 +171,20 @@ public class CrawlDbMerger extends Configured implements Tool {
* @param args
*/
public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new CrawlDbMerger(), args);
+ int res = ToolRunner.run(NutchConfiguration.create(), new CrawlDbMerger(),
+ args);
System.exit(res);
}
-
+
public int run(String[] args) throws Exception {
if (args.length < 2) {
- System.err.println("Usage: CrawlDbMerger <output_crawldb> <crawldb1> [<crawldb2> <crawldb3> ...] [-normalize] [-filter]");
+ System.err
+ .println("Usage: CrawlDbMerger <output_crawldb> <crawldb1> [<crawldb2> <crawldb3> ...] [-normalize] [-filter]");
System.err.println("\toutput_crawldb\toutput CrawlDb");
- System.err.println("\tcrawldb1 ...\tinput CrawlDb-s (single input CrawlDb is ok)");
- System.err.println("\t-normalize\tuse URLNormalizer on urls in the crawldb(s) (usually not needed)");
+ System.err
+ .println("\tcrawldb1 ...\tinput CrawlDb-s (single input CrawlDb is ok)");
+ System.err
+ .println("\t-normalize\tuse URLNormalizer on urls in the crawldb(s) (usually not needed)");
System.err.println("\t-filter\tuse URLFilters on urls in the crawldb(s)");
return -1;
}
@@ -185,8 +202,8 @@ public class CrawlDbMerger extends Configured implements Tool {
continue;
}
final Path dbPath = new Path(args[i]);
- if(fs.exists(dbPath))
- dbs.add(dbPath);
+ if (fs.exists(dbPath))
+ dbs.add(dbPath);
}
try {
merge(output, dbs.toArray(new Path[dbs.size()]), normalize, filter);
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
index 50af3e6cb..e5caadc2b 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReader.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
@@ -30,7 +30,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.TreeMap;
-
// Commons Logging imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -66,9 +65,9 @@ import org.apache.nutch.util.StringUtil;
/**
* Read utility for the CrawlDB.
- *
+ *
* @author Andrzej Bialecki
- *
+ *
*/
public class CrawlDbReader implements Closeable {
@@ -76,15 +75,18 @@ public class CrawlDbReader implements Closeable {
private MapFile.Reader[] readers = null;
- private void openReaders(String crawlDb, Configuration config) throws IOException {
- if (readers != null) return;
+ private void openReaders(String crawlDb, Configuration config)
+ throws IOException {
+ if (readers != null)
+ return;
FileSystem fs = FileSystem.get(config);
readers = MapFileOutputFormat.getReaders(fs, new Path(crawlDb,
CrawlDb.CURRENT_NAME), config);
}
private void closeReaders() {
- if (readers == null) return;
+ if (readers == null)
+ return;
for (int i = 0; i < readers.length; i++) {
try {
readers[i].close();
@@ -94,55 +96,61 @@ public class CrawlDbReader implements Closeable {
}
}
- public static class CrawlDatumCsvOutputFormat extends FileOutputFormat<Text,CrawlDatum> {
- protected static class LineRecordWriter implements RecordWriter<Text,CrawlDatum> {
+ public static class CrawlDatumCsvOutputFormat extends
+ FileOutputFormat<Text, CrawlDatum> {
+ protected static class LineRecordWriter implements
+ RecordWriter<Text, CrawlDatum> {
private DataOutputStream out;
+
public LineRecordWriter(DataOutputStream out) {
this.out = out;
try {
out.writeBytes("Url,Status code,Status name,Fetch Time,Modified Time,Retries since fetch,Retry interval seconds,Retry interval days,Score,Signature,Metadata\n");
- } catch (IOException e) {}
+ } catch (IOException e) {
+ }
}
- public synchronized void write(Text key, CrawlDatum value) throws IOException {
- out.writeByte('"');
- out.writeBytes(key.toString());
- out.writeByte('"');
- out.writeByte(',');
- out.writeBytes(Integer.toString(value.getStatus()));
- out.writeByte(',');
- out.writeByte('"');
- out.writeBytes(CrawlDatum.getStatusName(value.getStatus()));
- out.writeByte('"');
- out.writeByte(',');
- out.writeBytes(new Date(value.getFetchTime()).toString());
- out.writeByte(',');
- out.writeBytes(new Date(value.getModifiedTime()).toString());
- out.writeByte(',');
- out.writeBytes(Integer.toString(value.getRetriesSinceFetch()));
- out.writeByte(',');
- out.writeBytes(Float.toString(value.getFetchInterval()));
- out.writeByte(',');
- out.writeBytes(Float.toString((value.getFetchInterval() / FetchSchedule.SECONDS_PER_DAY)));
- out.writeByte(',');
- out.writeBytes(Float.toString(value.getScore()));
- out.writeByte(',');
- out.writeByte('"');
- out.writeBytes(value.getSignature() != null ? StringUtil.toHexString(value.getSignature()): "null");
- out.writeByte('"');
- out.writeByte(',');
- out.writeByte('"');
- if (value.getMetaData() != null) {
- for (Entry<Writable, Writable> e : value.getMetaData().entrySet()) {
- out.writeBytes(e.getKey().toString());
- out.writeByte(':');
- out.writeBytes(e.getValue().toString());
- out.writeBytes("|||");
- }
+ public synchronized void write(Text key, CrawlDatum value)
+ throws IOException {
+ out.writeByte('"');
+ out.writeBytes(key.toString());
+ out.writeByte('"');
+ out.writeByte(',');
+ out.writeBytes(Integer.toString(value.getStatus()));
+ out.writeByte(',');
+ out.writeByte('"');
+ out.writeBytes(CrawlDatum.getStatusName(value.getStatus()));
+ out.writeByte('"');
+ out.writeByte(',');
+ out.writeBytes(new Date(value.getFetchTime()).toString());
+ out.writeByte(',');
+ out.writeBytes(new Date(value.getModifiedTime()).toString());
+ out.writeByte(',');
+ out.writeBytes(Integer.toString(value.getRetriesSinceFetch()));
+ out.writeByte(',');
+ out.writeBytes(Float.toString(value.getFetchInterval()));
+ out.writeByte(',');
+ out.writeBytes(Float.toString((value.getFetchInterval() / FetchSchedule.SECONDS_PER_DAY)));
+ out.writeByte(',');
+ out.writeBytes(Float.toString(value.getScore()));
+ out.writeByte(',');
+ out.writeByte('"');
+ out.writeBytes(value.getSignature() != null ? StringUtil
+ .toHexString(value.getSignature()) : "null");
+ out.writeByte('"');
+ out.writeByte(',');
+ out.writeByte('"');
+ if (value.getMetaData() != null) {
+ for (Entry<Writable, Writable> e : value.getMetaData().entrySet()) {
+ out.writeBytes(e.getKey().toString());
+ out.writeByte(':');
+ out.writeBytes(e.getValue().toString());
+ out.writeBytes("|||");
}
- out.writeByte('"');
+ }
+ out.writeByte('"');
- out.writeByte('\n');
+ out.writeByte('\n');
}
public synchronized void close(Reporter reporter) throws IOException {
@@ -150,42 +158,59 @@ public class CrawlDbReader implements Closeable {
}
}
- public RecordWriter<Text,CrawlDatum> getRecordWriter(FileSystem fs, JobConf job, String name,
- Progressable progress) throws IOException {
+ public RecordWriter<Text, CrawlDatum> getRecordWriter(FileSystem fs,
+ JobConf job, String name, Progressable progress) throws IOException {
Path dir = FileOutputFormat.getOutputPath(job);
DataOutputStream fileOut = fs.create(new Path(dir, name), progress);
return new LineRecordWriter(fileOut);
- }
+ }
}
- public static class CrawlDbStatMapper implements Mapper<Text, CrawlDatum, Text, LongWritable> {
+ public static class CrawlDbStatMapper implements
+ Mapper<Text, CrawlDatum, Text, LongWritable> {
LongWritable COUNT_1 = new LongWritable(1);
private boolean sort = false;
+
public void configure(JobConf job) {
- sort = job.getBoolean("db.reader.stats.sort", false );
+ sort = job.getBoolean("db.reader.stats.sort", false);
+ }
+
+ public void close() {
}
- public void close() {}
- public void map(Text key, CrawlDatum value, OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
+
+ public void map(Text key, CrawlDatum value,
+ OutputCollector<Text, LongWritable> output, Reporter reporter)
+ throws IOException {
output.collect(new Text("T"), COUNT_1);
output.collect(new Text("status " + value.getStatus()), COUNT_1);
- output.collect(new Text("retry " + value.getRetriesSinceFetch()), COUNT_1);
- output.collect(new Text("s"), new LongWritable((long) (value.getScore() * 1000.0)));
- if(sort){
+ output
+ .collect(new Text("retry " + value.getRetriesSinceFetch()), COUNT_1);
+ output.collect(new Text("s"), new LongWritable(
+ (long) (value.getScore() * 1000.0)));
+ if (sort) {
URL u = new URL(key.toString());
String host = u.getHost();
- output.collect(new Text("status " + value.getStatus() + " " + host), COUNT_1);
+ output.collect(new Text("status " + value.getStatus() + " " + host),
+ COUNT_1);
}
}
}
- public static class CrawlDbStatCombiner implements Reducer<Text, LongWritable, Text, LongWritable> {
+ public static class CrawlDbStatCombiner implements
+ Reducer<Text, LongWritable, Text, LongWritable> {
LongWritable val = new LongWritable();
- public CrawlDbStatCombiner() { }
- public void configure(JobConf job) { }
- public void close() {}
- public void reduce(Text key, Iterator<LongWritable> values, OutputCollector<Text, LongWritable> output, Reporter reporter)
+ public CrawlDbStatCombiner() {
+ }
+
+ public void configure(JobConf job) {
+ }
+
+ public void close() {
+ }
+
+ public void reduce(Text key, Iterator<LongWritable> values,
+ OutputCollector<Text, LongWritable> output, Reporter reporter)
throws IOException {
val.set(0L);
String k = key.toString();
@@ -201,8 +226,10 @@ public class CrawlDbReader implements Closeable {
long max = Long.MIN_VALUE;
while (values.hasNext()) {
LongWritable cnt = values.next();
- if (cnt.get() < min) min = cnt.get();
- if (cnt.get() > max) max = cnt.get();
+ if (cnt.get() < min)
+ min = cnt.get();
+ if (cnt.get() > max)
+ max = cnt.get();
total += cnt.get();
}
output.collect(new Text("scn"), new LongWritable(min));
@@ -212,11 +239,17 @@ public class CrawlDbReader implements Closeable {
}
}
- public static class CrawlDbStatReducer implements Reducer<Text, LongWritable, Text, LongWritable> {
- public void configure(JobConf job) {}
- public void close() {}
- public void reduce(Text key, Iterator<LongWritable> values, OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
+ public static class CrawlDbStatReducer implements
+ Reducer<Text, LongWritable, Text, LongWritable> {
+ public void configure(JobConf job) {
+ }
+
+ public void close() {
+ }
+
+ public void reduce(Text key, Iterator<LongWritable> values,
+ OutputCollector<Text, LongWritable> output, Reporter reporter)
+ throws IOException {
String k = key.toString();
if (k.equals("T")) {
@@ -238,14 +271,16 @@ public class CrawlDbReader implements Closeable {
LongWritable cnt = new LongWritable(Long.MIN_VALUE);
while (values.hasNext()) {
LongWritable val = values.next();
- if (cnt.get() < val.get()) cnt.set(val.get());
+ if (cnt.get() < val.get())
+ cnt.set(val.get());
}
output.collect(key, cnt);
} else if (k.equals("scn")) {
LongWritable cnt = new LongWritable(Long.MAX_VALUE);
while (values.hasNext()) {
LongWritable val = values.next();
- if (cnt.get() > val.get()) cnt.set(val.get());
+ if (cnt.get() > val.get())
+ cnt.set(val.get());
}
output.collect(key, cnt);
} else if (k.equals("sct")) {
@@ -259,27 +294,36 @@ public class CrawlDbReader implements Closeable {
}
}
- public static class CrawlDbTopNMapper implements Mapper<Text, CrawlDatum, FloatWritable, Text> {
+ public static class CrawlDbTopNMapper implements
+ Mapper<Text, CrawlDatum, FloatWritable, Text> {
private static final FloatWritable fw = new FloatWritable();
private float min = 0.0f;
public void configure(JobConf job) {
min = job.getFloat("db.reader.topn.min", 0.0f);
}
- public void close() {}
- public void map(Text key, CrawlDatum value, OutputCollector<FloatWritable, Text> output, Reporter reporter)
- throws IOException {
- if (value.getScore() < min) return; // don't collect low-scoring records
+
+ public void close() {
+ }
+
+ public void map(Text key, CrawlDatum value,
+ OutputCollector<FloatWritable, Text> output, Reporter reporter)
+ throws IOException {
+ if (value.getScore() < min)
+ return; // don't collect low-scoring records
fw.set(-value.getScore()); // reverse sorting order
output.collect(fw, key); // invert mapping: score -> url
}
}
- public static class CrawlDbTopNReducer implements Reducer<FloatWritable, Text, FloatWritable, Text> {
+ public static class CrawlDbTopNReducer implements
+ Reducer<FloatWritable, Text, FloatWritable, Text> {
private long topN;
private long count = 0L;
- public void reduce(FloatWritable key, Iterator<Text> values, OutputCollector<FloatWritable, Text> output, Reporter reporter) throws IOException {
+ public void reduce(FloatWritable key, Iterator<Text> values,
+ OutputCollector<FloatWritable, Text> output, Reporter reporter)
+ throws IOException {
while (values.hasNext() && count < topN) {
key.set(-key.get());
output.collect(key, values.next());
@@ -291,14 +335,16 @@ public class CrawlDbReader implements Closeable {
topN = job.getLong("db.reader.topn", 100) / job.getNumReduceTasks();
}
- public void close() {}
+ public void close() {
+ }
}
public void close() {
closeReaders();
}
- public void processStatJob(String crawlDb, Configuration config, boolean sort) throws IOException {
+ public void processStatJob(String crawlDb, Configuration config, boolean sort)
+ throws IOException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb statistics start: " + crawlDb);
@@ -329,7 +375,8 @@ public class CrawlDbReader implements Closeable {
// reading the result
FileSystem fileSystem = FileSystem.get(config);
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(config, tmpFolder);
+ SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(config,
+ tmpFolder);
Text key = new Text();
LongWritable value = new LongWritable();
@@ -342,14 +389,18 @@ public class CrawlDbReader implements Closeable {
LongWritable val = stats.get(k);
if (val == null) {
val = new LongWritable();
- if (k.equals("scx")) val.set(Long.MIN_VALUE);
- if (k.equals("scn")) val.set(Long.MAX_VALUE);
+ if (k.equals("scx"))
+ val.set(Long.MIN_VALUE);
+ if (k.equals("scn"))
+ val.set(Long.MAX_VALUE);
stats.put(k, val);
}
if (k.equals("scx")) {
- if (val.get() < value.get()) val.set(value.get());
+ if (val.get() < value.get())
+ val.set(value.get());
} else if (k.equals("scn")) {
- if (val.get() > value.get()) val.set(value.get());
+ if (val.get() > value.get())
+ val.set(value.get());
} else {
val.set(val.get() + value.get());
}
@@ -370,31 +421,40 @@ public class CrawlDbReader implements Closeable {
} else if (k.equals("scx")) {
LOG.info("max score:\t" + (val.get() / 1000.0f));
} else if (k.equals("sct")) {
- LOG.info("avg score:\t" + (float) ((((double)val.get()) / totalCnt.get()) / 1000.0));
+ LOG.info("avg score:\t"
+ + (float) ((((double) val.get()) / totalCnt.get()) / 1000.0));
} else if (k.startsWith("status")) {
String[] st = k.split(" ");
int code = Integer.parseInt(st[1]);
- if(st.length >2 ) LOG.info(" " + st[2] +" :\t" + val);
- else LOG.info(st[0] +" " +code + " (" + CrawlDatum.getStatusName((byte) code) + "):\t" + val);
- } else LOG.info(k + ":\t" + val);
+ if (st.length > 2)
+ LOG.info(" " + st[2] + " :\t" + val);
+ else
+ LOG.info(st[0] + " " + code + " ("
+ + CrawlDatum.getStatusName((byte) code) + "):\t" + val);
+ } else
+ LOG.info(k + ":\t" + val);
}
}
// removing the tmp folder
fileSystem.delete(tmpFolder, true);
- if (LOG.isInfoEnabled()) { LOG.info("CrawlDb statistics: done"); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("CrawlDb statistics: done");
+ }
}
- public CrawlDatum get(String crawlDb, String url, Configuration config) throws IOException {
+ public CrawlDatum get(String crawlDb, String url, Configuration config)
+ throws IOException {
Text key = new Text(url);
CrawlDatum val = new CrawlDatum();
openReaders(crawlDb, config);
- CrawlDatum res = (CrawlDatum)MapFileOutputFormat.getEntry(readers,
+ CrawlDatum res = (CrawlDatum) MapFileOutputFormat.getEntry(readers,
new HashPartitioner<Text, CrawlDatum>(), key, val);
return res;
}
- public void readUrl(String crawlDb, String url, Configuration config) throws IOException {
+ public void readUrl(String crawlDb, String url, Configuration config)
+ throws IOException {
CrawlDatum res = get(crawlDb, url, config);
System.out.println("URL: " + url);
if (res != null) {
@@ -404,7 +464,9 @@ public class CrawlDbReader implements Closeable {
}
}
- public void processDumpJob(String crawlDb, String output, Configuration config, String format, String regex, String status, Integer retry) throws IOException {
+ public void processDumpJob(String crawlDb, String output,
+ Configuration config, String format, String regex, String status,
+ Integer retry) throws IOException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb dump: starting");
LOG.info("CrawlDb db: " + crawlDb);
@@ -421,26 +483,31 @@ public class CrawlDbReader implements Closeable {
if (format.equals("csv")) {
job.setOutputFormat(CrawlDatumCsvOutputFormat.class);
- }
- else if (format.equals("crawldb")) {
+ } else if (format.equals("crawldb")) {
job.setOutputFormat(MapFileOutputFormat.class);
} else {
job.setOutputFormat(TextOutputFormat.class);
}
- if (status != null) job.set("status", status);
- if (regex != null) job.set("regex", regex);
- if (retry != null) job.setInt("retry", retry);
-
+ if (status != null)
+ job.set("status", status);
+ if (regex != null)
+ job.set("regex", regex);
+ if (retry != null)
+ job.setInt("retry", retry);
+
job.setMapperClass(CrawlDbDumpMapper.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
JobClient.runJob(job);
- if (LOG.isInfoEnabled()) { LOG.info("CrawlDb dump: done"); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("CrawlDb dump: done");
+ }
}
- public static class CrawlDbDumpMapper implements Mapper<Text, CrawlDatum, Text, CrawlDatum> {
+ public static class CrawlDbDumpMapper implements
+ Mapper<Text, CrawlDatum, Text, CrawlDatum> {
Pattern pattern = null;
Matcher matcher = null;
String status = null;
@@ -454,10 +521,13 @@ public class CrawlDbReader implements Closeable {
retry = job.getInt("retry", -1);
}
- public void close() {}
- public void map(Text key, CrawlDatum value, OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
-
+ public void close() {
+ }
+
+ public void map(Text key, CrawlDatum value,
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
+
// check retry
if (retry != -1) {
if (value.getRetriesSinceFetch() < retry) {
@@ -467,7 +537,9 @@ public class CrawlDbReader implements Closeable {
// check status
if (status != null
- && !status.equalsIgnoreCase(CrawlDatum.getStatusName(value.getStatus()))) return;
+ && !status.equalsIgnoreCase(CrawlDatum.getStatusName(value
+ .getStatus())))
+ return;
// check regex
if (pattern != null) {
@@ -481,7 +553,8 @@ public class CrawlDbReader implements Closeable {
}
}
- public void processTopNJob(String crawlDb, long topN, float min, String output, Configuration config) throws IOException {
+ public void processTopNJob(String crawlDb, long topN, float min,
+ String output, Configuration config) throws IOException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb topN: starting (topN=" + topN + ", min=" + min + ")");
@@ -489,10 +562,9 @@ public class CrawlDbReader implements Closeable {
}
Path outFolder = new Path(output);
- Path tempDir =
- new Path(config.get("mapred.temp.dir", ".") +
- "/readdb-topN-temp-"+
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ Path tempDir = new Path(config.get("mapred.temp.dir", ".")
+ + "/readdb-topN-temp-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
JobConf job = new NutchJob(config);
job.setJobName("topN prepare " + crawlDb);
@@ -531,7 +603,9 @@ public class CrawlDbReader implements Closeable {
JobClient.runJob(job);
FileSystem fs = FileSystem.get(config);
fs.delete(tempDir, true);
- if (LOG.isInfoEnabled()) { LOG.info("CrawlDb topN: done"); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("CrawlDb topN: done");
+ }
}
@@ -540,20 +614,29 @@ public class CrawlDbReader implements Closeable {
CrawlDbReader dbr = new CrawlDbReader();
if (args.length < 2) {
- System.err.println("Usage: CrawlDbReader <crawldb> (-stats | -dump <out_dir> | -topN <nnnn> <out_dir> [<min>] | -url <url>)");
- System.err.println("\t<crawldb>\tdirectory name where crawldb is located");
- System.err.println("\t-stats [-sort] \tprint overall statistics to System.out");
+ System.err
+ .println("Usage: CrawlDbReader <crawldb> (-stats | -dump <out_dir> | -topN <nnnn> <out_dir> [<min>] | -url <url>)");
+ System.err
+ .println("\t<crawldb>\tdirectory name where crawldb is located");
+ System.err
+ .println("\t-stats [-sort] \tprint overall statistics to System.out");
System.err.println("\t\t[-sort]\tlist status sorted by host");
- System.err.println("\t-dump <out_dir> [-format normal|csv|crawldb]\tdump the whole db to a text file in <out_dir>");
+ System.err
+ .println("\t-dump <out_dir> [-format normal|csv|crawldb]\tdump the whole db to a text file in <out_dir>");
System.err.println("\t\t[-format csv]\tdump in Csv format");
- System.err.println("\t\t[-format normal]\tdump in standard format (default option)");
+ System.err
+ .println("\t\t[-format normal]\tdump in standard format (default option)");
System.err.println("\t\t[-format crawldb]\tdump as CrawlDB");
System.err.println("\t\t[-regex <expr>]\tfilter records with expression");
System.err.println("\t\t[-retry <num>]\tminimum retry count");
- System.err.println("\t\t[-status <status>]\tfilter records by CrawlDatum status");
- System.err.println("\t-url <url>\tprint information on <url> to System.out");
- System.err.println("\t-topN <nnnn> <out_dir> [<min>]\tdump top <nnnn> urls sorted by score to <out_dir>");
- System.err.println("\t\t[<min>]\tskip records with scores below this value.");
+ System.err
+ .println("\t\t[-status <status>]\tfilter records by CrawlDatum status");
+ System.err
+ .println("\t-url <url>\tprint information on <url> to System.out");
+ System.err
+ .println("\t-topN <nnnn> <out_dir> [<min>]\tdump top <nnnn> urls sorted by score to <out_dir>");
+ System.err
+ .println("\t\t[<min>]\tskip records with scores below this value.");
System.err.println("\t\t\tThis can significantly improve performance.");
return;
}
@@ -563,7 +646,7 @@ public class CrawlDbReader implements Closeable {
for (int i = 1; i < args.length; i++) {
if (args[i].equals("-stats")) {
boolean toSort = false;
- if(i < args.length - 1 && "-sort".equals(args[i+1])){
+ if (i < args.length - 1 && "-sort".equals(args[i + 1])) {
toSort = true;
i++;
}
@@ -577,19 +660,19 @@ public class CrawlDbReader implements Closeable {
for (int j = i + 1; j < args.length; j++) {
if (args[j].equals("-format")) {
format = args[++j];
- i=i+2;
+ i = i + 2;
}
if (args[j].equals("-regex")) {
regex = args[++j];
- i=i+2;
+ i = i + 2;
}
if (args[j].equals("-retry")) {
retry = Integer.parseInt(args[++j]);
- i=i+2;
+ i = i + 2;
}
if (args[j].equals("-status")) {
status = args[++j];
- i=i+2;
+ i = i + 2;
}
}
dbr.processDumpJob(crawlDb, param, conf, format, regex, status, retry);
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
index bf4d8dd82..f189cc371 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
@@ -35,9 +35,11 @@ import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.scoring.ScoringFilters;
/** Merge new page entries with existing entries. */
-public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatum> {
- public static final Logger LOG = LoggerFactory.getLogger(CrawlDbReducer.class);
-
+public class CrawlDbReducer implements
+ Reducer<Text, CrawlDatum, Text, CrawlDatum> {
+ public static final Logger LOG = LoggerFactory
+ .getLogger(CrawlDbReducer.class);
+
private int retryMax;
private CrawlDatum result = new CrawlDatum();
private InlinkPriorityQueue linked = null;
@@ -50,17 +52,18 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
retryMax = job.getInt("db.fetch.retry.max", 3);
scfilters = new ScoringFilters(job);
additionsAllowed = job.getBoolean(CrawlDb.CRAWLDB_ADDITIONS_ALLOWED, true);
- maxInterval = job.getInt("db.fetch.interval.max", 0 );
+ maxInterval = job.getInt("db.fetch.interval.max", 0);
schedule = FetchScheduleFactory.getFetchSchedule(job);
int maxLinks = job.getInt("db.update.max.inlinks", 10000);
linked = new InlinkPriorityQueue(maxLinks);
}
- public void close() {}
+ public void close() {
+ }
public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
CrawlDatum fetch = new CrawlDatum();
CrawlDatum old = new CrawlDatum();
@@ -71,10 +74,11 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
boolean multiple = false; // avoid deep copy when only single value exists
linked.clear();
org.apache.hadoop.io.MapWritable metaFromParse = null;
-
+
while (values.hasNext()) {
CrawlDatum datum = values.next();
- if (!multiple && values.hasNext()) multiple = true;
+ if (!multiple && values.hasNext())
+ multiple = true;
if (CrawlDatum.hasDbStatus(datum)) {
if (!oldSet) {
if (multiple) {
@@ -86,7 +90,8 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
oldSet = true;
} else {
// always take the latest version
- if (old.getFetchTime() < datum.getFetchTime()) old.set(datum);
+ if (old.getFetchTime() < datum.getFetchTime())
+ old.set(datum);
}
continue;
}
@@ -101,12 +106,13 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
fetchSet = true;
} else {
// always take the latest version
- if (fetch.getFetchTime() < datum.getFetchTime()) fetch.set(datum);
+ if (fetch.getFetchTime() < datum.getFetchTime())
+ fetch.set(datum);
}
continue;
}
- switch (datum.getStatus()) { // collect other info
+ switch (datum.getStatus()) { // collect other info
case CrawlDatum.STATUS_LINKED:
CrawlDatum link;
if (multiple) {
@@ -127,7 +133,7 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
LOG.warn("Unknown status, key: " + key + ", datum: " + datum);
}
}
-
+
// copy the content of the queue into a List
// in reversed order
int numLinks = linked.size();
@@ -135,28 +141,31 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
for (int i = numLinks - 1; i >= 0; i--) {
linkList.add(linked.pop());
}
-
+
// if it doesn't already exist, skip it
- if (!oldSet && !additionsAllowed) return;
-
+ if (!oldSet && !additionsAllowed)
+ return;
+
// if there is no fetched datum, perhaps there is a link
if (!fetchSet && linkList.size() > 0) {
fetch = linkList.get(0);
fetchSet = true;
}
-
+
// still no new data - record only unchanged old data, if exists, and return
if (!fetchSet) {
if (oldSet) {// at this point at least "old" should be present
output.collect(key, old);
- reporter.getCounter("CrawlDB status", CrawlDatum.getStatusName(old.getStatus())).increment(1);
+ reporter.getCounter("CrawlDB status",
+ CrawlDatum.getStatusName(old.getStatus())).increment(1);
} else {
LOG.warn("Missing fetch and old value, signature=" + signature);
}
return;
}
-
- if (signature == null) signature = fetch.getSignature();
+
+ if (signature == null)
+ signature = fetch.getSignature();
long prevModifiedTime = oldSet ? old.getModifiedTime() : 0L;
long prevFetchTime = oldSet ? old.getFetchTime() : 0L;
@@ -175,12 +184,12 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
result.setModifiedTime(old.getModifiedTime());
}
}
-
- switch (fetch.getStatus()) { // determine new status
- case CrawlDatum.STATUS_LINKED: // it was link
- if (oldSet) { // if old exists
- result.set(old); // use it
+ switch (fetch.getStatus()) { // determine new status
+
+ case CrawlDatum.STATUS_LINKED: // it was link
+ if (oldSet) { // if old exists
+ result.set(old); // use it
} else {
result = schedule.initializeSchedule(key, result);
result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
@@ -188,18 +197,18 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
scfilters.initialScore(key, result);
} catch (ScoringFilterException e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Cannot filter init score for url " + key +
- ", using default: " + e.getMessage());
+ LOG.warn("Cannot filter init score for url " + key
+ + ", using default: " + e.getMessage());
}
result.setScore(0.0f);
}
}
break;
-
- case CrawlDatum.STATUS_FETCH_SUCCESS: // succesful fetch
- case CrawlDatum.STATUS_FETCH_REDIR_TEMP: // successful fetch, redirected
+
+ case CrawlDatum.STATUS_FETCH_SUCCESS: // succesful fetch
+ case CrawlDatum.STATUS_FETCH_REDIR_TEMP: // successful fetch, redirected
case CrawlDatum.STATUS_FETCH_REDIR_PERM:
- case CrawlDatum.STATUS_FETCH_NOTMODIFIED: // successful fetch, notmodified
+ case CrawlDatum.STATUS_FETCH_NOTMODIFIED: // successful fetch, notmodified
// determine the modification status
int modified = FetchSchedule.STATUS_UNKNOWN;
if (fetch.getStatus() == CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
@@ -217,15 +226,18 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
}
// set the schedule
result = schedule.setFetchSchedule(key, result, prevFetchTime,
- prevModifiedTime, fetch.getFetchTime(), fetch.getModifiedTime(), modified);
+ prevModifiedTime, fetch.getFetchTime(), fetch.getModifiedTime(),
+ modified);
// set the result status and signature
if (modified == FetchSchedule.STATUS_NOTMODIFIED) {
result.setStatus(CrawlDatum.STATUS_DB_NOTMODIFIED);
- // NUTCH-1341 The page is not modified according to its signature, let's reset lastModified as well
+ // NUTCH-1341 The page is not modified according to its signature, let's
+ // reset lastModified as well
result.setModifiedTime(prevModifiedTime);
- if (oldSet) result.setSignature(old.getSignature());
+ if (oldSet)
+ result.setSignature(old.getSignature());
} else {
switch (fetch.getStatus()) {
case CrawlDatum.STATUS_FETCH_SUCCESS:
@@ -238,9 +250,12 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
result.setStatus(CrawlDatum.STATUS_DB_REDIR_TEMP);
break;
default:
- LOG.warn("Unexpected status: " + fetch.getStatus() + " resetting to old status.");
- if (oldSet) result.setStatus(old.getStatus());
- else result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
+ LOG.warn("Unexpected status: " + fetch.getStatus()
+ + " resetting to old status.");
+ if (oldSet)
+ result.setStatus(old.getStatus());
+ else
+ result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
}
result.setSignature(signature);
}
@@ -262,11 +277,11 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
case CrawlDatum.STATUS_SIGNATURE:
if (LOG.isWarnEnabled()) {
LOG.warn("Lone CrawlDatum.STATUS_SIGNATURE: " + key);
- }
+ }
return;
- case CrawlDatum.STATUS_FETCH_RETRY: // temporary failure
+ case CrawlDatum.STATUS_FETCH_RETRY: // temporary failure
if (oldSet) {
- result.setSignature(old.getSignature()); // use old signature
+ result.setSignature(old.getSignature()); // use old signature
}
result = schedule.setPageRetrySchedule(key, result, prevFetchTime,
prevModifiedTime, fetch.getFetchTime());
@@ -275,20 +290,21 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
} else {
result.setStatus(CrawlDatum.STATUS_DB_GONE);
result = schedule.setPageGoneSchedule(key, result, prevFetchTime,
- prevModifiedTime, fetch.getFetchTime());
+ prevModifiedTime, fetch.getFetchTime());
}
break;
- case CrawlDatum.STATUS_FETCH_GONE: // permanent failure
+ case CrawlDatum.STATUS_FETCH_GONE: // permanent failure
if (oldSet)
- result.setSignature(old.getSignature()); // use old signature
+ result.setSignature(old.getSignature()); // use old signature
result.setStatus(CrawlDatum.STATUS_DB_GONE);
result = schedule.setPageGoneSchedule(key, result, prevFetchTime,
prevModifiedTime, fetch.getFetchTime());
break;
default:
- throw new RuntimeException("Unknown status: " + fetch.getStatus() + " " + key);
+ throw new RuntimeException("Unknown status: " + fetch.getStatus() + " "
+ + key);
}
try {
@@ -301,22 +317,23 @@ public class CrawlDbReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatu
// remove generation time, if any
result.getMetaData().remove(Nutch.WRITABLE_GENERATE_TIME_KEY);
output.collect(key, result);
- reporter.getCounter("CrawlDB status", CrawlDatum.getStatusName(result.getStatus())).increment(1);
+ reporter.getCounter("CrawlDB status",
+ CrawlDatum.getStatusName(result.getStatus())).increment(1);
}
-
+
}
class InlinkPriorityQueue extends PriorityQueue<CrawlDatum> {
-
+
public InlinkPriorityQueue(int maxSize) {
initialize(maxSize);
}
-
+
/** Determines the ordering of objects in this priority queue. **/
protected boolean lessThan(Object arg0, Object arg1) {
CrawlDatum candidate = (CrawlDatum) arg0;
CrawlDatum least = (CrawlDatum) arg1;
return candidate.getScore() > least.getScore();
}
-
+
}
diff --git a/src/java/org/apache/nutch/crawl/DeduplicationJob.java b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
index db62b8a9e..44680775e 100644
--- a/src/java/org/apache/nutch/crawl/DeduplicationJob.java
+++ b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
@@ -54,245 +54,244 @@ import org.slf4j.LoggerFactory;
* all of them as duplicate except the one with the highest score (based on the
* score in the crawldb, which is not necessarily the same as the score
* indexed). If two (or more) documents have the same score, then the document
- * with the latest timestamp is kept. If the documents have the same timestamp
- * then the one with the shortest URL is kept. The documents marked as duplicate can then
- * be deleted with the command CleaningJob.
+ * with the latest timestamp is kept. If the documents have the same timestamp
+ * then the one with the shortest URL is kept. The documents marked as duplicate
+ * can then be deleted with the command CleaningJob.
***/
public class DeduplicationJob extends Configured implements Tool {
- public static final Logger LOG = LoggerFactory
- .getLogger(DeduplicationJob.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(DeduplicationJob.class);
- private final static Text urlKey = new Text("_URLTEMPKEY_");
+ private final static Text urlKey = new Text("_URLTEMPKEY_");
- public static class DBFilter implements
- Mapper<Text, CrawlDatum, BytesWritable, CrawlDatum> {
+ public static class DBFilter implements
+ Mapper<Text, CrawlDatum, BytesWritable, CrawlDatum> {
- @Override
- public void configure(JobConf arg0) {
- }
+ @Override
+ public void configure(JobConf arg0) {
+ }
- @Override
- public void close() throws IOException {
- }
+ @Override
+ public void close() throws IOException {
+ }
- @Override
- public void map(Text key, CrawlDatum value,
- OutputCollector<BytesWritable, CrawlDatum> output,
- Reporter reporter) throws IOException {
-
- if (value.getStatus() == CrawlDatum.STATUS_DB_FETCHED
- || value.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
- // || value.getStatus() ==CrawlDatum.STATUS_DB_GONE){
- byte[] signature = value.getSignature();
- if (signature == null) return;
- BytesWritable sig = new BytesWritable(signature);
- // add the URL as a temporary MD
- value.getMetaData().put(urlKey, key);
- // reduce on the signature
- output.collect(sig, value);
- }
- }
+ @Override
+ public void map(Text key, CrawlDatum value,
+ OutputCollector<BytesWritable, CrawlDatum> output, Reporter reporter)
+ throws IOException {
+
+ if (value.getStatus() == CrawlDatum.STATUS_DB_FETCHED
+ || value.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
+ // || value.getStatus() ==CrawlDatum.STATUS_DB_GONE){
+ byte[] signature = value.getSignature();
+ if (signature == null)
+ return;
+ BytesWritable sig = new BytesWritable(signature);
+ // add the URL as a temporary MD
+ value.getMetaData().put(urlKey, key);
+ // reduce on the signature
+ output.collect(sig, value);
+ }
+ }
+ }
+
+ public static class DedupReducer implements
+ Reducer<BytesWritable, CrawlDatum, Text, CrawlDatum> {
+
+ private void writeOutAsDuplicate(CrawlDatum datum,
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
+ datum.setStatus(CrawlDatum.STATUS_DB_DUPLICATE);
+ Text key = (Text) datum.getMetaData().remove(urlKey);
+ reporter.incrCounter("DeduplicationJobStatus",
+ "Documents marked as duplicate", 1);
+ output.collect(key, datum);
}
- public static class DedupReducer implements
- Reducer<BytesWritable, CrawlDatum, Text, CrawlDatum> {
-
- private void writeOutAsDuplicate(CrawlDatum datum,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- datum.setStatus(CrawlDatum.STATUS_DB_DUPLICATE);
- Text key = (Text) datum.getMetaData().remove(urlKey);
- reporter.incrCounter("DeduplicationJobStatus",
- "Documents marked as duplicate", 1);
- output.collect(key, datum);
+ @Override
+ public void reduce(BytesWritable key, Iterator<CrawlDatum> values,
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
+ CrawlDatum existingDoc = null;
+
+ while (values.hasNext()) {
+ if (existingDoc == null) {
+ existingDoc = new CrawlDatum();
+ existingDoc.set(values.next());
+ continue;
}
-
- @Override
- public void reduce(BytesWritable key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- CrawlDatum existingDoc = null;
-
- while (values.hasNext()) {
- if (existingDoc == null) {
- existingDoc = new CrawlDatum();
- existingDoc.set(values.next());
- continue;
- }
- CrawlDatum newDoc = values.next();
- // compare based on score
- if (existingDoc.getScore() < newDoc.getScore()) {
- writeOutAsDuplicate(existingDoc, output, reporter);
- existingDoc = new CrawlDatum();
- existingDoc.set(newDoc);
- continue;
- } else if (existingDoc.getScore() > newDoc.getScore()) {
- // mark new one as duplicate
- writeOutAsDuplicate(newDoc, output, reporter);
- continue;
- }
- // same score? delete the one which is oldest
- if (existingDoc.getFetchTime() > newDoc.getFetchTime()) {
- // mark new one as duplicate
- writeOutAsDuplicate(newDoc, output, reporter);
- continue;
- } else if (existingDoc.getFetchTime() < newDoc.getFetchTime()) {
- // mark existing one as duplicate
- writeOutAsDuplicate(existingDoc, output, reporter);
- existingDoc = new CrawlDatum();
- existingDoc.set(newDoc);
- continue;
- }
- // same time? keep the one which has the shortest URL
- String urlExisting = existingDoc.getMetaData().get(urlKey).toString();
- String urlnewDoc = newDoc.getMetaData().get(urlKey).toString();
- if (urlExisting.length()<urlnewDoc.length()){
- // mark new one as duplicate
- writeOutAsDuplicate(newDoc, output, reporter);
- continue;
- }
- else if (urlExisting.length()>urlnewDoc.length()){
- // mark existing one as duplicate
- writeOutAsDuplicate(existingDoc, output, reporter);
- existingDoc = new CrawlDatum();
- existingDoc.set(newDoc);
- continue;
- }
- }
+ CrawlDatum newDoc = values.next();
+ // compare based on score
+ if (existingDoc.getScore() < newDoc.getScore()) {
+ writeOutAsDuplicate(existingDoc, output, reporter);
+ existingDoc = new CrawlDatum();
+ existingDoc.set(newDoc);
+ continue;
+ } else if (existingDoc.getScore() > newDoc.getScore()) {
+ // mark new one as duplicate
+ writeOutAsDuplicate(newDoc, output, reporter);
+ continue;
}
-
- @Override
- public void configure(JobConf arg0) {
+ // same score? delete the one which is oldest
+ if (existingDoc.getFetchTime() > newDoc.getFetchTime()) {
+ // mark new one as duplicate
+ writeOutAsDuplicate(newDoc, output, reporter);
+ continue;
+ } else if (existingDoc.getFetchTime() < newDoc.getFetchTime()) {
+ // mark existing one as duplicate
+ writeOutAsDuplicate(existingDoc, output, reporter);
+ existingDoc = new CrawlDatum();
+ existingDoc.set(newDoc);
+ continue;
}
-
- @Override
- public void close() throws IOException {
-
+ // same time? keep the one which has the shortest URL
+ String urlExisting = existingDoc.getMetaData().get(urlKey).toString();
+ String urlnewDoc = newDoc.getMetaData().get(urlKey).toString();
+ if (urlExisting.length() < urlnewDoc.length()) {
+ // mark new one as duplicate
+ writeOutAsDuplicate(newDoc, output, reporter);
+ continue;
+ } else if (urlExisting.length() > urlnewDoc.length()) {
+ // mark existing one as duplicate
+ writeOutAsDuplicate(existingDoc, output, reporter);
+ existingDoc = new CrawlDatum();
+ existingDoc.set(newDoc);
+ continue;
}
+ }
}
- /** Combine multiple new entries for a url. */
- public static class StatusUpdateReducer implements
- Reducer<Text, CrawlDatum, Text, CrawlDatum> {
+ @Override
+ public void configure(JobConf arg0) {
+ }
- public void configure(JobConf job) {
- }
+ @Override
+ public void close() throws IOException {
- public void close() {
- }
+ }
+ }
- private CrawlDatum old = new CrawlDatum();
- private CrawlDatum duplicate = new CrawlDatum();
-
- public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- boolean duplicateSet = false;
-
- while (values.hasNext()) {
- CrawlDatum val = values.next();
- if (val.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
- duplicate.set(val);
- duplicateSet = true;
- } else {
- old.set(val);
- }
- }
-
- // keep the duplicate if there is one
- if (duplicateSet) {
- output.collect(key, duplicate);
- return;
- }
-
- // no duplicate? keep old one then
- output.collect(key, old);
- }
+ /** Combine multiple new entries for a url. */
+ public static class StatusUpdateReducer implements
+ Reducer<Text, CrawlDatum, Text, CrawlDatum> {
+
+ public void configure(JobConf job) {
}
- public int run(String[] args) throws IOException {
- if (args.length < 1) {
- System.err.println("Usage: DeduplicationJob <crawldb>");
- return 1;
+ public void close() {
+ }
+
+ private CrawlDatum old = new CrawlDatum();
+ private CrawlDatum duplicate = new CrawlDatum();
+
+ public void reduce(Text key, Iterator<CrawlDatum> values,
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
+ boolean duplicateSet = false;
+
+ while (values.hasNext()) {
+ CrawlDatum val = values.next();
+ if (val.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
+ duplicate.set(val);
+ duplicateSet = true;
+ } else {
+ old.set(val);
}
+ }
- String crawldb = args[0];
+ // keep the duplicate if there is one
+ if (duplicateSet) {
+ output.collect(key, duplicate);
+ return;
+ }
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- long start = System.currentTimeMillis();
- LOG.info("DeduplicationJob: starting at " + sdf.format(start));
+ // no duplicate? keep old one then
+ output.collect(key, old);
+ }
+ }
- Path tempDir = new Path(getConf().get("mapred.temp.dir", ".")
- + "/dedup-temp-"
- + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ public int run(String[] args) throws IOException {
+ if (args.length < 1) {
+ System.err.println("Usage: DeduplicationJob <crawldb>");
+ return 1;
+ }
- JobConf job = new NutchJob(getConf());
-
- job.setJobName("Deduplication on "+crawldb);
+ String crawldb = args[0];
- FileInputFormat.addInputPath(job, new Path(crawldb,
- CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ long start = System.currentTimeMillis();
+ LOG.info("DeduplicationJob: starting at " + sdf.format(start));
- FileOutputFormat.setOutputPath(job, tempDir);
- job.setOutputFormat(SequenceFileOutputFormat.class);
+ Path tempDir = new Path(getConf().get("mapred.temp.dir", ".")
+ + "/dedup-temp-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- job.setMapOutputKeyClass(BytesWritable.class);
- job.setMapOutputValueClass(CrawlDatum.class);
+ JobConf job = new NutchJob(getConf());
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(CrawlDatum.class);
+ job.setJobName("Deduplication on " + crawldb);
- job.setMapperClass(DBFilter.class);
- job.setReducerClass(DedupReducer.class);
+ FileInputFormat.addInputPath(job, new Path(crawldb, CrawlDb.CURRENT_NAME));
+ job.setInputFormat(SequenceFileInputFormat.class);
- try {
- RunningJob rj = JobClient.runJob(job);
- Group g = rj.getCounters().getGroup("DeduplicationJobStatus");
- if (g != null){
- long dups = g.getCounter("Documents marked as duplicate");
- LOG.info("Deduplication: "+(int)dups+" documents marked as duplicates");
- }
- } catch (final Exception e) {
- LOG.error("DeduplicationJob: " + StringUtils.stringifyException(e));
- return -1;
- }
-
- // merge with existing crawl db
- if (LOG.isInfoEnabled()) {
- LOG.info("Deduplication: Updating status of duplicate urls into crawl db.");
- }
+ FileOutputFormat.setOutputPath(job, tempDir);
+ job.setOutputFormat(SequenceFileOutputFormat.class);
- Path dbPath = new Path(crawldb);
- JobConf mergeJob = CrawlDb.createJob(getConf(), dbPath);
- FileInputFormat.addInputPath(mergeJob, tempDir);
- mergeJob.setReducerClass(StatusUpdateReducer.class);
-
- try {
- JobClient.runJob(mergeJob);
- } catch (final Exception e) {
- LOG.error("DeduplicationMergeJob: "
- + StringUtils.stringifyException(e));
- return -1;
- }
+ job.setMapOutputKeyClass(BytesWritable.class);
+ job.setMapOutputValueClass(CrawlDatum.class);
- CrawlDb.install(mergeJob, dbPath);
+ job.setOutputKeyClass(Text.class);
+ job.setOutputValueClass(CrawlDatum.class);
- // clean up
- FileSystem fs = FileSystem.get(getConf());
- fs.delete(tempDir, true);
-
- long end = System.currentTimeMillis();
- LOG.info("Deduplication finished at " + sdf.format(end)
- + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ job.setMapperClass(DBFilter.class);
+ job.setReducerClass(DedupReducer.class);
- return 0;
+ try {
+ RunningJob rj = JobClient.runJob(job);
+ Group g = rj.getCounters().getGroup("DeduplicationJobStatus");
+ if (g != null) {
+ long dups = g.getCounter("Documents marked as duplicate");
+ LOG.info("Deduplication: " + (int) dups
+ + " documents marked as duplicates");
+ }
+ } catch (final Exception e) {
+ LOG.error("DeduplicationJob: " + StringUtils.stringifyException(e));
+ return -1;
}
- public static void main(String[] args) throws Exception {
- int result = ToolRunner.run(NutchConfiguration.create(),
- new DeduplicationJob(), args);
- System.exit(result);
+ // merge with existing crawl db
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Deduplication: Updating status of duplicate urls into crawl db.");
}
+
+ Path dbPath = new Path(crawldb);
+ JobConf mergeJob = CrawlDb.createJob(getConf(), dbPath);
+ FileInputFormat.addInputPath(mergeJob, tempDir);
+ mergeJob.setReducerClass(StatusUpdateReducer.class);
+
+ try {
+ JobClient.runJob(mergeJob);
+ } catch (final Exception e) {
+ LOG.error("DeduplicationMergeJob: " + StringUtils.stringifyException(e));
+ return -1;
+ }
+
+ CrawlDb.install(mergeJob, dbPath);
+
+ // clean up
+ FileSystem fs = FileSystem.get(getConf());
+ fs.delete(tempDir, true);
+
+ long end = System.currentTimeMillis();
+ LOG.info("Deduplication finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
+
+ return 0;
+ }
+
+ public static void main(String[] args) throws Exception {
+ int result = ToolRunner.run(NutchConfiguration.create(),
+ new DeduplicationJob(), args);
+ System.exit(result);
+ }
}
diff --git a/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java b/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java
index 9419c44c6..4a60a1c92 100755
--- a/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/DefaultFetchSchedule.java
@@ -20,8 +20,8 @@ package org.apache.nutch.crawl;
import org.apache.hadoop.io.Text;
/**
- * This class implements the default re-fetch schedule. That is, no matter
- * if the page was changed or not, the <code>fetchInterval</code> remains
+ * This class implements the default re-fetch schedule. That is, no matter if
+ * the page was changed or not, the <code>fetchInterval</code> remains
* unchanged, and the updated page fetchTime will always be set to
* <code>fetchTime + fetchInterval * 1000</code>.
*
@@ -31,14 +31,14 @@ public class DefaultFetchSchedule extends AbstractFetchSchedule {
@Override
public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime,
- long fetchTime, long modifiedTime, int state) {
+ long prevFetchTime, long prevModifiedTime, long fetchTime,
+ long modifiedTime, int state) {
datum = super.setFetchSchedule(url, datum, prevFetchTime, prevModifiedTime,
fetchTime, modifiedTime, state);
- if (datum.getFetchInterval() == 0 ) {
+ if (datum.getFetchInterval() == 0) {
datum.setFetchInterval(defaultInterval);
}
- datum.setFetchTime(fetchTime + (long)datum.getFetchInterval() * 1000);
+ datum.setFetchTime(fetchTime + (long) datum.getFetchInterval() * 1000);
datum.setModifiedTime(modifiedTime);
return datum;
}
diff --git a/src/java/org/apache/nutch/crawl/FetchSchedule.java b/src/java/org/apache/nutch/crawl/FetchSchedule.java
index 84df23580..10ee185a4 100755
--- a/src/java/org/apache/nutch/crawl/FetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/FetchSchedule.java
@@ -21,160 +21,188 @@ import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.io.Text;
/**
- * This interface defines the contract for implementations that manipulate
- * fetch times and re-fetch intervals.
+ * This interface defines the contract for implementations that manipulate fetch
+ * times and re-fetch intervals.
*
* @author Andrzej Bialecki
*/
public interface FetchSchedule extends Configurable {
-
+
/** It is unknown whether page was changed since our last visit. */
- public static final int STATUS_UNKNOWN = 0;
+ public static final int STATUS_UNKNOWN = 0;
/** Page is known to have been modified since our last visit. */
- public static final int STATUS_MODIFIED = 1;
+ public static final int STATUS_MODIFIED = 1;
/** Page is known to remain unmodified since our last visit. */
- public static final int STATUS_NOTMODIFIED = 2;
-
+ public static final int STATUS_NOTMODIFIED = 2;
+
public static final int SECONDS_PER_DAY = 3600 * 24;
+
/**
- * Initialize fetch schedule related data. Implementations should at least
- * set the <code>fetchTime</code> and <code>fetchInterval</code>. The default
- * implementation set the <code>fetchTime</code> to now, using the
- * default <code>fetchInterval</code>.
- *
- * @param url URL of the page.
- *
- * @param datum datum instance to be initialized.
- *
+ * Initialize fetch schedule related data. Implementations should at least set
+ * the <code>fetchTime</code> and <code>fetchInterval</code>. The default
+ * implementation set the <code>fetchTime</code> to now, using the default
+ * <code>fetchInterval</code>.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * datum instance to be initialized.
+ *
* @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than @see CrawlDatum, but
- * implementations should make sure that it contains at least all
- * information from @see CrawlDatum.
+ * NOTE: this may be a different instance than @see CrawlDatum, but
+ * implementations should make sure that it contains at least all
+ * information from @see CrawlDatum.
*/
public CrawlDatum initializeSchedule(Text url, CrawlDatum datum);
-
+
/**
* Sets the <code>fetchInterval</code> and <code>fetchTime</code> on a
- * successfully fetched page.
- * Implementations may use supplied arguments to support different re-fetching
- * schedules.
- *
- * @param url url of the page
- *
- * @param datum page description to be adjusted. NOTE: this instance, passed by reference,
- * may be modified inside the method.
- *
- * @param prevFetchTime previous value of fetch time, or 0 if not available.
- *
- * @param prevModifiedTime previous value of modifiedTime, or 0 if not available.
- *
- * @param fetchTime the latest time, when the page was recently re-fetched. Most FetchSchedule
- * implementations should update the value in @see CrawlDatum to something greater than this value.
- *
- * @param modifiedTime last time the content was modified. This information comes from
- * the protocol implementations, or is set to < 0 if not available. Most FetchSchedule
- * implementations should update the value in @see CrawlDatum to this value.
- *
- * @param state if {@link #STATUS_MODIFIED}, then the content is considered to be "changed" before the
- * <code>fetchTime</code>, if {@link #STATUS_NOTMODIFIED} then the content is known to be unchanged.
- * This information may be obtained by comparing page signatures before and after fetching. If this
- * is set to {@link #STATUS_UNKNOWN}, then it is unknown whether the page was changed; implementations
- * are free to follow a sensible default behavior.
- *
- * @return adjusted page information, including all original information. NOTE: this may
- * be a different instance than @see CrawlDatum, but implementations should make sure that
- * it contains at least all information from @see CrawlDatum}.
+ * successfully fetched page. Implementations may use supplied arguments to
+ * support different re-fetching schedules.
+ *
+ * @param url
+ * url of the page
+ *
+ * @param datum
+ * page description to be adjusted. NOTE: this instance, passed by
+ * reference, may be modified inside the method.
+ *
+ * @param prevFetchTime
+ * previous value of fetch time, or 0 if not available.
+ *
+ * @param prevModifiedTime
+ * previous value of modifiedTime, or 0 if not available.
+ *
+ * @param fetchTime
+ * the latest time, when the page was recently re-fetched. Most
+ * FetchSchedule implementations should update the value in @see
+ * CrawlDatum to something greater than this value.
+ *
+ * @param modifiedTime
+ * last time the content was modified. This information comes from
+ * the protocol implementations, or is set to < 0 if not available.
+ * Most FetchSchedule implementations should update the value in @see
+ * CrawlDatum to this value.
+ *
+ * @param state
+ * if {@link #STATUS_MODIFIED}, then the content is considered to be
+ * "changed" before the <code>fetchTime</code>, if
+ * {@link #STATUS_NOTMODIFIED} then the content is known to be
+ * unchanged. This information may be obtained by comparing page
+ * signatures before and after fetching. If this is set to
+ * {@link #STATUS_UNKNOWN}, then it is unknown whether the page was
+ * changed; implementations are free to follow a sensible default
+ * behavior.
+ *
+ * @return adjusted page information, including all original information.
+ * NOTE: this may be a different instance than @see CrawlDatum, but
+ * implementations should make sure that it contains at least all
+ * information from @see CrawlDatum}.
*/
public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime,
- long fetchTime, long modifiedTime, int state);
-
+ long prevFetchTime, long prevModifiedTime, long fetchTime,
+ long modifiedTime, int state);
+
/**
- * This method specifies how to schedule refetching of pages
- * marked as GONE. Default implementation increases fetchInterval by 50%,
- * and if it exceeds the <code>maxInterval</code> it calls
+ * This method specifies how to schedule refetching of pages marked as GONE.
+ * Default implementation increases fetchInterval by 50%, and if it exceeds
+ * the <code>maxInterval</code> it calls
* {@link #forceRefetch(Text, CrawlDatum, boolean)}.
- *
- * @param url URL of the page
- *
- * @param datum datum instance to be adjusted.
- *
+ *
+ * @param url
+ * URL of the page
+ *
+ * @param datum
+ * datum instance to be adjusted.
+ *
* @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than @see CrawlDatum, but
- * implementations should make sure that it contains at least all
- * information from @see CrawlDatum.
+ * NOTE: this may be a different instance than @see CrawlDatum, but
+ * implementations should make sure that it contains at least all
+ * information from @see CrawlDatum.
*/
public CrawlDatum setPageGoneSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime, long fetchTime);
-
+ long prevFetchTime, long prevModifiedTime, long fetchTime);
+
/**
- * This method adjusts the fetch schedule if fetching needs to be
- * re-tried due to transient errors. The default implementation
- * sets the next fetch time 1 day in the future and increases the
- * retry counter.
- *
- * @param url URL of the page.
- *
- * @param datum page information.
- *
- * @param prevFetchTime previous fetch time.
- *
- * @param prevModifiedTime previous modified time.
- *
- * @param fetchTime current fetch time.
- *
+ * This method adjusts the fetch schedule if fetching needs to be re-tried due
+ * to transient errors. The default implementation sets the next fetch time 1
+ * day in the future and increases the retry counter.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * page information.
+ *
+ * @param prevFetchTime
+ * previous fetch time.
+ *
+ * @param prevModifiedTime
+ * previous modified time.
+ *
+ * @param fetchTime
+ * current fetch time.
+ *
* @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than @see CrawlDatum, but
- * implementations should make sure that it contains at least all
- * information from @see CrawlDatum.
+ * NOTE: this may be a different instance than @see CrawlDatum, but
+ * implementations should make sure that it contains at least all
+ * information from @see CrawlDatum.
*/
public CrawlDatum setPageRetrySchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime, long fetchTime);
-
+ long prevFetchTime, long prevModifiedTime, long fetchTime);
+
/**
* Calculates last fetch time of the given CrawlDatum.
+ *
* @return the date as a long.
*/
public long calculateLastFetchTime(CrawlDatum datum);
/**
- * This method provides information whether the page is suitable for
- * selection in the current fetchlist. NOTE: a true return value does not
- * guarantee that the page will be fetched, it just allows it to be
- * included in the further selection process based on scores. The default
- * implementation checks <code>fetchTime</code>, if it is higher than the
- * curTime it returns false, and true otherwise. It will also
- * check that fetchTime is not too remote (more than <code>maxInterval</code),
- * in which case it lowers the interval and returns true.
- *
- * @param url URL of the page.
- *
- * @param datum datum instance.
- *
- * @param curTime reference time (usually set to the time when the
- * fetchlist generation process was started).
- *
+ * This method provides information whether the page is suitable for selection
+ * in the current fetchlist. NOTE: a true return value does not guarantee that
+ * the page will be fetched, it just allows it to be included in the further
+ * selection process based on scores. The default implementation checks
+ * <code>fetchTime</code>, if it is higher than the curTime it returns false,
+ * and true otherwise. It will also check that fetchTime is not too remote
+ * (more than <code>maxInterval</code), in which case it lowers the interval
+ * and returns true.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * datum instance.
+ *
+ * @param curTime
+ * reference time (usually set to the time when the fetchlist
+ * generation process was started).
+ *
* @return true, if the page should be considered for inclusion in the current
- * fetchlist, otherwise false.
+ * fetchlist, otherwise false.
*/
public boolean shouldFetch(Text url, CrawlDatum datum, long curTime);
-
+
/**
- * This method resets fetchTime, fetchInterval, modifiedTime and
- * page signature, so that it forces refetching.
- *
- * @param url URL of the page.
- *
- * @param datum datum instance.
- *
- * @param asap if true, force refetch as soon as possible - this sets
- * the fetchTime to now. If false, force refetch whenever the next fetch
- * time is set.
- *
+ * This method resets fetchTime, fetchInterval, modifiedTime and page
+ * signature, so that it forces refetching.
+ *
+ * @param url
+ * URL of the page.
+ *
+ * @param datum
+ * datum instance.
+ *
+ * @param asap
+ * if true, force refetch as soon as possible - this sets the
+ * fetchTime to now. If false, force refetch whenever the next fetch
+ * time is set.
+ *
* @return adjusted page information, including all original information.
- * NOTE: this may be a different instance than @see CrawlDatum, but
- * implementations should make sure that it contains at least all
- * information from @see CrawlDatum.
+ * NOTE: this may be a different instance than @see CrawlDatum, but
+ * implementations should make sure that it contains at least all
+ * information from @see CrawlDatum.
*/
public CrawlDatum forceRefetch(Text url, CrawlDatum datum, boolean asap);
}
diff --git a/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java b/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
index 0657c37ac..7a845246f 100755
--- a/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
+++ b/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
@@ -25,20 +25,23 @@ import org.apache.nutch.util.ObjectCache;
/** Creates and caches a {@link FetchSchedule} implementation. */
public class FetchScheduleFactory {
- public static final Logger LOG = LoggerFactory.getLogger(FetchScheduleFactory.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(FetchScheduleFactory.class);
- private FetchScheduleFactory() {} // no public ctor
+ private FetchScheduleFactory() {
+ } // no public ctor
/** Return the FetchSchedule implementation. */
public synchronized static FetchSchedule getFetchSchedule(Configuration conf) {
- String clazz = conf.get("db.fetch.schedule.class", DefaultFetchSchedule.class.getName());
+ String clazz = conf.get("db.fetch.schedule.class",
+ DefaultFetchSchedule.class.getName());
ObjectCache objectCache = ObjectCache.get(conf);
- FetchSchedule impl = (FetchSchedule)objectCache.getObject(clazz);
+ FetchSchedule impl = (FetchSchedule) objectCache.getObject(clazz);
if (impl == null) {
try {
LOG.info("Using FetchSchedule impl: " + clazz);
Class<?> implClass = Class.forName(clazz);
- impl = (FetchSchedule)implClass.newInstance();
+ impl = (FetchSchedule) implClass.newInstance();
impl.setConf(conf);
objectCache.setObject(clazz, impl);
} catch (Exception e) {
diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.java
index 3cc45c685..9fc9d9840 100644
--- a/src/java/org/apache/nutch/crawl/Generator.java
+++ b/src/java/org/apache/nutch/crawl/Generator.java
@@ -51,9 +51,9 @@ import org.apache.nutch.util.URLUtil;
* Generates a subset of a crawl db to fetch. This version allows to generate
* fetchlists for several segments in one go. Unlike in the initial version
* (OldGenerator), the IP resolution is done ONLY on the entries which have been
- * selected for fetching. The URLs are partitioned by IP, domain or host within a
- * segment. We can chose separately how to count the URLS i.e. by domain or host
- * to limit the entries.
+ * selected for fetching. The URLs are partitioned by IP, domain or host within
+ * a segment. We can chose separately how to count the URLS i.e. by domain or
+ * host to limit the entries.
**/
public class Generator extends Configured implements Tool {
@@ -73,7 +73,7 @@ public class Generator extends Configured implements Tool {
public static final String GENERATOR_CUR_TIME = "generate.curTime";
public static final String GENERATOR_DELAY = "crawl.gen.delay";
public static final String GENERATOR_MAX_NUM_SEGMENTS = "generate.max.num.segments";
-
+
public static class SelectorEntry implements Writable {
public Text url;
public CrawlDatum datum;
@@ -98,25 +98,25 @@ public class Generator extends Configured implements Tool {
}
public String toString() {
- return "url=" + url.toString() + ", datum=" + datum.toString() + ", segnum="
- + segnum.toString();
+ return "url=" + url.toString() + ", datum=" + datum.toString()
+ + ", segnum=" + segnum.toString();
}
}
/** Selects entries due for fetch. */
public static class Selector implements
- Mapper<Text,CrawlDatum,FloatWritable,SelectorEntry>,
- Partitioner<FloatWritable,Writable>,
- Reducer<FloatWritable,SelectorEntry,FloatWritable,SelectorEntry> {
+ Mapper<Text, CrawlDatum, FloatWritable, SelectorEntry>,
+ Partitioner<FloatWritable, Writable>,
+ Reducer<FloatWritable, SelectorEntry, FloatWritable, SelectorEntry> {
private LongWritable genTime = new LongWritable(System.currentTimeMillis());
private long curTime;
private long limit;
private long count;
- private HashMap<String,int[]> hostCounts = new HashMap<String,int[]>();
+ private HashMap<String, int[]> hostCounts = new HashMap<String, int[]>();
private int segCounts[];
private int maxCount;
private boolean byDomain = false;
- private Partitioner<Text,Writable> partitioner = new URLPartitioner();
+ private Partitioner<Text, Writable> partitioner = new URLPartitioner();
private URLFilters filters;
private URLNormalizers normalizers;
private ScoringFilters scfilters;
@@ -134,22 +134,26 @@ public class Generator extends Configured implements Tool {
public void configure(JobConf job) {
curTime = job.getLong(GENERATOR_CUR_TIME, System.currentTimeMillis());
- limit = job.getLong(GENERATOR_TOP_N, Long.MAX_VALUE) / job.getNumReduceTasks();
+ limit = job.getLong(GENERATOR_TOP_N, Long.MAX_VALUE)
+ / job.getNumReduceTasks();
maxCount = job.getInt(GENERATOR_MAX_COUNT, -1);
- if (maxCount==-1){
+ if (maxCount == -1) {
byDomain = false;
}
- if (GENERATOR_COUNT_VALUE_DOMAIN.equals(job.get(GENERATOR_COUNT_MODE))) byDomain = true;
+ if (GENERATOR_COUNT_VALUE_DOMAIN.equals(job.get(GENERATOR_COUNT_MODE)))
+ byDomain = true;
filters = new URLFilters(job);
normalise = job.getBoolean(GENERATOR_NORMALISE, true);
- if (normalise) normalizers = new URLNormalizers(job,
- URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
+ if (normalise)
+ normalizers = new URLNormalizers(job,
+ URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
scfilters = new ScoringFilters(job);
partitioner.configure(job);
filter = job.getBoolean(GENERATOR_FILTER, true);
genDelay = job.getLong(GENERATOR_DELAY, 7L) * 3600L * 24L * 1000L;
long time = job.getLong(Nutch.GENERATE_TIME_KEY, 0L);
- if (time > 0) genTime.set(time);
+ if (time > 0)
+ genTime.set(time);
schedule = FetchScheduleFactory.getFetchSchedule(job);
scoreThreshold = job.getFloat(GENERATOR_MIN_SCORE, Float.NaN);
intervalThreshold = job.getInt(GENERATOR_MIN_INTERVAL, -1);
@@ -158,21 +162,24 @@ public class Generator extends Configured implements Tool {
segCounts = new int[maxNumSegments];
}
- public void close() {}
+ public void close() {
+ }
/** Select & invert subset due for fetch. */
public void map(Text key, CrawlDatum value,
- OutputCollector<FloatWritable,SelectorEntry> output, Reporter reporter)
+ OutputCollector<FloatWritable, SelectorEntry> output, Reporter reporter)
throws IOException {
Text url = key;
if (filter) {
// If filtering is on don't generate URLs that don't pass
// URLFilters
try {
- if (filters.filter(url.toString()) == null) return;
+ if (filters.filter(url.toString()) == null)
+ return;
} catch (URLFilterException e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't filter url: " + url + " (" + e.getMessage() + ")");
+ LOG.warn("Couldn't filter url: " + url + " (" + e.getMessage()
+ + ")");
}
}
}
@@ -189,8 +196,8 @@ public class Generator extends Configured implements Tool {
Nutch.WRITABLE_GENERATE_TIME_KEY);
if (oldGenTime != null) { // awaiting fetch & update
if (oldGenTime.get() + genDelay > curTime) // still wait for
- // update
- return;
+ // update
+ return;
}
float sort = 1.0f;
try {
@@ -202,13 +209,19 @@ public class Generator extends Configured implements Tool {
}
if (restrictStatus != null
- && !restrictStatus.equalsIgnoreCase(CrawlDatum.getStatusName(crawlDatum.getStatus()))) return;
+ && !restrictStatus.equalsIgnoreCase(CrawlDatum
+ .getStatusName(crawlDatum.getStatus())))
+ return;
// consider only entries with a score superior to the threshold
- if (scoreThreshold != Float.NaN && sort < scoreThreshold) return;
+ if (scoreThreshold != Float.NaN && sort < scoreThreshold)
+ return;
- // consider only entries with a retry (or fetch) interval lower than threshold
- if (intervalThreshold != -1 && crawlDatum.getFetchInterval() > intervalThreshold) return;
+ // consider only entries with a retry (or fetch) interval lower than
+ // threshold
+ if (intervalThreshold != -1
+ && crawlDatum.getFetchInterval() > intervalThreshold)
+ return;
// sort by decreasing score, using DecreasingFloatComparator
sortValue.set(sort);
@@ -220,13 +233,15 @@ public class Generator extends Configured implements Tool {
}
/** Partition by host / domain or IP. */
- public int getPartition(FloatWritable key, Writable value, int numReduceTasks) {
- return partitioner.getPartition(((SelectorEntry) value).url, key, numReduceTasks);
+ public int getPartition(FloatWritable key, Writable value,
+ int numReduceTasks) {
+ return partitioner.getPartition(((SelectorEntry) value).url, key,
+ numReduceTasks);
}
/** Collect until limit is reached. */
public void reduce(FloatWritable key, Iterator<SelectorEntry> values,
- OutputCollector<FloatWritable,SelectorEntry> output, Reporter reporter)
+ OutputCollector<FloatWritable, SelectorEntry> output, Reporter reporter)
throws IOException {
while (values.hasNext()) {
@@ -236,7 +251,8 @@ public class Generator extends Configured implements Tool {
if (currentsegmentnum < maxNumSegments) {
count = 0;
currentsegmentnum++;
- } else break;
+ } else
+ break;
}
SelectorEntry entry = values.next();
@@ -270,7 +286,7 @@ public class Generator extends Configured implements Tool {
if (maxCount > 0) {
int[] hostCount = hostCounts.get(hostordomain);
if (hostCount == null) {
- hostCount = new int[] {1, 0};
+ hostCount = new int[] { 1, 0 };
hostCounts.put(hostordomain, hostCount);
}
@@ -278,7 +294,8 @@ public class Generator extends Configured implements Tool {
hostCount[1]++;
// check if topN reached, select next segment if it is
- while (segCounts[hostCount[0]-1] >= limit && hostCount[0] < maxNumSegments) {
+ while (segCounts[hostCount[0] - 1] >= limit
+ && hostCount[0] < maxNumSegments) {
hostCount[0]++;
hostCount[1] = 0;
}
@@ -291,18 +308,23 @@ public class Generator extends Configured implements Tool {
hostCount[1] = 0;
} else {
if (hostCount[1] == maxCount + 1 && LOG.isInfoEnabled()) {
- LOG.info("Host or domain " + hostordomain + " has more than " + maxCount
- + " URLs for all " + maxNumSegments + " segments. Additional URLs won't be included in the fetchlist.");
+ LOG.info("Host or domain "
+ + hostordomain
+ + " has more than "
+ + maxCount
+ + " URLs for all "
+ + maxNumSegments
+ + " segments. Additional URLs won't be included in the fetchlist.");
}
// skip this entry
continue;
}
}
entry.segnum = new IntWritable(hostCount[0]);
- segCounts[hostCount[0]-1]++;
+ segCounts[hostCount[0] - 1]++;
} else {
entry.segnum = new IntWritable(currentsegmentnum);
- segCounts[currentsegmentnum-1]++;
+ segCounts[currentsegmentnum - 1]++;
}
output.collect(key, entry);
@@ -316,16 +338,17 @@ public class Generator extends Configured implements Tool {
// Allows the reducers to generate one subfile per
public static class GeneratorOutputFormat extends
- MultipleSequenceFileOutputFormat<FloatWritable,SelectorEntry> {
+ MultipleSequenceFileOutputFormat<FloatWritable, SelectorEntry> {
// generate a filename based on the segnum stored for this entry
- protected String generateFileNameForKeyValue(FloatWritable key, SelectorEntry value,
- String name) {
+ protected String generateFileNameForKeyValue(FloatWritable key,
+ SelectorEntry value, String name) {
return "fetchlist-" + value.segnum.toString() + "/" + name;
}
}
- public static class DecreasingFloatComparator extends FloatWritable.Comparator {
+ public static class DecreasingFloatComparator extends
+ FloatWritable.Comparator {
/** Compares two FloatWritables decreasing. */
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
@@ -334,20 +357,22 @@ public class Generator extends Configured implements Tool {
}
public static class SelectorInverseMapper extends MapReduceBase implements
- Mapper<FloatWritable,SelectorEntry,Text,SelectorEntry> {
+ Mapper<FloatWritable, SelectorEntry, Text, SelectorEntry> {
public void map(FloatWritable key, SelectorEntry value,
- OutputCollector<Text,SelectorEntry> output, Reporter reporter) throws IOException {
+ OutputCollector<Text, SelectorEntry> output, Reporter reporter)
+ throws IOException {
SelectorEntry entry = value;
output.collect(entry.url, entry);
}
}
public static class PartitionReducer extends MapReduceBase implements
- Reducer<Text,SelectorEntry,Text,CrawlDatum> {
+ Reducer<Text, SelectorEntry, Text, CrawlDatum> {
public void reduce(Text key, Iterator<SelectorEntry> values,
- OutputCollector<Text,CrawlDatum> output, Reporter reporter) throws IOException {
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
// if using HashComparator, we get only one input key in case of
// hash collision
// so use only URLs from values
@@ -365,7 +390,7 @@ public class Generator extends Configured implements Tool {
super(Text.class);
}
- @SuppressWarnings("rawtypes" )
+ @SuppressWarnings("rawtypes")
public int compare(WritableComparable a, WritableComparable b) {
Text url1 = (Text) a;
Text url2 = (Text) b;
@@ -395,15 +420,17 @@ public class Generator extends Configured implements Tool {
* Update the CrawlDB so that the next generate won't include the same URLs.
*/
public static class CrawlDbUpdater extends MapReduceBase implements
- Mapper<Text,CrawlDatum,Text,CrawlDatum>, Reducer<Text,CrawlDatum,Text,CrawlDatum> {
+ Mapper<Text, CrawlDatum, Text, CrawlDatum>,
+ Reducer<Text, CrawlDatum, Text, CrawlDatum> {
long generateTime;
public void configure(JobConf job) {
generateTime = job.getLong(Nutch.GENERATE_TIME_KEY, 0L);
}
- public void map(Text key, CrawlDatum value, OutputCollector<Text,CrawlDatum> output,
- Reporter reporter) throws IOException {
+ public void map(Text key, CrawlDatum value,
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
output.collect(key, value);
}
@@ -411,7 +438,8 @@ public class Generator extends Configured implements Tool {
private LongWritable genTime = new LongWritable(0L);
public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text,CrawlDatum> output, Reporter reporter) throws IOException {
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
genTime.set(0L);
while (values.hasNext()) {
CrawlDatum val = values.next();
@@ -435,19 +463,21 @@ public class Generator extends Configured implements Tool {
}
}
- public Generator() {}
+ public Generator() {
+ }
public Generator(Configuration conf) {
setConf(conf);
}
- public Path[] generate(Path dbDir, Path segments, int numLists, long topN, long curTime)
- throws IOException {
+ public Path[] generate(Path dbDir, Path segments, int numLists, long topN,
+ long curTime) throws IOException {
JobConf job = new NutchJob(getConf());
boolean filter = job.getBoolean(GENERATOR_FILTER, true);
boolean normalise = job.getBoolean(GENERATOR_NORMALISE, true);
- return generate(dbDir, segments, numLists, topN, curTime, filter, normalise, false, 1);
+ return generate(dbDir, segments, numLists, topN, curTime, filter,
+ normalise, false, 1);
}
/**
@@ -456,7 +486,8 @@ public class Generator extends Configured implements Tool {
**/
public Path[] generate(Path dbDir, Path segments, int numLists, long topN,
long curTime, boolean filter, boolean force) throws IOException {
- return generate(dbDir, segments, numLists, topN, curTime, filter, true, force, 1);
+ return generate(dbDir, segments, numLists, topN, curTime, filter, true,
+ force, 1);
}
/**
@@ -482,11 +513,11 @@ public class Generator extends Configured implements Tool {
* When an I/O error occurs
*/
public Path[] generate(Path dbDir, Path segments, int numLists, long topN,
- long curTime, boolean filter, boolean norm, boolean force, int maxNumSegments)
- throws IOException {
+ long curTime, boolean filter, boolean norm, boolean force,
+ int maxNumSegments) throws IOException {
- Path tempDir = new Path(getConf().get("mapred.temp.dir", ".") + "/generate-temp-"
- + java.util.UUID.randomUUID().toString());
+ Path tempDir = new Path(getConf().get("mapred.temp.dir", ".")
+ + "/generate-temp-" + java.util.UUID.randomUUID().toString());
Path lock = new Path(dbDir, CrawlDb.LOCK_NAME);
FileSystem fs = FileSystem.get(getConf());
@@ -501,7 +532,7 @@ public class Generator extends Configured implements Tool {
if (topN != Long.MAX_VALUE) {
LOG.info("Generator: topN: " + topN);
}
-
+
// map to inverted subset due for fetch, sort by score
JobConf job = new NutchJob(getConf());
job.setJobName("generate: select from " + dbDir);
@@ -553,7 +584,8 @@ public class Generator extends Configured implements Tool {
try {
for (FileStatus stat : status) {
Path subfetchlist = stat.getPath();
- if (!subfetchlist.getName().startsWith("fetchlist-")) continue;
+ if (!subfetchlist.getName().startsWith("fetchlist-"))
+ continue;
// start a new partition job for this segment
Path newSeg = partitionSegment(fs, segments, subfetchlist, numLists);
generatedSegments.add(newSeg);
@@ -573,8 +605,8 @@ public class Generator extends Configured implements Tool {
if (getConf().getBoolean(GENERATE_UPDATE_CRAWLDB, false)) {
// update the db from tempDir
- Path tempDir2 = new Path(getConf().get("mapred.temp.dir", ".") + "/generate-temp-"
- + java.util.UUID.randomUUID().toString());
+ Path tempDir2 = new Path(getConf().get("mapred.temp.dir", ".")
+ + "/generate-temp-" + java.util.UUID.randomUUID().toString());
job = new NutchJob(getConf());
job.setJobName("generate: updatedb " + dbDir);
@@ -607,7 +639,8 @@ public class Generator extends Configured implements Tool {
fs.delete(tempDir, true);
long end = System.currentTimeMillis();
- LOG.info("Generator: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("Generator: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
Path[] patharray = new Path[generatedSegments.size()];
return generatedSegments.toArray(patharray);
@@ -653,7 +686,8 @@ public class Generator extends Configured implements Tool {
public static synchronized String generateSegmentName() {
try {
Thread.sleep(1000);
- } catch (Throwable t) {}
+ } catch (Throwable t) {
+ }
;
return sdf.format(new Date(System.currentTimeMillis()));
}
@@ -662,7 +696,8 @@ public class Generator extends Configured implements Tool {
* Generate a fetchlist from the crawldb.
*/
public static void main(String args[]) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new Generator(), args);
+ int res = ToolRunner
+ .run(NutchConfiguration.create(), new Generator(), args);
System.exit(res);
}
@@ -706,9 +741,10 @@ public class Generator extends Configured implements Tool {
}
try {
- Path[] segs = generate(dbDir, segmentsDir, numFetchers, topN, curTime, filter,
- norm, force, maxNumSegments);
- if (segs == null) return 1;
+ Path[] segs = generate(dbDir, segmentsDir, numFetchers, topN, curTime,
+ filter, norm, force, maxNumSegments);
+ if (segs == null)
+ return 1;
} catch (Exception e) {
LOG.error("Generator: " + StringUtils.stringifyException(e));
return -1;
diff --git a/src/java/org/apache/nutch/crawl/Inlink.java b/src/java/org/apache/nutch/crawl/Inlink.java
index a5f78878e..67df357cb 100644
--- a/src/java/org/apache/nutch/crawl/Inlink.java
+++ b/src/java/org/apache/nutch/crawl/Inlink.java
@@ -26,7 +26,8 @@ public class Inlink implements Writable {
private String fromUrl;
private String anchor;
- public Inlink() {}
+ public Inlink() {
+ }
public Inlink(String fromUrl, String anchor) {
this.fromUrl = fromUrl;
@@ -40,8 +41,8 @@ public class Inlink implements Writable {
/** Skips over one Inlink in the input. */
public static void skip(DataInput in) throws IOException {
- Text.skip(in); // skip fromUrl
- Text.skip(in); // skip anchor
+ Text.skip(in); // skip fromUrl
+ Text.skip(in); // skip anchor
}
public void write(DataOutput out) throws IOException {
@@ -55,16 +56,20 @@ public class Inlink implements Writable {
return inlink;
}
- public String getFromUrl() { return fromUrl; }
- public String getAnchor() { return anchor; }
+ public String getFromUrl() {
+ return fromUrl;
+ }
+
+ public String getAnchor() {
+ return anchor;
+ }
public boolean equals(Object o) {
if (!(o instanceof Inlink))
return false;
- Inlink other = (Inlink)o;
- return
- this.fromUrl.equals(other.fromUrl) &&
- this.anchor.equals(other.anchor);
+ Inlink other = (Inlink) o;
+ return this.fromUrl.equals(other.fromUrl)
+ && this.anchor.equals(other.anchor);
}
public int hashCode() {
diff --git a/src/java/org/apache/nutch/crawl/Inlinks.java b/src/java/org/apache/nutch/crawl/Inlinks.java
index 78b0f9f84..89f973124 100644
--- a/src/java/org/apache/nutch/crawl/Inlinks.java
+++ b/src/java/org/apache/nutch/crawl/Inlinks.java
@@ -27,17 +27,25 @@ import org.apache.hadoop.io.*;
public class Inlinks implements Writable {
private HashSet<Inlink> inlinks = new HashSet<Inlink>(1);
- public void add(Inlink inlink) { inlinks.add(inlink); }
+ public void add(Inlink inlink) {
+ inlinks.add(inlink);
+ }
- public void add(Inlinks inlinks) { this.inlinks.addAll(inlinks.inlinks); }
+ public void add(Inlinks inlinks) {
+ this.inlinks.addAll(inlinks.inlinks);
+ }
public Iterator<Inlink> iterator() {
return this.inlinks.iterator();
}
-
- public int size() { return inlinks.size(); }
- public void clear() { inlinks.clear(); }
+ public int size() {
+ return inlinks.size();
+ }
+
+ public void clear() {
+ inlinks.clear();
+ }
public void readFields(DataInput in) throws IOException {
int length = in.readInt();
@@ -67,30 +75,32 @@ public class Inlinks implements Writable {
return buffer.toString();
}
- /** Return the set of anchor texts. Only a single anchor with a given text
- * is permitted from a given domain. */
+ /**
+ * Return the set of anchor texts. Only a single anchor with a given text is
+ * permitted from a given domain.
+ */
public String[] getAnchors() {
- HashMap<String, Set<String>> domainToAnchors =
- new HashMap<String, Set<String>>();
+ HashMap<String, Set<String>> domainToAnchors = new HashMap<String, Set<String>>();
ArrayList<String> results = new ArrayList<String>();
Iterator<Inlink> it = inlinks.iterator();
while (it.hasNext()) {
Inlink inlink = it.next();
String anchor = inlink.getAnchor();
- if (anchor.length() == 0) // skip empty anchors
+ if (anchor.length() == 0) // skip empty anchors
continue;
- String domain = null; // extract domain name
+ String domain = null; // extract domain name
try {
domain = new URL(inlink.getFromUrl()).getHost();
- } catch (MalformedURLException e) {}
+ } catch (MalformedURLException e) {
+ }
Set<String> domainAnchors = domainToAnchors.get(domain);
if (domainAnchors == null) {
domainAnchors = new HashSet<String>();
domainToAnchors.put(domain, domainAnchors);
}
- if (domainAnchors.add(anchor)) { // new anchor from domain
- results.add(anchor); // collect it
+ if (domainAnchors.add(anchor)) { // new anchor from domain
+ results.add(anchor); // collect it
}
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.java
index 0a7be2c31..c692ed63c 100644
--- a/src/java/org/apache/nutch/crawl/LinkDb.java
+++ b/src/java/org/apache/nutch/crawl/LinkDb.java
@@ -43,7 +43,8 @@ import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.TimingUtil;
/** Maintains an inverted link map, listing incoming links for each url. */
-public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData, Text, Inlinks> {
+public class LinkDb extends Configured implements Tool,
+ Mapper<Text, ParseData, Text, Inlinks> {
public static final Logger LOG = LoggerFactory.getLogger(LinkDb.class);
@@ -56,13 +57,14 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
private boolean ignoreInternalLinks;
private URLFilters urlFilters;
private URLNormalizers urlNormalizers;
-
- public LinkDb() {}
-
+
+ public LinkDb() {
+ }
+
public LinkDb(Configuration conf) {
setConf(conf);
}
-
+
public void configure(JobConf job) {
maxAnchorLength = job.getInt("db.max.anchor.length", 100);
ignoreInternalLinks = job.getBoolean(IGNORE_INTERNAL_LINKS, true);
@@ -74,16 +76,19 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
}
}
- public void close() {}
+ public void close() {
+ }
public void map(Text key, ParseData parseData,
- OutputCollector<Text, Inlinks> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, Inlinks> output, Reporter reporter)
+ throws IOException {
String fromUrl = key.toString();
String fromHost = getHost(fromUrl);
if (urlNormalizers != null) {
try {
- fromUrl = urlNormalizers.normalize(fromUrl, URLNormalizers.SCOPE_LINKDB); // normalize the url
+ fromUrl = urlNormalizers
+ .normalize(fromUrl, URLNormalizers.SCOPE_LINKDB); // normalize the
+ // url
} catch (Exception e) {
LOG.warn("Skipping " + fromUrl + ":" + e);
fromUrl = null;
@@ -97,7 +102,8 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
fromUrl = null;
}
}
- if (fromUrl == null) return; // discard all outlinks
+ if (fromUrl == null)
+ return; // discard all outlinks
Outlink[] outlinks = parseData.getOutlinks();
Inlinks inlinks = new Inlinks();
for (int i = 0; i < outlinks.length; i++) {
@@ -107,12 +113,14 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
if (ignoreInternalLinks) {
String toHost = getHost(toUrl);
if (toHost == null || toHost.equals(fromHost)) { // internal link
- continue; // skip it
+ continue; // skip it
}
}
if (urlNormalizers != null) {
try {
- toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB); // normalize the url
+ toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB); // normalize
+ // the
+ // url
} catch (Exception e) {
LOG.warn("Skipping " + toUrl + ":" + e);
toUrl = null;
@@ -126,13 +134,14 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
toUrl = null;
}
}
- if (toUrl == null) continue;
+ if (toUrl == null)
+ continue;
inlinks.clear();
- String anchor = outlink.getAnchor(); // truncate long anchors
+ String anchor = outlink.getAnchor(); // truncate long anchors
if (anchor.length() > maxAnchorLength) {
anchor = anchor.substring(0, maxAnchorLength);
}
- inlinks.add(new Inlink(fromUrl, anchor)); // collect inverted link
+ inlinks.add(new Inlink(fromUrl, anchor)); // collect inverted link
output.collect(new Text(toUrl), inlinks);
}
}
@@ -145,13 +154,16 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
}
}
- public void invert(Path linkDb, final Path segmentsDir, boolean normalize, boolean filter, boolean force) throws IOException {
+ public void invert(Path linkDb, final Path segmentsDir, boolean normalize,
+ boolean filter, boolean force) throws IOException {
final FileSystem fs = FileSystem.get(getConf());
- FileStatus[] files = fs.listStatus(segmentsDir, HadoopFSUtil.getPassDirectoriesFilter(fs));
+ FileStatus[] files = fs.listStatus(segmentsDir,
+ HadoopFSUtil.getPassDirectoriesFilter(fs));
invert(linkDb, HadoopFSUtil.getPaths(files), normalize, filter, force);
}
- public void invert(Path linkDb, Path[] segments, boolean normalize, boolean filter, boolean force) throws IOException {
+ public void invert(Path linkDb, Path[] segments, boolean normalize,
+ boolean filter, boolean force) throws IOException {
JobConf job = LinkDb.createJob(getConf(), linkDb, normalize, filter);
Path lock = new Path(linkDb, LOCK_NAME);
FileSystem fs = FileSystem.get(getConf());
@@ -174,7 +186,8 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
if (LOG.isInfoEnabled()) {
LOG.info("LinkDb: adding segment: " + segments[i]);
}
- FileInputFormat.addInputPath(job, new Path(segments[i], ParseData.DIR_NAME));
+ FileInputFormat.addInputPath(job, new Path(segments[i],
+ ParseData.DIR_NAME));
}
try {
JobClient.runJob(job);
@@ -203,13 +216,14 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
LinkDb.install(job, linkDb);
long end = System.currentTimeMillis();
- LOG.info("LinkDb: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("LinkDb: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- private static JobConf createJob(Configuration config, Path linkDb, boolean normalize, boolean filter) {
- Path newLinkDb =
- new Path("linkdb-" +
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ private static JobConf createJob(Configuration config, Path linkDb,
+ boolean normalize, boolean filter) {
+ Path newLinkDb = new Path("linkdb-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
JobConf job = new NutchJob(config);
job.setJobName("linkdb " + linkDb);
@@ -247,12 +261,14 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
Path old = new Path(linkDb, "old");
Path current = new Path(linkDb, CURRENT_NAME);
if (fs.exists(current)) {
- if (fs.exists(old)) fs.delete(old, true);
+ if (fs.exists(old))
+ fs.delete(old, true);
fs.rename(current, old);
}
fs.mkdirs(linkDb);
fs.rename(newLinkDb, current);
- if (fs.exists(old)) fs.delete(old, true);
+ if (fs.exists(old))
+ fs.delete(old, true);
LockUtil.removeLockFile(fs, new Path(linkDb, LOCK_NAME));
}
@@ -263,11 +279,14 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
public int run(String[] args) throws Exception {
if (args.length < 2) {
- System.err.println("Usage: LinkDb <linkdb> (-dir <segmentsDir> | <seg1> <seg2> ...) [-force] [-noNormalize] [-noFilter]");
+ System.err
+ .println("Usage: LinkDb <linkdb> (-dir <segmentsDir> | <seg1> <seg2> ...) [-force] [-noNormalize] [-noFilter]");
System.err.println("\tlinkdb\toutput LinkDb to create or update");
- System.err.println("\t-dir segmentsDir\tparent directory of several segments, OR");
+ System.err
+ .println("\t-dir segmentsDir\tparent directory of several segments, OR");
System.err.println("\tseg1 seg2 ...\t list of segment directories");
- System.err.println("\t-force\tforce update even if LinkDb appears to be locked (CAUTION advised)");
+ System.err
+ .println("\t-force\tforce update even if LinkDb appears to be locked (CAUTION advised)");
System.err.println("\t-noNormalize\tdon't normalize link URLs");
System.err.println("\t-noFilter\tdon't apply URLFilters to link URLs");
return -1;
@@ -281,7 +300,8 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
boolean force = false;
for (int i = 1; i < args.length; i++) {
if (args[i].equals("-dir")) {
- FileStatus[] paths = fs.listStatus(new Path(args[++i]), HadoopFSUtil.getPassDirectoriesFilter(fs));
+ FileStatus[] paths = fs.listStatus(new Path(args[++i]),
+ HadoopFSUtil.getPassDirectoriesFilter(fs));
segs.addAll(Arrays.asList(HadoopFSUtil.getPaths(paths)));
} else if (args[i].equalsIgnoreCase("-noNormalize")) {
normalize = false;
@@ -289,7 +309,8 @@ public class LinkDb extends Configured implements Tool, Mapper<Text, ParseData,
filter = false;
} else if (args[i].equalsIgnoreCase("-force")) {
force = true;
- } else segs.add(new Path(args[i]));
+ } else
+ segs.add(new Path(args[i]));
}
try {
invert(db, segs.toArray(new Path[segs.size()]), normalize, filter, force);
diff --git a/src/java/org/apache/nutch/crawl/LinkDbFilter.java b/src/java/org/apache/nutch/crawl/LinkDbFilter.java
index 8f86fa148..1ff9b050d 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbFilter.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbFilter.java
@@ -31,8 +31,8 @@ import org.apache.nutch.net.URLFilters;
import org.apache.nutch.net.URLNormalizers;
/**
- * This class provides a way to separate the URL normalization
- * and filtering steps from the rest of LinkDb manipulation code.
+ * This class provides a way to separate the URL normalization and filtering
+ * steps from the rest of LinkDb manipulation code.
*
* @author Andrzej Bialecki
*/
@@ -50,13 +50,13 @@ public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
private URLFilters filters;
private URLNormalizers normalizers;
-
+
private String scope;
-
+
public static final Logger LOG = LoggerFactory.getLogger(LinkDbFilter.class);
private Text newKey = new Text();
-
+
public void configure(JobConf job) {
filter = job.getBoolean(URL_FILTERING, false);
normalize = job.getBoolean(URL_NORMALIZING, false);
@@ -69,10 +69,12 @@ public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
}
}
- public void close() {}
+ public void close() {
+ }
public void map(Text key, Inlinks value,
- OutputCollector<Text, Inlinks> output, Reporter reporter) throws IOException {
+ OutputCollector<Text, Inlinks> output, Reporter reporter)
+ throws IOException {
String url = key.toString();
Inlinks result = new Inlinks();
if (normalize) {
@@ -91,7 +93,8 @@ public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
url = null;
}
}
- if (url == null) return; // didn't pass the filters
+ if (url == null)
+ return; // didn't pass the filters
Iterator<Inlink> it = value.iterator();
String fromUrl = null;
while (it.hasNext()) {
@@ -113,7 +116,7 @@ public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
fromUrl = null;
}
}
- if (fromUrl != null) {
+ if (fromUrl != null) {
result.add(new Inlink(fromUrl, inlink.getAnchor()));
}
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbMerger.java b/src/java/org/apache/nutch/crawl/LinkDbMerger.java
index 584a494c4..71b9ae64d 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbMerger.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbMerger.java
@@ -46,37 +46,44 @@ import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.TimingUtil;
/**
- * This tool merges several LinkDb-s into one, optionally filtering
- * URLs through the current URLFilters, to skip prohibited URLs and
- * links.
+ * This tool merges several LinkDb-s into one, optionally filtering URLs through
+ * the current URLFilters, to skip prohibited URLs and links.
*
- * <p>It's possible to use this tool just for filtering - in that case
- * only one LinkDb should be specified in arguments.</p>
- * <p>If more than one LinkDb contains information about the same URL,
- * all inlinks are accumulated, but only at most <code>db.max.inlinks</code>
- * inlinks will ever be added.</p>
- * <p>If activated, URLFilters will be applied to both the target URLs and
- * to any incoming link URL. If a target URL is prohibited, all
- * inlinks to that target will be removed, including the target URL. If
- * some of incoming links are prohibited, only they will be removed, and they
- * won't count when checking the above-mentioned maximum limit.
+ * <p>
+ * It's possible to use this tool just for filtering - in that case only one
+ * LinkDb should be specified in arguments.
+ * </p>
+ * <p>
+ * If more than one LinkDb contains information about the same URL, all inlinks
+ * are accumulated, but only at most <code>db.max.inlinks</code> inlinks will
+ * ever be added.
+ * </p>
+ * <p>
+ * If activated, URLFilters will be applied to both the target URLs and to any
+ * incoming link URL. If a target URL is prohibited, all inlinks to that target
+ * will be removed, including the target URL. If some of incoming links are
+ * prohibited, only they will be removed, and they won't count when checking the
+ * above-mentioned maximum limit.
*
* @author Andrzej Bialecki
*/
-public class LinkDbMerger extends Configured implements Tool, Reducer<Text, Inlinks, Text, Inlinks> {
+public class LinkDbMerger extends Configured implements Tool,
+ Reducer<Text, Inlinks, Text, Inlinks> {
private static final Logger LOG = LoggerFactory.getLogger(LinkDbMerger.class);
-
+
private int maxInlinks;
-
+
public LinkDbMerger() {
-
+
}
-
+
public LinkDbMerger(Configuration conf) {
setConf(conf);
}
- public void reduce(Text key, Iterator<Inlinks> values, OutputCollector<Text, Inlinks> output, Reporter reporter) throws IOException {
+ public void reduce(Text key, Iterator<Inlinks> values,
+ OutputCollector<Text, Inlinks> output, Reporter reporter)
+ throws IOException {
Inlinks result = new Inlinks();
@@ -86,43 +93,48 @@ public class LinkDbMerger extends Configured implements Tool, Reducer<Text, Inli
int end = Math.min(maxInlinks - result.size(), inlinks.size());
Iterator<Inlink> it = inlinks.iterator();
int i = 0;
- while(it.hasNext() && i++ < end) {
+ while (it.hasNext() && i++ < end) {
result.add(it.next());
}
}
- if (result.size() == 0) return;
+ if (result.size() == 0)
+ return;
output.collect(key, result);
-
+
}
public void configure(JobConf job) {
maxInlinks = job.getInt("db.max.inlinks", 10000);
}
- public void close() throws IOException { }
+ public void close() throws IOException {
+ }
- public void merge(Path output, Path[] dbs, boolean normalize, boolean filter) throws Exception {
+ public void merge(Path output, Path[] dbs, boolean normalize, boolean filter)
+ throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
LOG.info("LinkDb merge: starting at " + sdf.format(start));
JobConf job = createMergeJob(getConf(), output, normalize, filter);
for (int i = 0; i < dbs.length; i++) {
- FileInputFormat.addInputPath(job, new Path(dbs[i], LinkDb.CURRENT_NAME));
+ FileInputFormat.addInputPath(job, new Path(dbs[i], LinkDb.CURRENT_NAME));
}
JobClient.runJob(job);
FileSystem fs = FileSystem.get(getConf());
fs.mkdirs(output);
- fs.rename(FileOutputFormat.getOutputPath(job), new Path(output, LinkDb.CURRENT_NAME));
+ fs.rename(FileOutputFormat.getOutputPath(job), new Path(output,
+ LinkDb.CURRENT_NAME));
long end = System.currentTimeMillis();
- LOG.info("LinkDb merge: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("LinkDb merge: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- public static JobConf createMergeJob(Configuration config, Path linkDb, boolean normalize, boolean filter) {
- Path newLinkDb =
- new Path("linkdb-merge-" +
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ public static JobConf createMergeJob(Configuration config, Path linkDb,
+ boolean normalize, boolean filter) {
+ Path newLinkDb = new Path("linkdb-merge-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
JobConf job = new NutchJob(config);
job.setJobName("linkdb merge " + linkDb);
@@ -145,22 +157,27 @@ public class LinkDbMerger extends Configured implements Tool, Reducer<Text, Inli
return job;
}
-
+
/**
* @param args
*/
public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new LinkDbMerger(), args);
+ int res = ToolRunner.run(NutchConfiguration.create(), new LinkDbMerger(),
+ args);
System.exit(res);
}
-
+
public int run(String[] args) throws Exception {
if (args.length < 2) {
- System.err.println("Usage: LinkDbMerger <output_linkdb> <linkdb1> [<linkdb2> <linkdb3> ...] [-normalize] [-filter]");
+ System.err
+ .println("Usage: LinkDbMerger <output_linkdb> <linkdb1> [<linkdb2> <linkdb3> ...] [-normalize] [-filter]");
System.err.println("\toutput_linkdb\toutput LinkDb");
- System.err.println("\tlinkdb1 ...\tinput LinkDb-s (single input LinkDb is ok)");
- System.err.println("\t-normalize\tuse URLNormalizer on both fromUrls and toUrls in linkdb(s) (usually not needed)");
- System.err.println("\t-filter\tuse URLFilters on both fromUrls and toUrls in linkdb(s)");
+ System.err
+ .println("\tlinkdb1 ...\tinput LinkDb-s (single input LinkDb is ok)");
+ System.err
+ .println("\t-normalize\tuse URLNormalizer on both fromUrls and toUrls in linkdb(s) (usually not needed)");
+ System.err
+ .println("\t-filter\tuse URLFilters on both fromUrls and toUrls in linkdb(s)");
return -1;
}
Path output = new Path(args[0]);
@@ -172,7 +189,8 @@ public class LinkDbMerger extends Configured implements Tool, Reducer<Text, Inli
filter = true;
} else if (args[i].equals("-normalize")) {
normalize = true;
- } else dbs.add(new Path(args[i]));
+ } else
+ dbs.add(new Path(args[i]));
}
try {
merge(output, dbs.toArray(new Path[dbs.size()]), normalize, filter);
diff --git a/src/java/org/apache/nutch/crawl/LinkDbReader.java b/src/java/org/apache/nutch/crawl/LinkDbReader.java
index 0618b61aa..3c9ac8bd6 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbReader.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbReader.java
@@ -50,14 +50,14 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
private MapFile.Reader[] readers;
public LinkDbReader() {
-
+
}
-
+
public LinkDbReader(Configuration conf, Path directory) throws Exception {
setConf(conf);
init(directory);
}
-
+
public void init(Path directory) throws Exception {
this.fs = FileSystem.get(getConf());
this.directory = directory;
@@ -73,16 +73,16 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
public Inlinks getInlinks(Text url) throws IOException {
if (readers == null) {
- synchronized(this) {
- readers = MapFileOutputFormat.getReaders
- (fs, new Path(directory, LinkDb.CURRENT_NAME), getConf());
+ synchronized (this) {
+ readers = MapFileOutputFormat.getReaders(fs, new Path(directory,
+ LinkDb.CURRENT_NAME), getConf());
}
}
-
- return (Inlinks)MapFileOutputFormat.getEntry
- (readers, PARTITIONER, url, new Inlinks());
+
+ return (Inlinks) MapFileOutputFormat.getEntry(readers, PARTITIONER, url,
+ new Inlinks());
}
-
+
public void close() throws IOException {
if (readers != null) {
for (int i = 0; i < readers.length; i++) {
@@ -90,7 +90,7 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
}
}
}
-
+
public void processDumpJob(String linkdb, String output) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -114,19 +114,24 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
JobClient.runJob(job);
long end = System.currentTimeMillis();
- LOG.info("LinkDb dump: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("LinkDb dump: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
-
+
public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new LinkDbReader(), args);
+ int res = ToolRunner.run(NutchConfiguration.create(), new LinkDbReader(),
+ args);
System.exit(res);
}
-
+
public int run(String[] args) throws Exception {
if (args.length < 2) {
- System.err.println("Usage: LinkDbReader <linkdb> (-dump <out_dir> | -url <url>)");
- System.err.println("\t-dump <out_dir>\tdump whole link db to a text file in <out_dir>");
- System.err.println("\t-url <url>\tprint information about <url> to System.out");
+ System.err
+ .println("Usage: LinkDbReader <linkdb> (-dump <out_dir> | -url <url>)");
+ System.err
+ .println("\t-dump <out_dir>\tdump whole link db to a text file in <out_dir>");
+ System.err
+ .println("\t-url <url>\tprint information about <url> to System.out");
return -1;
}
try {
diff --git a/src/java/org/apache/nutch/crawl/MD5Signature.java b/src/java/org/apache/nutch/crawl/MD5Signature.java
index fb11d10e5..f6ec8dd68 100644
--- a/src/java/org/apache/nutch/crawl/MD5Signature.java
+++ b/src/java/org/apache/nutch/crawl/MD5Signature.java
@@ -22,9 +22,9 @@ import org.apache.nutch.parse.Parse;
import org.apache.nutch.protocol.Content;
/**
- * Default implementation of a page signature. It calculates an MD5 hash
- * of the raw binary content of a page. In case there is no content, it
- * calculates a hash from the page's URL.
+ * Default implementation of a page signature. It calculates an MD5 hash of the
+ * raw binary content of a page. In case there is no content, it calculates a
+ * hash from the page's URL.
*
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
@@ -32,7 +32,8 @@ public class MD5Signature extends Signature {
public byte[] calculate(Content content, Parse parse) {
byte[] data = content.getContent();
- if (data == null) data = content.getUrl().getBytes();
+ if (data == null)
+ data = content.getUrl().getBytes();
return MD5Hash.digest(data).getDigest();
}
}
diff --git a/src/java/org/apache/nutch/crawl/MapWritable.java b/src/java/org/apache/nutch/crawl/MapWritable.java
index f8461c268..714dd77ee 100644
--- a/src/java/org/apache/nutch/crawl/MapWritable.java
+++ b/src/java/org/apache/nutch/crawl/MapWritable.java
@@ -47,19 +47,19 @@ import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.protocol.ProtocolStatus;
/**
- * A writable map, with a similar behavior as <code>java.util.HashMap</code>.
- * In addition to the size of key and value writable tuple two additional bytes
- * are stored to identify the Writable classes. This means that a maximum of
- * 255 different class types can be used for key and value objects.
- * A binary-id to class mapping is defined in a static block of this class.
- * However it is possible to use custom implementations of Writable.
- * For these custom Writables we write the byte id - utf class name tuple
- * into the header of each MapWritable that uses these types.
- *
+ * A writable map, with a similar behavior as <code>java.util.HashMap</code>. In
+ * addition to the size of key and value writable tuple two additional bytes are
+ * stored to identify the Writable classes. This means that a maximum of 255
+ * different class types can be used for key and value objects. A binary-id to
+ * class mapping is defined in a static block of this class. However it is
+ * possible to use custom implementations of Writable. For these custom
+ * Writables we write the byte id - utf class name tuple into the header of each
+ * MapWritable that uses these types.
+ *
* @author Stefan Groschupf
* @deprecated Use org.apache.hadoop.io.MapWritable instead.
*/
-
+
@Deprecated
public class MapWritable implements Writable {
@@ -105,14 +105,16 @@ public class MapWritable implements Writable {
CLASS_ID_MAP.put(clazz, byteId);
ID_CLASS_MAP.put(byteId, clazz);
}
-
- public MapWritable() { }
-
+
+ public MapWritable() {
+ }
+
/**
* Copy constructor. This constructor makes a deep copy, using serialization /
* deserialization to break any possible references to contained objects.
*
- * @param map map to copy from
+ * @param map
+ * map to copy from
*/
public MapWritable(MapWritable map) {
if (map != null) {
@@ -123,8 +125,8 @@ public class MapWritable implements Writable {
dib.reset(dob.getData(), dob.getLength());
readFields(dib);
} catch (IOException e) {
- throw new IllegalArgumentException("this map cannot be copied: " +
- StringUtils.stringifyException(e));
+ throw new IllegalArgumentException("this map cannot be copied: "
+ + StringUtils.stringifyException(e));
}
}
}
@@ -177,7 +179,8 @@ public class MapWritable implements Writable {
public Set<Writable> keySet() {
HashSet<Writable> set = new HashSet<Writable>();
- if (isEmpty()) return set;
+ if (isEmpty())
+ return set;
set.add(fFirst.fKey);
KeyValueEntry entry = fFirst;
while ((entry = entry.fNextEntry) != null) {
@@ -257,7 +260,8 @@ public class MapWritable implements Writable {
public boolean equals(Object obj) {
if (obj instanceof MapWritable) {
MapWritable map = (MapWritable) obj;
- if (fSize != map.fSize) return false;
+ if (fSize != map.fSize)
+ return false;
HashSet<KeyValueEntry> set1 = new HashSet<KeyValueEntry>();
KeyValueEntry e1 = fFirst;
while (e1 != null) {
@@ -345,7 +349,7 @@ public class MapWritable implements Writable {
clazz = Class.forName(Text.readString(in));
addIdEntry(id, clazz);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
+ if (LOG.isWarnEnabled()) {
LOG.warn("Unable to load internal map entry" + e.toString());
}
fIdCount--;
@@ -364,8 +368,8 @@ public class MapWritable implements Writable {
}
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to load meta data entry, ignoring.. : " +
- e.toString());
+ LOG.warn("Unable to load meta data entry, ignoring.. : "
+ + e.toString());
}
fSize--;
}
diff --git a/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java b/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
index 5027f8dde..5d2a60e33 100644
--- a/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
@@ -34,29 +34,31 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Extension of @see AdaptiveFetchSchedule that allows for more flexible configuration
- * of DEC and INC factors for various MIME-types.
- *
- * This class can be typically used in cases where a recrawl consists of many different
- * MIME-types. It's not very common for MIME-types other than text/html to change frequently.
- * Using this class you can configure different factors per MIME-type so to prefer frequently
- * changing MIME-types over others.
+ * Extension of @see AdaptiveFetchSchedule that allows for more flexible
+ * configuration of DEC and INC factors for various MIME-types.
+ *
+ * This class can be typically used in cases where a recrawl consists of many
+ * different MIME-types. It's not very common for MIME-types other than
+ * text/html to change frequently. Using this class you can configure different
+ * factors per MIME-type so to prefer frequently changing MIME-types over
+ * others.
+ *
+ * For it to work this class relies on the Content-Type MetaData key being
+ * present in the CrawlDB. This can either be done when injecting new URL's or
+ * by adding "Content-Type" to the db.parsemeta.to.crawldb configuration setting
+ * to force MIME-types of newly discovered URL's to be added to the CrawlDB.
*
- * For it to work this class relies on the Content-Type MetaData key being present in the CrawlDB.
- * This can either be done when injecting new URL's or by adding "Content-Type" to the
- * db.parsemeta.to.crawldb configuration setting to force MIME-types of newly discovered URL's to
- * be added to the CrawlDB.
- *
* @author markus
*/
public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
// Loggg
- public static final Logger LOG = LoggerFactory.getLogger(MimeAdaptiveFetchSchedule.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(MimeAdaptiveFetchSchedule.class);
// Conf directives
public static final String SCHEDULE_INC_RATE = "db.fetch.schedule.adaptive.inc_rate";
public static final String SCHEDULE_DEC_RATE = "db.fetch.schedule.adaptive.dec_rate";
- public static final String SCHEDULE_MIME_FILE= "db.fetch.schedule.mime.file";
+ public static final String SCHEDULE_MIME_FILE = "db.fetch.schedule.mime.file";
// Default values for DEC and INC rate
private float defaultIncRate;
@@ -74,18 +76,21 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
}
// Here we store the mime's and their delta's
- private HashMap<String,AdaptiveRate> mimeMap;
+ private HashMap<String, AdaptiveRate> mimeMap;
public void setConf(Configuration conf) {
super.setConf(conf);
- if (conf == null) return;
+ if (conf == null)
+ return;
- // Read and set the default INC and DEC rates in case we cannot set values based on MIME-type
+ // Read and set the default INC and DEC rates in case we cannot set values
+ // based on MIME-type
defaultIncRate = conf.getFloat(SCHEDULE_INC_RATE, 0.2f);
defaultDecRate = conf.getFloat(SCHEDULE_DEC_RATE, 0.2f);
// Where's the mime/factor file?
- Reader mimeFile = conf.getConfResourceAsReader(conf.get(SCHEDULE_MIME_FILE, "adaptive-mimetypes.txt"));
+ Reader mimeFile = conf.getConfResourceAsReader(conf.get(SCHEDULE_MIME_FILE,
+ "adaptive-mimetypes.txt"));
try {
readMimeFile(mimeFile);
@@ -96,8 +101,8 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
@Override
public CrawlDatum setFetchSchedule(Text url, CrawlDatum datum,
- long prevFetchTime, long prevModifiedTime,
- long fetchTime, long modifiedTime, int state) {
+ long prevFetchTime, long prevModifiedTime, long fetchTime,
+ long modifiedTime, int state) {
// Set defaults
INC_RATE = defaultIncRate;
@@ -106,7 +111,8 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
// Check if the Content-Type field is available in the CrawlDatum
if (datum.getMetaData().containsKey(HttpHeaders.WRITABLE_CONTENT_TYPE)) {
// Get the MIME-type of the current URL
- String currentMime = datum.getMetaData().get(HttpHeaders.WRITABLE_CONTENT_TYPE).toString();
+ String currentMime = datum.getMetaData()
+ .get(HttpHeaders.WRITABLE_CONTENT_TYPE).toString();
// Get rid of charset
currentMime = currentMime.substring(0, currentMime.indexOf(';'));
@@ -120,18 +126,19 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
}
return super.setFetchSchedule(url, datum, prevFetchTime, prevModifiedTime,
- fetchTime, modifiedTime, state);
+ fetchTime, modifiedTime, state);
}
/**
* Reads the mime types and their associated INC/DEC factors in a HashMap
- *
- * @param mimeFile Reader
+ *
+ * @param mimeFile
+ * Reader
* @return void
*/
private void readMimeFile(Reader mimeFile) throws IOException {
// Instance of our mime/factor map
- mimeMap = new HashMap<String,AdaptiveRate>();
+ mimeMap = new HashMap<String, AdaptiveRate>();
// Open a reader
BufferedReader reader = new BufferedReader(mimeFile);
@@ -149,7 +156,8 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
// Sanity check, we need two or three items
if (splits.length == 3) {
// Add a lower cased MIME-type and the factor to the map
- mimeMap.put(StringUtils.lowerCase(splits[0]), new AdaptiveRate(new Float(splits[1]), new Float(splits[2])));
+ mimeMap.put(StringUtils.lowerCase(splits[0]), new AdaptiveRate(
+ new Float(splits[1]), new Float(splits[2])));
} else {
LOG.warn("Invalid configuration line in: " + line);
}
@@ -178,7 +186,8 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
// Set a default MIME-type to test with
org.apache.hadoop.io.MapWritable x = new org.apache.hadoop.io.MapWritable();
- x.put(HttpHeaders.WRITABLE_CONTENT_TYPE, new Text("text/html; charset=utf-8"));
+ x.put(HttpHeaders.WRITABLE_CONTENT_TYPE, new Text(
+ "text/html; charset=utf-8"));
p.setMetaData(x);
p.setFetchTime(0);
@@ -187,37 +196,45 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
// let's move the timeline a couple of deltas
for (int i = 0; i < 10000; i++) {
if (lastModified + update < curTime) {
- //System.out.println("i=" + i + ", lastModified=" + lastModified + ", update=" + update + ", curTime=" + curTime);
+ // System.out.println("i=" + i + ", lastModified=" + lastModified +
+ // ", update=" + update + ", curTime=" + curTime);
changed = true;
changeCnt++;
lastModified = curTime;
}
- LOG.info(i + ". " + changed + "\twill fetch at " + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY ) + " days" + "\t missed " + miss);
+ LOG.info(i + ". " + changed + "\twill fetch at "
+ + (p.getFetchTime() / delta) + "\tinterval "
+ + (p.getFetchInterval() / SECONDS_PER_DAY) + " days" + "\t missed "
+ + miss);
if (p.getFetchTime() <= curTime) {
fetchCnt++;
- fs.setFetchSchedule(new Text("http://www.example.com"), p,
- p.getFetchTime(), p.getModifiedTime(), curTime, lastModified,
- changed ? FetchSchedule.STATUS_MODIFIED : FetchSchedule.STATUS_NOTMODIFIED);
-
- LOG.info("\tfetched & adjusted: " + "\twill fetch at " + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY ) + " days");
-
- if (!changed) miss++;
- if (miss > maxMiss) maxMiss = miss;
+ fs.setFetchSchedule(new Text("http://www.example.com"), p, p
+ .getFetchTime(), p.getModifiedTime(), curTime, lastModified,
+ changed ? FetchSchedule.STATUS_MODIFIED
+ : FetchSchedule.STATUS_NOTMODIFIED);
+
+ LOG.info("\tfetched & adjusted: " + "\twill fetch at "
+ + (p.getFetchTime() / delta) + "\tinterval "
+ + (p.getFetchInterval() / SECONDS_PER_DAY) + " days");
+
+ if (!changed)
+ miss++;
+ if (miss > maxMiss)
+ maxMiss = miss;
changed = false;
totalMiss += miss;
miss = 0;
}
- if (changed) miss++;
+ if (changed)
+ miss++;
curTime += delta;
}
LOG.info("Total missed: " + totalMiss + ", max miss: " + maxMiss);
- LOG.info("Page changed " + changeCnt + " times, fetched " + fetchCnt + " times.");
+ LOG.info("Page changed " + changeCnt + " times, fetched " + fetchCnt
+ + " times.");
}
-
}
\ No newline at end of file
diff --git a/src/java/org/apache/nutch/crawl/NutchWritable.java b/src/java/org/apache/nutch/crawl/NutchWritable.java
index 945d8f708..ff2328cf4 100644
--- a/src/java/org/apache/nutch/crawl/NutchWritable.java
+++ b/src/java/org/apache/nutch/crawl/NutchWritable.java
@@ -26,32 +26,31 @@ public class NutchWritable extends GenericWritableConfigurable {
static {
CLASSES = (Class<? extends Writable>[]) new Class<?>[] {
- org.apache.hadoop.io.NullWritable.class,
- org.apache.hadoop.io.BooleanWritable.class,
- org.apache.hadoop.io.LongWritable.class,
- org.apache.hadoop.io.BytesWritable.class,
- org.apache.hadoop.io.FloatWritable.class,
- org.apache.hadoop.io.IntWritable.class,
- org.apache.hadoop.io.MapWritable.class,
- org.apache.hadoop.io.Text.class,
- org.apache.hadoop.io.MD5Hash.class,
- org.apache.nutch.crawl.CrawlDatum.class,
- org.apache.nutch.crawl.Inlink.class,
- org.apache.nutch.crawl.Inlinks.class,
- org.apache.nutch.indexer.NutchIndexAction.class,
- org.apache.nutch.metadata.Metadata.class,
- org.apache.nutch.parse.Outlink.class,
- org.apache.nutch.parse.ParseText.class,
- org.apache.nutch.parse.ParseData.class,
- org.apache.nutch.parse.ParseImpl.class,
- org.apache.nutch.parse.ParseStatus.class,
- org.apache.nutch.protocol.Content.class,
- org.apache.nutch.protocol.ProtocolStatus.class,
- org.apache.nutch.scoring.webgraph.LinkDatum.class
- };
+ org.apache.hadoop.io.NullWritable.class,
+ org.apache.hadoop.io.BooleanWritable.class,
+ org.apache.hadoop.io.LongWritable.class,
+ org.apache.hadoop.io.BytesWritable.class,
+ org.apache.hadoop.io.FloatWritable.class,
+ org.apache.hadoop.io.IntWritable.class,
+ org.apache.hadoop.io.MapWritable.class,
+ org.apache.hadoop.io.Text.class, org.apache.hadoop.io.MD5Hash.class,
+ org.apache.nutch.crawl.CrawlDatum.class,
+ org.apache.nutch.crawl.Inlink.class,
+ org.apache.nutch.crawl.Inlinks.class,
+ org.apache.nutch.indexer.NutchIndexAction.class,
+ org.apache.nutch.metadata.Metadata.class,
+ org.apache.nutch.parse.Outlink.class,
+ org.apache.nutch.parse.ParseText.class,
+ org.apache.nutch.parse.ParseData.class,
+ org.apache.nutch.parse.ParseImpl.class,
+ org.apache.nutch.parse.ParseStatus.class,
+ org.apache.nutch.protocol.Content.class,
+ org.apache.nutch.protocol.ProtocolStatus.class,
+ org.apache.nutch.scoring.webgraph.LinkDatum.class };
}
- public NutchWritable() { }
+ public NutchWritable() {
+ }
public NutchWritable(Writable instance) {
set(instance);
diff --git a/src/java/org/apache/nutch/crawl/Signature.java b/src/java/org/apache/nutch/crawl/Signature.java
index d10e0f927..21dfe07d4 100644
--- a/src/java/org/apache/nutch/crawl/Signature.java
+++ b/src/java/org/apache/nutch/crawl/Signature.java
@@ -24,7 +24,7 @@ import org.apache.hadoop.conf.Configurable;
public abstract class Signature implements Configurable {
protected Configuration conf;
-
+
public abstract byte[] calculate(Content content, Parse parse);
public Configuration getConf() {
diff --git a/src/java/org/apache/nutch/crawl/SignatureComparator.java b/src/java/org/apache/nutch/crawl/SignatureComparator.java
index 4449ffb2e..d217d93a0 100644
--- a/src/java/org/apache/nutch/crawl/SignatureComparator.java
+++ b/src/java/org/apache/nutch/crawl/SignatureComparator.java
@@ -23,25 +23,34 @@ public class SignatureComparator implements Comparator<Object> {
public int compare(Object o1, Object o2) {
return _compare(o1, o2);
}
-
+
public static int _compare(Object o1, Object o2) {
- if (o1 == null && o2 == null) return 0;
- if (o1 == null) return -1;
- if (o2 == null) return 1;
- if (!(o1 instanceof byte[])) return -1;
- if (!(o2 instanceof byte[])) return 1;
- byte[] data1 = (byte[])o1;
- byte[] data2 = (byte[])o2;
+ if (o1 == null && o2 == null)
+ return 0;
+ if (o1 == null)
+ return -1;
+ if (o2 == null)
+ return 1;
+ if (!(o1 instanceof byte[]))
+ return -1;
+ if (!(o2 instanceof byte[]))
+ return 1;
+ byte[] data1 = (byte[]) o1;
+ byte[] data2 = (byte[]) o2;
return _compare(data1, 0, data1.length, data2, 0, data2.length);
}
-
- public static int _compare(byte[] data1, int s1, int l1, byte[] data2, int s2, int l2) {
- if (l2 > l1) return -1;
- if (l2 < l1) return 1;
+
+ public static int _compare(byte[] data1, int s1, int l1, byte[] data2,
+ int s2, int l2) {
+ if (l2 > l1)
+ return -1;
+ if (l2 < l1)
+ return 1;
int res = 0;
for (int i = 0; i < l1; i++) {
res = (data1[s1 + i] - data2[s2 + i]);
- if (res != 0) return res;
+ if (res != 0)
+ return res;
}
return 0;
}
diff --git a/src/java/org/apache/nutch/crawl/SignatureFactory.java b/src/java/org/apache/nutch/crawl/SignatureFactory.java
index 1a66063fd..16d8cc091 100644
--- a/src/java/org/apache/nutch/crawl/SignatureFactory.java
+++ b/src/java/org/apache/nutch/crawl/SignatureFactory.java
@@ -27,28 +27,30 @@ import org.apache.nutch.util.ObjectCache;
/**
* Factory class, which instantiates a Signature implementation according to the
- * current Configuration configuration. This newly created instance is cached in the
- * Configuration instance, so that it could be later retrieved.
+ * current Configuration configuration. This newly created instance is cached in
+ * the Configuration instance, so that it could be later retrieved.
*
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
public class SignatureFactory {
- private static final Logger LOG = LoggerFactory.getLogger(SignatureFactory.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(SignatureFactory.class);
- private SignatureFactory() {} // no public ctor
+ private SignatureFactory() {
+ } // no public ctor
/** Return the default Signature implementation. */
public synchronized static Signature getSignature(Configuration conf) {
String clazz = conf.get("db.signature.class", MD5Signature.class.getName());
ObjectCache objectCache = ObjectCache.get(conf);
- Signature impl = (Signature)objectCache.getObject(clazz);
+ Signature impl = (Signature) objectCache.getObject(clazz);
if (impl == null) {
try {
if (LOG.isInfoEnabled()) {
LOG.info("Using Signature impl: " + clazz);
}
Class<?> implClass = Class.forName(clazz);
- impl = (Signature)implClass.newInstance();
+ impl = (Signature) implClass.newInstance();
impl.setConf(conf);
objectCache.setObject(clazz, impl);
} catch (Exception e) {
diff --git a/src/java/org/apache/nutch/crawl/TextMD5Signature.java b/src/java/org/apache/nutch/crawl/TextMD5Signature.java
index 78c1992d8..b88cfa6ed 100644
--- a/src/java/org/apache/nutch/crawl/TextMD5Signature.java
+++ b/src/java/org/apache/nutch/crawl/TextMD5Signature.java
@@ -22,9 +22,9 @@ import org.apache.nutch.parse.Parse;
import org.apache.nutch.protocol.Content;
/**
- * Implementation of a page signature. It calculates an MD5 hash
- * of the textual content of a page. In case there is no content, it
- * calculates a hash from the page's URL.
+ * Implementation of a page signature. It calculates an MD5 hash of the textual
+ * content of a page. In case there is no content, it calculates a hash from the
+ * page's URL.
*/
public class TextMD5Signature extends Signature {
@@ -36,7 +36,7 @@ public class TextMD5Signature extends Signature {
if (text == null || text.length() == 0) {
return fallback.calculate(content, parse);
}
-
+
return MD5Hash.digest(text).getDigest();
}
}
diff --git a/src/java/org/apache/nutch/crawl/TextProfileSignature.java b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
index e1b28caf5..5d930f959 100644
--- a/src/java/org/apache/nutch/crawl/TextProfileSignature.java
+++ b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
@@ -35,41 +35,50 @@ import org.apache.nutch.util.StringUtil;
import org.apache.nutch.util.NutchConfiguration;
/**
- * <p>An implementation of a page signature. It calculates an MD5 hash
- * of a plain text "profile" of a page. In case there is no text, it
- * calculates a hash using the {@link MD5Signature}.</p>
- * <p>The algorithm to calculate a page "profile" takes the plain text version of
- * a page and performs the following steps:
+ * <p>
+ * An implementation of a page signature. It calculates an MD5 hash of a plain
+ * text "profile" of a page. In case there is no text, it calculates a hash
+ * using the {@link MD5Signature}.
+ * </p>
+ * <p>
+ * The algorithm to calculate a page "profile" takes the plain text version of a
+ * page and performs the following steps:
* <ul>
* <li>remove all characters except letters and digits, and bring all characters
* to lower case,</li>
* <li>split the text into tokens (all consecutive non-whitespace characters),</li>
- * <li>discard tokens equal or shorter than MIN_TOKEN_LEN (default 2 characters),</li>
+ * <li>discard tokens equal or shorter than MIN_TOKEN_LEN (default 2
+ * characters),</li>
* <li>sort the list of tokens by decreasing frequency,</li>
- * <li>round down the counts of tokens to the nearest multiple of QUANT
- * (<code>QUANT = QUANT_RATE * maxFreq</code>, where <code>QUANT_RATE</code> is 0.01f
- * by default, and <code>maxFreq</code> is the maximum token frequency). If
- * <code>maxFreq</code> is higher than 1, then QUANT is always higher than 2 (which
- * means that tokens with frequency 1 are always discarded).</li>
- * <li>tokens, which frequency after quantization falls below QUANT, are discarded.</li>
- * <li>create a list of tokens and their quantized frequency, separated by spaces,
- * in the order of decreasing frequency.</li>
+ * <li>round down the counts of tokens to the nearest multiple of QUANT (
+ * <code>QUANT = QUANT_RATE * maxFreq</code>, where <code>QUANT_RATE</code> is
+ * 0.01f by default, and <code>maxFreq</code> is the maximum token frequency).
+ * If <code>maxFreq</code> is higher than 1, then QUANT is always higher than 2
+ * (which means that tokens with frequency 1 are always discarded).</li>
+ * <li>tokens, which frequency after quantization falls below QUANT, are
+ * discarded.</li>
+ * <li>create a list of tokens and their quantized frequency, separated by
+ * spaces, in the order of decreasing frequency.</li>
* </ul>
* This list is then submitted to an MD5 hash calculation.
*
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
public class TextProfileSignature extends Signature {
-
+
Signature fallback = new MD5Signature();
public byte[] calculate(Content content, Parse parse) {
- int MIN_TOKEN_LEN = getConf().getInt("db.signature.text_profile.min_token_len", 2);
- float QUANT_RATE = getConf().getFloat("db.signature.text_profile.quant_rate", 0.01f);
+ int MIN_TOKEN_LEN = getConf().getInt(
+ "db.signature.text_profile.min_token_len", 2);
+ float QUANT_RATE = getConf().getFloat(
+ "db.signature.text_profile.quant_rate", 0.01f);
HashMap<String, Token> tokens = new HashMap<String, Token>();
String text = null;
- if (parse != null) text = parse.getText();
- if (text == null || text.length() == 0) return fallback.calculate(content, parse);
+ if (parse != null)
+ text = parse.getText();
+ if (text == null || text.length() == 0)
+ return fallback.calculate(content, parse);
StringBuffer curToken = new StringBuffer();
int maxFreq = 0;
for (int i = 0; i < text.length(); i++) {
@@ -87,7 +96,8 @@ public class TextProfileSignature extends Signature {
tokens.put(s, tok);
}
tok.cnt++;
- if (tok.cnt > maxFreq) maxFreq = tok.cnt;
+ if (tok.cnt > maxFreq)
+ maxFreq = tok.cnt;
}
curToken.setLength(0);
}
@@ -103,17 +113,20 @@ public class TextProfileSignature extends Signature {
tokens.put(s, tok);
}
tok.cnt++;
- if (tok.cnt > maxFreq) maxFreq = tok.cnt;
+ if (tok.cnt > maxFreq)
+ maxFreq = tok.cnt;
}
Iterator<Token> it = tokens.values().iterator();
ArrayList<Token> profile = new ArrayList<Token>();
// calculate the QUANT value
int QUANT = Math.round(maxFreq * QUANT_RATE);
if (QUANT < 2) {
- if (maxFreq > 1) QUANT = 2;
- else QUANT = 1;
+ if (maxFreq > 1)
+ QUANT = 2;
+ else
+ QUANT = 1;
}
- while(it.hasNext()) {
+ while (it.hasNext()) {
Token t = it.next();
// round down to the nearest QUANT
t.cnt = (t.cnt / QUANT) * QUANT;
@@ -128,32 +141,33 @@ public class TextProfileSignature extends Signature {
it = profile.iterator();
while (it.hasNext()) {
Token t = it.next();
- if (newText.length() > 0) newText.append("\n");
+ if (newText.length() > 0)
+ newText.append("\n");
newText.append(t.toString());
}
return MD5Hash.digest(newText.toString()).getDigest();
}
-
+
private static class Token {
public int cnt;
public String val;
-
+
public Token(int cnt, String val) {
this.cnt = cnt;
this.val = val;
}
-
+
public String toString() {
return val + " " + cnt;
}
}
-
+
private static class TokenComparator implements Comparator<Token> {
public int compare(Token t1, Token t2) {
return t2.cnt - t1.cnt;
}
}
-
+
public static void main(String[] args) throws Exception {
TextProfileSignature sig = new TextProfileSignature();
sig.setConf(NutchConfiguration.create());
@@ -161,15 +175,18 @@ public class TextProfileSignature extends Signature {
File[] files = new File(args[0]).listFiles();
for (int i = 0; i < files.length; i++) {
FileInputStream fis = new FileInputStream(files[i]);
- BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(fis, "UTF-8"));
StringBuffer text = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
- if (text.length() > 0) text.append("\n");
+ if (text.length() > 0)
+ text.append("\n");
text.append(line);
}
br.close();
- byte[] signature = sig.calculate(null, new ParseImpl(text.toString(), null));
+ byte[] signature = sig.calculate(null, new ParseImpl(text.toString(),
+ null));
res.put(files[i].toString(), signature);
}
Iterator<String> it = res.keySet().iterator();
diff --git a/src/java/org/apache/nutch/crawl/URLPartitioner.java b/src/java/org/apache/nutch/crawl/URLPartitioner.java
index c129a73a5..4675f8338 100644
--- a/src/java/org/apache/nutch/crawl/URLPartitioner.java
+++ b/src/java/org/apache/nutch/crawl/URLPartitioner.java
@@ -33,8 +33,9 @@ import org.apache.nutch.util.URLUtil;
* Partition urls by host, domain name or IP depending on the value of the
* parameter 'partition.url.mode' which can be 'byHost', 'byDomain' or 'byIP'
*/
-public class URLPartitioner implements Partitioner<Text,Writable> {
- private static final Logger LOG = LoggerFactory.getLogger(URLPartitioner.class);
+public class URLPartitioner implements Partitioner<Text, Writable> {
+ private static final Logger LOG = LoggerFactory
+ .getLogger(URLPartitioner.class);
public static final String PARTITION_MODE_KEY = "partition.url.mode";
@@ -58,7 +59,8 @@ public class URLPartitioner implements Partitioner<Text,Writable> {
normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_PARTITION);
}
- public void close() {}
+ public void close() {
+ }
/** Hash by domain name. */
public int getPartition(Text key, Writable value, int numReduceTasks) {
@@ -66,15 +68,16 @@ public class URLPartitioner implements Partitioner<Text,Writable> {
URL url = null;
int hashCode = urlString.hashCode();
try {
- urlString = normalizers.normalize(urlString, URLNormalizers.SCOPE_PARTITION);
+ urlString = normalizers.normalize(urlString,
+ URLNormalizers.SCOPE_PARTITION);
url = new URL(urlString);
hashCode = url.getHost().hashCode();
} catch (MalformedURLException e) {
LOG.warn("Malformed URL: '" + urlString + "'");
}
- if (mode.equals(PARTITION_MODE_DOMAIN) && url != null) hashCode = URLUtil
- .getDomainName(url).hashCode();
+ if (mode.equals(PARTITION_MODE_DOMAIN) && url != null)
+ hashCode = URLUtil.getDomainName(url).hashCode();
else if (mode.equals(PARTITION_MODE_IP)) {
try {
InetAddress address = InetAddress.getByName(url.getHost());
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index ce4f518b2..e714b434a 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -55,37 +55,40 @@ import crawlercommons.robots.BaseRobotRules;
/**
* A queue-based fetcher.
- *
- * <p>This fetcher uses a well-known model of one producer (a QueueFeeder)
- * and many consumers (FetcherThread-s).
- *
- * <p>QueueFeeder reads input fetchlists and
- * populates a set of FetchItemQueue-s, which hold FetchItem-s that
- * describe the items to be fetched. There are as many queues as there are unique
- * hosts, but at any given time the total number of fetch items in all queues
- * is less than a fixed number (currently set to a multiple of the number of
- * threads).
- *
- * <p>As items are consumed from the queues, the QueueFeeder continues to add new
+ *
+ * <p>
+ * This fetcher uses a well-known model of one producer (a QueueFeeder) and many
+ * consumers (FetcherThread-s).
+ *
+ * <p>
+ * QueueFeeder reads input fetchlists and populates a set of FetchItemQueue-s,
+ * which hold FetchItem-s that describe the items to be fetched. There are as
+ * many queues as there are unique hosts, but at any given time the total number
+ * of fetch items in all queues is less than a fixed number (currently set to a
+ * multiple of the number of threads).
+ *
+ * <p>
+ * As items are consumed from the queues, the QueueFeeder continues to add new
* input items, so that their total count stays fixed (FetcherThread-s may also
* add new items to the queues e.g. as a results of redirection) - until all
* input items are exhausted, at which point the number of items in the queues
* begins to decrease. When this number reaches 0 fetcher will finish.
- *
- * <p>This fetcher implementation handles per-host blocking itself, instead
- * of delegating this work to protocol-specific plugins.
- * Each per-host queue handles its own "politeness" settings, such as the
- * maximum number of concurrent requests and crawl delay between consecutive
- * requests - and also a list of requests in progress, and the time the last
- * request was finished. As FetcherThread-s ask for new items to be fetched,
- * queues may return eligible items or null if for "politeness" reasons this
- * host's queue is not yet ready.
- *
- * <p>If there are still unfetched items in the queues, but none of the items
- * are ready, FetcherThread-s will spin-wait until either some items become
+ *
+ * <p>
+ * This fetcher implementation handles per-host blocking itself, instead of
+ * delegating this work to protocol-specific plugins. Each per-host queue
+ * handles its own "politeness" settings, such as the maximum number of
+ * concurrent requests and crawl delay between consecutive requests - and also a
+ * list of requests in progress, and the time the last request was finished. As
+ * FetcherThread-s ask for new items to be fetched, queues may return eligible
+ * items or null if for "politeness" reasons this host's queue is not yet ready.
+ *
+ * <p>
+ * If there are still unfetched items in the queues, but none of the items are
+ * ready, FetcherThread-s will spin-wait until either some items become
* available, or a timeout is reached (at which point the Fetcher will abort,
* assuming the task is hung).
- *
+ *
* @author Andrzej Bialecki
*/
public class Fetcher extends Configured implements Tool,
@@ -99,16 +102,16 @@ public class Fetcher extends Configured implements Tool,
public static final Logger LOG = LoggerFactory.getLogger(Fetcher.class);
- public static class InputFormat extends SequenceFileInputFormat<Text, CrawlDatum> {
+ public static class InputFormat extends
+ SequenceFileInputFormat<Text, CrawlDatum> {
/** Don't split inputs, to keep things polite. */
- public InputSplit[] getSplits(JobConf job, int nSplits)
- throws IOException {
+ public InputSplit[] getSplits(JobConf job, int nSplits) throws IOException {
FileStatus[] files = listStatus(job);
FileSplit[] splits = new FileSplit[files.length];
for (int i = 0; i < files.length; i++) {
FileStatus cur = files[i];
- splits[i] = new FileSplit(cur.getPath(), 0,
- cur.getLen(), (String[])null);
+ splits[i] = new FileSplit(cur.getPath(), 0, cur.getLen(),
+ (String[]) null);
}
return splits;
}
@@ -124,8 +127,8 @@ public class Fetcher extends Configured implements Tool,
private long start = System.currentTimeMillis(); // start time of fetcher run
private AtomicLong lastRequestStart = new AtomicLong(start);
- private AtomicLong bytes = new AtomicLong(0); // total bytes fetched
- private AtomicInteger pages = new AtomicInteger(0); // total pages fetched
+ private AtomicLong bytes = new AtomicLong(0); // total bytes fetched
+ private AtomicInteger pages = new AtomicInteger(0); // total pages fetched
private AtomicInteger errors = new AtomicInteger(0); // total pages errored
private boolean storingContent;
@@ -149,7 +152,8 @@ public class Fetcher extends Configured implements Tool,
this(url, u, datum, queueID, 0);
}
- public FetchItem(Text url, URL u, CrawlDatum datum, String queueID, int outlinkDepth) {
+ public FetchItem(Text url, URL u, CrawlDatum datum, String queueID,
+ int outlinkDepth) {
this.url = url;
this.u = u;
this.datum = datum;
@@ -157,15 +161,17 @@ public class Fetcher extends Configured implements Tool,
this.outlinkDepth = outlinkDepth;
}
- /** Create an item. Queue id will be created based on <code>queueMode</code>
- * argument, either as a protocol + hostname pair, protocol + IP
- * address pair or protocol+domain pair.
+ /**
+ * Create an item. Queue id will be created based on <code>queueMode</code>
+ * argument, either as a protocol + hostname pair, protocol + IP address
+ * pair or protocol+domain pair.
*/
- public static FetchItem create(Text url, CrawlDatum datum, String queueMode) {
+ public static FetchItem create(Text url, CrawlDatum datum, String queueMode) {
return create(url, datum, queueMode, 0);
}
- public static FetchItem create(Text url, CrawlDatum datum, String queueMode, int outlinkDepth) {
+ public static FetchItem create(Text url, CrawlDatum datum,
+ String queueMode, int outlinkDepth) {
String queueID;
URL u = null;
try {
@@ -185,19 +191,18 @@ public class Fetcher extends Configured implements Tool,
LOG.warn("Unable to resolve: " + u.getHost() + ", skipping.");
return null;
}
- }
- else if (FetchItemQueues.QUEUE_MODE_DOMAIN.equalsIgnoreCase(queueMode)){
+ } else if (FetchItemQueues.QUEUE_MODE_DOMAIN.equalsIgnoreCase(queueMode)) {
key = URLUtil.getDomainName(u);
if (key == null) {
- LOG.warn("Unknown domain for url: " + url + ", using URL string as key");
- key=u.toExternalForm();
+ LOG.warn("Unknown domain for url: " + url
+ + ", using URL string as key");
+ key = u.toExternalForm();
}
- }
- else {
+ } else {
key = u.getHost();
if (key == null) {
LOG.warn("Unknown host for url: " + url + ", using URL string as key");
- key=u.toExternalForm();
+ key = u.toExternalForm();
}
}
queueID = proto + "://" + key.toLowerCase();
@@ -222,13 +227,14 @@ public class Fetcher extends Configured implements Tool,
}
/**
- * This class handles FetchItems which come from the same host ID (be it
- * a proto/hostname or proto/IP pair). It also keeps track of requests in
+ * This class handles FetchItems which come from the same host ID (be it a
+ * proto/hostname or proto/IP pair). It also keeps track of requests in
* progress and elapsed time between requests.
*/
private static class FetchItemQueue {
- List<FetchItem> queue = Collections.synchronizedList(new LinkedList<FetchItem>());
- AtomicInteger inProgress = new AtomicInteger();
+ List<FetchItem> queue = Collections
+ .synchronizedList(new LinkedList<FetchItem>());
+ AtomicInteger inProgress = new AtomicInteger();
AtomicLong nextFetchTime = new AtomicLong();
AtomicInteger exceptionCounter = new AtomicInteger();
long crawlDelay;
@@ -236,7 +242,8 @@ public class Fetcher extends Configured implements Tool,
int maxThreads;
Configuration conf;
- public FetchItemQueue(Configuration conf, int maxThreads, long crawlDelay, long minCrawlDelay) {
+ public FetchItemQueue(Configuration conf, int maxThreads, long crawlDelay,
+ long minCrawlDelay) {
this.conf = conf;
this.maxThreads = maxThreads;
this.crawlDelay = crawlDelay;
@@ -271,26 +278,33 @@ public class Fetcher extends Configured implements Tool,
}
public void addFetchItem(FetchItem it) {
- if (it == null) return;
+ if (it == null)
+ return;
queue.add(it);
}
public void addInProgressFetchItem(FetchItem it) {
- if (it == null) return;
+ if (it == null)
+ return;
inProgress.incrementAndGet();
}
public FetchItem getFetchItem() {
- if (inProgress.get() >= maxThreads) return null;
+ if (inProgress.get() >= maxThreads)
+ return null;
long now = System.currentTimeMillis();
- if (nextFetchTime.get() > now) return null;
+ if (nextFetchTime.get() > now)
+ return null;
FetchItem it = null;
- if (queue.size() == 0) return null;
+ if (queue.size() == 0)
+ return null;
try {
it = queue.remove(0);
inProgress.incrementAndGet();
} catch (Exception e) {
- LOG.error("Cannot remove FetchItem from queue or cannot add it to inProgress queue", e);
+ LOG.error(
+ "Cannot remove FetchItem from queue or cannot add it to inProgress queue",
+ e);
}
return it;
}
@@ -314,7 +328,8 @@ public class Fetcher extends Configured implements Tool,
private void setEndTime(long endTime, boolean asap) {
if (!asap)
- nextFetchTime.set(endTime + (maxThreads > 1 ? minCrawlDelay : crawlDelay));
+ nextFetchTime.set(endTime
+ + (maxThreads > 1 ? minCrawlDelay : crawlDelay));
else
nextFetchTime.set(endTime);
}
@@ -346,17 +361,21 @@ public class Fetcher extends Configured implements Tool,
this.maxThreads = conf.getInt("fetcher.threads.per.queue", 1);
queueMode = conf.get("fetcher.queue.mode", QUEUE_MODE_HOST);
// check that the mode is known
- if (!queueMode.equals(QUEUE_MODE_IP) && !queueMode.equals(QUEUE_MODE_DOMAIN)
+ if (!queueMode.equals(QUEUE_MODE_IP)
+ && !queueMode.equals(QUEUE_MODE_DOMAIN)
&& !queueMode.equals(QUEUE_MODE_HOST)) {
- LOG.error("Unknown partition mode : " + queueMode + " - forcing to byHost");
+ LOG.error("Unknown partition mode : " + queueMode
+ + " - forcing to byHost");
queueMode = QUEUE_MODE_HOST;
}
- LOG.info("Using queue mode : "+queueMode);
+ LOG.info("Using queue mode : " + queueMode);
this.crawlDelay = (long) (conf.getFloat("fetcher.server.delay", 1.0f) * 1000);
- this.minCrawlDelay = (long) (conf.getFloat("fetcher.server.min.delay", 0.0f) * 1000);
+ this.minCrawlDelay = (long) (conf.getFloat("fetcher.server.min.delay",
+ 0.0f) * 1000);
this.timelimit = conf.getLong("fetcher.timelimit", -1);
- this.maxExceptionsPerQueue = conf.getInt("fetcher.max.exceptions.per.queue", -1);
+ this.maxExceptionsPerQueue = conf.getInt(
+ "fetcher.max.exceptions.per.queue", -1);
}
public int getTotalSize() {
@@ -369,7 +388,8 @@ public class Fetcher extends Configured implements Tool,
public void addFetchItem(Text url, CrawlDatum datum) {
FetchItem it = FetchItem.create(url, datum, queueMode);
- if (it != null) addFetchItem(it);
+ if (it != null)
+ addFetchItem(it);
}
public synchronized void addFetchItem(FetchItem it) {
@@ -402,8 +422,8 @@ public class Fetcher extends Configured implements Tool,
}
public synchronized FetchItem getFetchItem() {
- Iterator<Map.Entry<String, FetchItemQueue>> it =
- queues.entrySet().iterator();
+ Iterator<Map.Entry<String, FetchItemQueue>> it = queues.entrySet()
+ .iterator();
while (it.hasNext()) {
FetchItemQueue fiq = it.next().getValue();
// reap empty queues
@@ -431,7 +451,8 @@ public class Fetcher extends Configured implements Tool,
// there might also be a case where totalsize !=0 but number of queues
// == 0
// in which case we simply force it to 0 to avoid blocking
- if (totalSize.get() != 0 && queues.size() == 0) totalSize.set(0);
+ if (totalSize.get() != 0 && queues.size() == 0)
+ totalSize.set(0);
}
return count;
}
@@ -442,7 +463,8 @@ public class Fetcher extends Configured implements Tool,
for (String id : queues.keySet()) {
FetchItemQueue fiq = queues.get(id);
- if (fiq.getQueueSize() == 0) continue;
+ if (fiq.getQueueSize() == 0)
+ continue;
LOG.info("* queue: " + id + " >> dropping! ");
int deleted = fiq.emptyQueue();
for (int i = 0; i < deleted; i++) {
@@ -457,7 +479,7 @@ public class Fetcher extends Configured implements Tool,
/**
* Increment the exception counter of a queue in case of an exception e.g.
* timeout; when higher than a given threshold simply empty the queue.
- *
+ *
* @param queueid
* @return number of purged items
*/
@@ -470,7 +492,7 @@ public class Fetcher extends Configured implements Tool,
return 0;
}
int excCount = fiq.incrementExceptionCounter();
- if (maxExceptionsPerQueue!= -1 && excCount >= maxExceptionsPerQueue) {
+ if (maxExceptionsPerQueue != -1 && excCount >= maxExceptionsPerQueue) {
// too many exceptions for items in this queue - purge it
int deleted = fiq.emptyQueue();
LOG.info("* queue: " + queueid + " >> removed " + deleted
@@ -483,11 +505,11 @@ public class Fetcher extends Configured implements Tool,
return 0;
}
-
public synchronized void dump() {
for (String id : queues.keySet()) {
FetchItemQueue fiq = queues.get(id);
- if (fiq.getQueueSize() == 0) continue;
+ if (fiq.getQueueSize() == 0)
+ continue;
LOG.info("* queue: " + id);
fiq.dump();
}
@@ -495,8 +517,8 @@ public class Fetcher extends Configured implements Tool,
}
/**
- * This class feeds the queues with input items, and re-fills them as
- * items are consumed by FetcherThread-s.
+ * This class feeds the queues with input items, and re-fills them as items
+ * are consumed by FetcherThread-s.
*/
private static class QueueFeeder extends Thread {
private RecordReader<Text, CrawlDatum> reader;
@@ -541,7 +563,9 @@ public class Fetcher extends Configured implements Tool,
// queues are full - spin-wait until they have some free space
try {
Thread.sleep(1000);
- } catch (Exception e) {};
+ } catch (Exception e) {
+ }
+ ;
continue;
} else {
LOG.debug("-feeding " + feed + " input urls ...");
@@ -562,8 +586,8 @@ public class Fetcher extends Configured implements Tool,
}
}
}
- LOG.info("QueueFeeder finished: total " + cnt + " records + hit by time limit :"
- + timelimitcount);
+ LOG.info("QueueFeeder finished: total " + cnt
+ + " records + hit by time limit :" + timelimitcount);
}
}
@@ -595,12 +619,12 @@ public class Fetcher extends Configured implements Tool,
private int outlinksDepthDivisor;
private boolean skipTruncated;
-
+
private boolean halted = false;
public FetcherThread(Configuration conf) {
- this.setDaemon(true); // don't hang JVM on exit
- this.setName("FetcherThread"); // use an informative name
+ this.setDaemon(true); // don't hang JVM on exit
+ this.setName("FetcherThread"); // use an informative name
this.conf = conf;
this.urlFilters = new URLFilters(conf);
this.scfilters = new ScoringFilters(conf);
@@ -609,26 +633,33 @@ public class Fetcher extends Configured implements Tool,
this.protocolFactory = new ProtocolFactory(conf);
this.normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_FETCHER);
this.maxCrawlDelay = conf.getInt("fetcher.max.crawl.delay", 30) * 1000;
- queueMode = conf.get("fetcher.queue.mode", FetchItemQueues.QUEUE_MODE_HOST);
+ queueMode = conf.get("fetcher.queue.mode",
+ FetchItemQueues.QUEUE_MODE_HOST);
// check that the mode is known
- if (!queueMode.equals(FetchItemQueues.QUEUE_MODE_IP) && !queueMode.equals(FetchItemQueues.QUEUE_MODE_DOMAIN)
+ if (!queueMode.equals(FetchItemQueues.QUEUE_MODE_IP)
+ && !queueMode.equals(FetchItemQueues.QUEUE_MODE_DOMAIN)
&& !queueMode.equals(FetchItemQueues.QUEUE_MODE_HOST)) {
- LOG.error("Unknown partition mode : " + queueMode + " - forcing to byHost");
+ LOG.error("Unknown partition mode : " + queueMode
+ + " - forcing to byHost");
queueMode = FetchItemQueues.QUEUE_MODE_HOST;
}
- LOG.info("Using queue mode : "+queueMode);
+ LOG.info("Using queue mode : " + queueMode);
this.maxRedirect = conf.getInt("http.redirect.max", 3);
- this.ignoreExternalLinks =
- conf.getBoolean("db.ignore.external.links", false);
+ this.ignoreExternalLinks = conf.getBoolean("db.ignore.external.links",
+ false);
maxOutlinksPerPage = conf.getInt("db.max.outlinks.per.page", 100);
- maxOutlinks = (maxOutlinksPerPage < 0) ? Integer.MAX_VALUE : maxOutlinksPerPage;
+ maxOutlinks = (maxOutlinksPerPage < 0) ? Integer.MAX_VALUE
+ : maxOutlinksPerPage;
interval = conf.getInt("db.fetch.interval.default", 2592000);
ignoreExternalLinks = conf.getBoolean("db.ignore.external.links", false);
maxOutlinkDepth = conf.getInt("fetcher.follow.outlinks.depth", -1);
- outlinksIgnoreExternal = conf.getBoolean("fetcher.follow.outlinks.ignore.external", false);
- maxOutlinkDepthNumLinks = conf.getInt("fetcher.follow.outlinks.num.links", 4);
- outlinksDepthDivisor = conf.getInt("fetcher.follow.outlinks.depth.divisor", 2);
+ outlinksIgnoreExternal = conf.getBoolean(
+ "fetcher.follow.outlinks.ignore.external", false);
+ maxOutlinkDepthNumLinks = conf.getInt(
+ "fetcher.follow.outlinks.num.links", 4);
+ outlinksDepthDivisor = conf.getInt(
+ "fetcher.follow.outlinks.depth.divisor", 2);
}
@SuppressWarnings("fallthrough")
@@ -645,7 +676,7 @@ public class Fetcher extends Configured implements Tool,
fit = null;
return;
}
-
+
fit = fetchQueues.getFetchItem();
if (fit == null) {
if (feeder.isAlive() || fetchQueues.getTotalSize() > 0) {
@@ -654,8 +685,9 @@ public class Fetcher extends Configured implements Tool,
spinWaiting.incrementAndGet();
try {
Thread.sleep(500);
- } catch (Exception e) {}
- spinWaiting.decrementAndGet();
+ } catch (Exception e) {
+ }
+ spinWaiting.decrementAndGet();
continue;
} else {
// all done, finish this thread
@@ -664,8 +696,8 @@ public class Fetcher extends Configured implements Tool,
}
}
lastRequestStart.set(System.currentTimeMillis());
- Text reprUrlWritable =
- (Text) fit.datum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
+ Text reprUrlWritable = (Text) fit.datum.getMetaData().get(
+ Nutch.WRITABLE_REPR_URL_KEY);
if (reprUrlWritable == null) {
reprUrl = fit.url.toString();
} else {
@@ -677,14 +709,16 @@ public class Fetcher extends Configured implements Tool,
redirectCount = 0;
do {
if (LOG.isInfoEnabled()) {
- LOG.info("fetching " + fit.url + " (queue crawl delay=" +
- fetchQueues.getFetchItemQueue(fit.queueID).crawlDelay + "ms)");
+ LOG.info("fetching " + fit.url + " (queue crawl delay="
+ + fetchQueues.getFetchItemQueue(fit.queueID).crawlDelay
+ + "ms)");
}
if (LOG.isDebugEnabled()) {
LOG.debug("redirectCount=" + redirectCount);
}
redirecting = false;
- Protocol protocol = this.protocolFactory.getProtocol(fit.url.toString());
+ Protocol protocol = this.protocolFactory.getProtocol(fit.url
+ .toString());
BaseRobotRules rules = protocol.getRobotRules(fit.url, fit.datum);
if (!rules.isAllowed(fit.u.toString())) {
// unblock
@@ -692,7 +726,9 @@ public class Fetcher extends Configured implements Tool,
if (LOG.isDebugEnabled()) {
LOG.debug("Denied by robots.txt: " + fit.url);
}
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_ROBOTS_DENIED, CrawlDatum.STATUS_FETCH_GONE);
+ output(fit.url, fit.datum, null,
+ ProtocolStatus.STATUS_ROBOTS_DENIED,
+ CrawlDatum.STATUS_FETCH_GONE);
reporter.incrCounter("FetcherStatus", "robots_denied", 1);
continue;
}
@@ -700,19 +736,27 @@ public class Fetcher extends Configured implements Tool,
if (rules.getCrawlDelay() > maxCrawlDelay && maxCrawlDelay >= 0) {
// unblock
fetchQueues.finishFetchItem(fit, true);
- LOG.debug("Crawl-Delay for " + fit.url + " too long (" + rules.getCrawlDelay() + "), skipping");
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_ROBOTS_DENIED, CrawlDatum.STATUS_FETCH_GONE);
- reporter.incrCounter("FetcherStatus", "robots_denied_maxcrawldelay", 1);
+ LOG.debug("Crawl-Delay for " + fit.url + " too long ("
+ + rules.getCrawlDelay() + "), skipping");
+ output(fit.url, fit.datum, null,
+ ProtocolStatus.STATUS_ROBOTS_DENIED,
+ CrawlDatum.STATUS_FETCH_GONE);
+ reporter.incrCounter("FetcherStatus",
+ "robots_denied_maxcrawldelay", 1);
continue;
} else {
- FetchItemQueue fiq = fetchQueues.getFetchItemQueue(fit.queueID);
+ FetchItemQueue fiq = fetchQueues
+ .getFetchItemQueue(fit.queueID);
fiq.crawlDelay = rules.getCrawlDelay();
if (LOG.isDebugEnabled()) {
- LOG.info("Crawl delay for queue: " + fit.queueID + " is set to " + fiq.crawlDelay + " as per robots.txt. url: " + fit.url);
+ LOG.info("Crawl delay for queue: " + fit.queueID
+ + " is set to " + fiq.crawlDelay
+ + " as per robots.txt. url: " + fit.url);
}
}
}
- ProtocolOutput output = protocol.getProtocolOutput(fit.url, fit.datum);
+ ProtocolOutput output = protocol.getProtocolOutput(fit.url,
+ fit.datum);
ProtocolStatus status = output.getStatus();
Content content = output.getContent();
ParseStatus pstatus = null;
@@ -723,32 +767,31 @@ public class Fetcher extends Configured implements Tool,
reporter.incrCounter("FetcherStatus", status.getName(), 1);
- switch(status.getCode()) {
+ switch (status.getCode()) {
case ProtocolStatus.WOULDBLOCK:
// retry ?
fetchQueues.addFetchItem(fit);
break;
- case ProtocolStatus.SUCCESS: // got a page
- pstatus = output(fit.url, fit.datum, content, status, CrawlDatum.STATUS_FETCH_SUCCESS, fit.outlinkDepth);
+ case ProtocolStatus.SUCCESS: // got a page
+ pstatus = output(fit.url, fit.datum, content, status,
+ CrawlDatum.STATUS_FETCH_SUCCESS, fit.outlinkDepth);
updateStatus(content.getContent().length);
- if (pstatus != null && pstatus.isSuccess() &&
- pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
+ if (pstatus != null && pstatus.isSuccess()
+ && pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
String newUrl = pstatus.getMessage();
int refreshTime = Integer.valueOf(pstatus.getArgs()[1]);
- Text redirUrl =
- handleRedirect(fit.url, fit.datum,
- urlString, newUrl,
- refreshTime < Fetcher.PERM_REFRESH_TIME,
- Fetcher.CONTENT_REDIR);
+ Text redirUrl = handleRedirect(fit.url, fit.datum, urlString,
+ newUrl, refreshTime < Fetcher.PERM_REFRESH_TIME,
+ Fetcher.CONTENT_REDIR);
if (redirUrl != null) {
queueRedirect(redirUrl, fit);
}
}
break;
- case ProtocolStatus.MOVED: // redirect
+ case ProtocolStatus.MOVED: // redirect
case ProtocolStatus.TEMP_MOVED:
int code;
boolean temp;
@@ -761,10 +804,8 @@ public class Fetcher extends Configured implements Tool,
}
output(fit.url, fit.datum, content, status, code);
String newUrl = status.getMessage();
- Text redirUrl =
- handleRedirect(fit.url, fit.datum,
- urlString, newUrl, temp,
- Fetcher.PROTOCOL_REDIR);
+ Text redirUrl = handleRedirect(fit.url, fit.datum, urlString,
+ newUrl, temp, Fetcher.PROTOCOL_REDIR);
if (redirUrl != null) {
queueRedirect(redirUrl, fit);
} else {
@@ -775,31 +816,37 @@ public class Fetcher extends Configured implements Tool,
case ProtocolStatus.EXCEPTION:
logError(fit.url, status.getMessage());
- int killedURLs = fetchQueues.checkExceptionThreshold(fit.getQueueID());
- if (killedURLs!=0)
- reporter.incrCounter("FetcherStatus", "AboveExceptionThresholdInQueue", killedURLs);
+ int killedURLs = fetchQueues.checkExceptionThreshold(fit
+ .getQueueID());
+ if (killedURLs != 0)
+ reporter.incrCounter("FetcherStatus",
+ "AboveExceptionThresholdInQueue", killedURLs);
/* FALLTHROUGH */
- case ProtocolStatus.RETRY: // retry
+ case ProtocolStatus.RETRY: // retry
case ProtocolStatus.BLOCKED:
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_RETRY);
+ output(fit.url, fit.datum, null, status,
+ CrawlDatum.STATUS_FETCH_RETRY);
break;
- case ProtocolStatus.GONE: // gone
+ case ProtocolStatus.GONE: // gone
case ProtocolStatus.NOTFOUND:
case ProtocolStatus.ACCESS_DENIED:
case ProtocolStatus.ROBOTS_DENIED:
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_GONE);
+ output(fit.url, fit.datum, null, status,
+ CrawlDatum.STATUS_FETCH_GONE);
break;
case ProtocolStatus.NOTMODIFIED:
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_NOTMODIFIED);
+ output(fit.url, fit.datum, null, status,
+ CrawlDatum.STATUS_FETCH_NOTMODIFIED);
break;
default:
if (LOG.isWarnEnabled()) {
LOG.warn("Unknown ProtocolStatus: " + status.getCode());
}
- output(fit.url, fit.datum, null, status, CrawlDatum.STATUS_FETCH_RETRY);
+ output(fit.url, fit.datum, null, status,
+ CrawlDatum.STATUS_FETCH_RETRY);
}
if (redirecting && redirectCount > maxRedirect) {
@@ -807,34 +854,38 @@ public class Fetcher extends Configured implements Tool,
if (LOG.isInfoEnabled()) {
LOG.info(" - redirect count exceeded " + fit.url);
}
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_REDIR_EXCEEDED, CrawlDatum.STATUS_FETCH_GONE);
+ output(fit.url, fit.datum, null,
+ ProtocolStatus.STATUS_REDIR_EXCEEDED,
+ CrawlDatum.STATUS_FETCH_GONE);
}
} while (redirecting && (redirectCount <= maxRedirect));
- } catch (Throwable t) { // unexpected exception
+ } catch (Throwable t) { // unexpected exception
// unblock
fetchQueues.finishFetchItem(fit);
logError(fit.url, StringUtils.stringifyException(t));
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_FAILED, CrawlDatum.STATUS_FETCH_RETRY);
+ output(fit.url, fit.datum, null, ProtocolStatus.STATUS_FAILED,
+ CrawlDatum.STATUS_FETCH_RETRY);
}
}
} catch (Throwable e) {
if (LOG.isErrorEnabled()) {
- LOG.error("fetcher caught:"+e.toString());
+ LOG.error("fetcher caught:" + e.toString());
}
} finally {
- if (fit != null) fetchQueues.finishFetchItem(fit);
+ if (fit != null)
+ fetchQueues.finishFetchItem(fit);
activeThreads.decrementAndGet(); // count threads
- LOG.info("-finishing thread " + getName() + ", activeThreads=" + activeThreads);
+ LOG.info("-finishing thread " + getName() + ", activeThreads="
+ + activeThreads);
}
}
- private Text handleRedirect(Text url, CrawlDatum datum,
- String urlString, String newUrl,
- boolean temp, String redirType)
- throws MalformedURLException, URLFilterException {
+ private Text handleRedirect(Text url, CrawlDatum datum, String urlString,
+ String newUrl, boolean temp, String redirType)
+ throws MalformedURLException, URLFilterException {
newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);
newUrl = urlFilters.filter(newUrl);
@@ -844,13 +895,14 @@ public class Fetcher extends Configured implements Tool,
String newHost = new URL(newUrl).getHost().toLowerCase();
if (!origHost.equals(newHost)) {
if (LOG.isDebugEnabled()) {
- LOG.debug(" - ignoring redirect " + redirType + " from " +
- urlString + " to " + newUrl +
- " because external links are ignored");
+ LOG.debug(" - ignoring redirect " + redirType + " from "
+ + urlString + " to " + newUrl
+ + " because external links are ignored");
}
return null;
}
- } catch (MalformedURLException e) { }
+ } catch (MalformedURLException e) {
+ }
}
if (newUrl != null && !newUrl.equals(urlString)) {
@@ -860,13 +912,13 @@ public class Fetcher extends Configured implements Tool,
redirecting = true;
redirectCount++;
if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching now)");
+ LOG.debug(" - " + redirType + " redirect to " + url
+ + " (fetching now)");
}
return url;
} else {
CrawlDatum newDatum = new CrawlDatum(CrawlDatum.STATUS_LINKED,
- datum.getFetchInterval(),datum.getScore());
+ datum.getFetchInterval(), datum.getScore());
// transfer existing metadata
newDatum.getMetaData().putAll(datum.getMetaData());
try {
@@ -880,21 +932,22 @@ public class Fetcher extends Configured implements Tool,
}
output(url, newDatum, null, null, CrawlDatum.STATUS_LINKED);
if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching later)");
+ LOG.debug(" - " + redirType + " redirect to " + url
+ + " (fetching later)");
}
return null;
}
} else {
if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect skipped: " +
- (newUrl != null ? "to same url" : "filtered"));
+ LOG.debug(" - " + redirType + " redirect skipped: "
+ + (newUrl != null ? "to same url" : "filtered"));
}
return null;
}
}
- private void queueRedirect(Text redirUrl, FetchItem fit) throws ScoringFilterException {
+ private void queueRedirect(Text redirUrl, FetchItem fit)
+ throws ScoringFilterException {
CrawlDatum newDatum = new CrawlDatum(CrawlDatum.STATUS_DB_UNFETCHED,
fit.datum.getFetchInterval(), fit.datum.getScore());
// transfer all existing metadata to the redirect
@@ -906,13 +959,13 @@ public class Fetcher extends Configured implements Tool,
}
fit = FetchItem.create(redirUrl, newDatum, queueMode);
if (fit != null) {
- FetchItemQueue fiq =
- fetchQueues.getFetchItemQueue(fit.queueID);
+ FetchItemQueue fiq = fetchQueues.getFetchItemQueue(fit.queueID);
fiq.addInProgressFetchItem(fit);
} else {
// stop redirecting
redirecting = false;
- reporter.incrCounter("FetcherStatus", "FetchItem.notCreated.redirect", 1);
+ reporter.incrCounter("FetcherStatus", "FetchItem.notCreated.redirect",
+ 1);
}
}
@@ -923,26 +976,29 @@ public class Fetcher extends Configured implements Tool,
errors.incrementAndGet();
}
- private ParseStatus output(Text key, CrawlDatum datum,
- Content content, ProtocolStatus pstatus, int status) {
+ private ParseStatus output(Text key, CrawlDatum datum, Content content,
+ ProtocolStatus pstatus, int status) {
return output(key, datum, content, pstatus, status, 0);
}
- private ParseStatus output(Text key, CrawlDatum datum,
- Content content, ProtocolStatus pstatus, int status, int outlinkDepth) {
+ private ParseStatus output(Text key, CrawlDatum datum, Content content,
+ ProtocolStatus pstatus, int status, int outlinkDepth) {
datum.setStatus(status);
datum.setFetchTime(System.currentTimeMillis());
- if (pstatus != null) datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
-
+ if (pstatus != null)
+ datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
+
ParseResult parseResult = null;
if (content != null) {
Metadata metadata = content.getMetadata();
-
+
// store the guessed content type in the crawldatum
- if (content.getContentType() != null) datum.getMetaData().put(new Text(Metadata.CONTENT_TYPE), new Text(content.getContentType()));
-
+ if (content.getContentType() != null)
+ datum.getMetaData().put(new Text(Metadata.CONTENT_TYPE),
+ new Text(content.getContentType()));
+
// add segment to metadata
metadata.set(Nutch.SEGMENT_NAME_KEY, segmentName);
// add score to content metadata so that ParseSegment can pick it up.
@@ -953,29 +1009,34 @@ public class Fetcher extends Configured implements Tool,
LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
}
}
- /* Note: Fetcher will only follow meta-redirects coming from the
- * original URL. */
+ /*
+ * Note: Fetcher will only follow meta-redirects coming from the
+ * original URL.
+ */
if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {
- if (!skipTruncated || (skipTruncated && !ParseSegment.isTruncated(content))) {
+ if (!skipTruncated
+ || (skipTruncated && !ParseSegment.isTruncated(content))) {
try {
parseResult = this.parseUtil.parse(content);
} catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": " + StringUtils.stringifyException(e));
+ LOG.warn("Error parsing: " + key + ": "
+ + StringUtils.stringifyException(e));
}
}
-
+
if (parseResult == null) {
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content,
- new ParseStatus().getEmptyParse(conf));
+ byte[] signature = SignatureFactory.getSignature(getConf())
+ .calculate(content, new ParseStatus().getEmptyParse(conf));
datum.setSignature(signature);
}
}
- /* Store status code in content So we can read this value during
- * parsing (as a separate job) and decide to parse or not.
+ /*
+ * Store status code in content So we can read this value during parsing
+ * (as a separate job) and decide to parse or not.
*/
- content.getMetadata().add(Nutch.FETCH_STATUS_KEY, Integer.toString(status));
+ content.getMetadata().add(Nutch.FETCH_STATUS_KEY,
+ Integer.toString(status));
}
try {
@@ -996,11 +1057,10 @@ public class Fetcher extends Configured implements Tool,
// Calculate page signature. For non-parsing fetchers this will
// be done in ParseSegment
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content, parse);
+ byte[] signature = SignatureFactory.getSignature(getConf())
+ .calculate(content, parse);
// Ensure segment name and score are in parseData metadata
- parseData.getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
- segmentName);
+ parseData.getContentMeta().set(Nutch.SEGMENT_NAME_KEY, segmentName);
parseData.getContentMeta().set(Nutch.SIGNATURE_KEY,
StringUtil.toHexString(signature));
// Pass fetch time to content meta
@@ -1039,7 +1099,8 @@ public class Fetcher extends Configured implements Tool,
for (int i = 0; i < links.length && validCount < outlinksToStore; i++) {
String toUrl = links[i].getToUrl();
- toUrl = ParseOutputFormat.filterNormalize(url.toString(), toUrl, fromHost, ignoreExternalLinks, urlFilters, normalizers);
+ toUrl = ParseOutputFormat.filterNormalize(url.toString(), toUrl,
+ fromHost, ignoreExternalLinks, urlFilters, normalizers);
if (toUrl == null) {
continue;
}
@@ -1052,49 +1113,57 @@ public class Fetcher extends Configured implements Tool,
// Only process depth N outlinks
if (maxOutlinkDepth > 0 && outlinkDepth < maxOutlinkDepth) {
- reporter.incrCounter("FetcherOutlinks", "outlinks_detected", outlinks.size());
+ reporter.incrCounter("FetcherOutlinks", "outlinks_detected",
+ outlinks.size());
// Counter to limit num outlinks to follow per page
int outlinkCounter = 0;
- // Calculate variable number of outlinks by depth using the divisor (outlinks = Math.floor(divisor / depth * num.links))
- int maxOutlinksByDepth = (int)Math.floor(outlinksDepthDivisor / (outlinkDepth + 1) * maxOutlinkDepthNumLinks);
+ // Calculate variable number of outlinks by depth using the
+ // divisor (outlinks = Math.floor(divisor / depth * num.links))
+ int maxOutlinksByDepth = (int) Math.floor(outlinksDepthDivisor
+ / (outlinkDepth + 1) * maxOutlinkDepthNumLinks);
String followUrl;
// Walk over the outlinks and add as new FetchItem to the queues
Iterator<String> iter = outlinks.iterator();
- while(iter.hasNext() && outlinkCounter < maxOutlinkDepthNumLinks) {
+ while (iter.hasNext() && outlinkCounter < maxOutlinkDepthNumLinks) {
followUrl = iter.next();
// Check whether we'll follow external outlinks
if (outlinksIgnoreExternal) {
- if (!URLUtil.getHost(url.toString()).equals(URLUtil.getHost(followUrl))) {
+ if (!URLUtil.getHost(url.toString()).equals(
+ URLUtil.getHost(followUrl))) {
continue;
}
}
- reporter.incrCounter("FetcherOutlinks", "outlinks_following", 1);
+ reporter
+ .incrCounter("FetcherOutlinks", "outlinks_following", 1);
// Create new FetchItem with depth incremented
- FetchItem fit = FetchItem.create(new Text(followUrl), new CrawlDatum(CrawlDatum.STATUS_LINKED, interval), queueMode, outlinkDepth + 1);
+ FetchItem fit = FetchItem.create(new Text(followUrl),
+ new CrawlDatum(CrawlDatum.STATUS_LINKED, interval),
+ queueMode, outlinkDepth + 1);
fetchQueues.addFetchItem(fit);
outlinkCounter++;
}
}
- // Overwrite the outlinks in ParseData with the normalized and filtered set
- parseData.setOutlinks(outlinkList.toArray(new Outlink[outlinkList.size()]));
+ // Overwrite the outlinks in ParseData with the normalized and
+ // filtered set
+ parseData.setOutlinks(outlinkList.toArray(new Outlink[outlinkList
+ .size()]));
- output.collect(url, new NutchWritable(
- new ParseImpl(new ParseText(parse.getText()),
- parseData, parse.isCanonical())));
+ output.collect(url, new NutchWritable(new ParseImpl(new ParseText(
+ parse.getText()), parseData, parse.isCanonical())));
}
}
} catch (IOException e) {
if (LOG.isErrorEnabled()) {
- LOG.error("fetcher caught:"+e.toString());
+ LOG.error("fetcher caught:" + e.toString());
}
}
@@ -1102,7 +1171,8 @@ public class Fetcher extends Configured implements Tool,
if (parseResult != null && !parseResult.isEmpty()) {
Parse p = parseResult.get(content.getUrl());
if (p != null) {
- reporter.incrCounter("ParserStatus", ParseStatus.majorCodes[p.getData().getStatus().getMajorCode()], 1);
+ reporter.incrCounter("ParserStatus", ParseStatus.majorCodes[p
+ .getData().getStatus().getMajorCode()], 1);
return p.getData().getStatus();
}
}
@@ -1116,33 +1186,39 @@ public class Fetcher extends Configured implements Tool,
public synchronized boolean isHalted() {
return halted;
}
-
+
}
- public Fetcher() { super(null); }
+ public Fetcher() {
+ super(null);
+ }
- public Fetcher(Configuration conf) { super(conf); }
+ public Fetcher(Configuration conf) {
+ super(conf);
+ }
private void updateStatus(int bytesInPage) throws IOException {
pages.incrementAndGet();
bytes.addAndGet(bytesInPage);
}
-
- private void reportStatus(int pagesLastSec, int bytesLastSec) throws IOException {
+ private void reportStatus(int pagesLastSec, int bytesLastSec)
+ throws IOException {
StringBuilder status = new StringBuilder();
- Long elapsed = new Long((System.currentTimeMillis() - start)/1000);
+ Long elapsed = new Long((System.currentTimeMillis() - start) / 1000);
- float avgPagesSec = (float) pages.get() / elapsed.floatValue();
- long avgBytesSec = (bytes.get() /125l) / elapsed.longValue();
+ float avgPagesSec = (float) pages.get() / elapsed.floatValue();
+ long avgBytesSec = (bytes.get() / 125l) / elapsed.longValue();
- status.append(activeThreads).append(" threads (").append(spinWaiting.get()).append(" waiting), ");
+ status.append(activeThreads).append(" threads (").append(spinWaiting.get())
+ .append(" waiting), ");
status.append(fetchQueues.getQueueCount()).append(" queues, ");
status.append(fetchQueues.getTotalSize()).append(" URLs queued, ");
status.append(pages).append(" pages, ").append(errors).append(" errors, ");
status.append(String.format("%.2f", avgPagesSec)).append(" pages/s (");
status.append(pagesLastSec).append(" last sec), ");
- status.append(avgBytesSec).append(" kbits/s (").append((bytesLastSec / 125)).append(" last sec)");
+ status.append(avgBytesSec).append(" kbits/s (")
+ .append((bytesLastSec / 125)).append(" last sec)");
reporter.setStatus(status.toString());
}
@@ -1154,12 +1230,13 @@ public class Fetcher extends Configured implements Tool,
this.storingContent = isStoringContent(job);
this.parsing = isParsing(job);
-// if (job.getBoolean("fetcher.verbose", false)) {
-// LOG.setLevel(Level.FINE);
-// }
+ // if (job.getBoolean("fetcher.verbose", false)) {
+ // LOG.setLevel(Level.FINE);
+ // }
}
- public void close() {}
+ public void close() {
+ }
public static boolean isParsing(Configuration conf) {
return conf.getBoolean("fetcher.parse", true);
@@ -1170,43 +1247,53 @@ public class Fetcher extends Configured implements Tool,
}
public void run(RecordReader<Text, CrawlDatum> input,
- OutputCollector<Text, NutchWritable> output,
- Reporter reporter) throws IOException {
+ OutputCollector<Text, NutchWritable> output, Reporter reporter)
+ throws IOException {
this.output = output;
this.reporter = reporter;
this.fetchQueues = new FetchItemQueues(getConf());
int threadCount = getConf().getInt("fetcher.threads.fetch", 10);
- if (LOG.isInfoEnabled()) { LOG.info("Fetcher: threads: " + threadCount); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: threads: " + threadCount);
+ }
int timeoutDivisor = getConf().getInt("fetcher.threads.timeout.divisor", 2);
- if (LOG.isInfoEnabled()) { LOG.info("Fetcher: time-out divisor: " + timeoutDivisor); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: time-out divisor: " + timeoutDivisor);
+ }
- int queueDepthMuliplier = getConf().getInt("fetcher.queue.depth.multiplier", 50);
+ int queueDepthMuliplier = getConf().getInt(
+ "fetcher.queue.depth.multiplier", 50);
- feeder = new QueueFeeder(input, fetchQueues, threadCount * queueDepthMuliplier);
- //feeder.setPriority((Thread.MAX_PRIORITY + Thread.NORM_PRIORITY) / 2);
+ feeder = new QueueFeeder(input, fetchQueues, threadCount
+ * queueDepthMuliplier);
+ // feeder.setPriority((Thread.MAX_PRIORITY + Thread.NORM_PRIORITY) / 2);
- // the value of the time limit is either -1 or the time where it should finish
+ // the value of the time limit is either -1 or the time where it should
+ // finish
long timelimit = getConf().getLong("fetcher.timelimit", -1);
- if (timelimit != -1) feeder.setTimeLimit(timelimit);
+ if (timelimit != -1)
+ feeder.setTimeLimit(timelimit);
feeder.start();
// set non-blocking & no-robots mode for HTTP protocol plugins.
getConf().setBoolean(Protocol.CHECK_BLOCKING, false);
getConf().setBoolean(Protocol.CHECK_ROBOTS, false);
- for (int i = 0; i < threadCount; i++) { // spawn threads
+ for (int i = 0; i < threadCount; i++) { // spawn threads
FetcherThread t = new FetcherThread(getConf());
fetcherThreads.add(t);
t.start();
}
// select a timeout that avoids a task timeout
- long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/timeoutDivisor;
+ long timeout = getConf().getInt("mapred.task.timeout", 10 * 60 * 1000)
+ / timeoutDivisor;
- // Used for threshold check, holds pages and bytes processed in the last second
+ // Used for threshold check, holds pages and bytes processed in the last
+ // second
int pagesLastSec;
int bytesLastSec;
@@ -1214,57 +1301,74 @@ public class Fetcher extends Configured implements Tool,
boolean throughputThresholdExceeded = false;
int throughputThresholdNumRetries = 0;
- int throughputThresholdPages = getConf().getInt("fetcher.throughput.threshold.pages", -1);
- if (LOG.isInfoEnabled()) { LOG.info("Fetcher: throughput threshold: " + throughputThresholdPages); }
- int throughputThresholdMaxRetries = getConf().getInt("fetcher.throughput.threshold.retries", 5);
- if (LOG.isInfoEnabled()) { LOG.info("Fetcher: throughput threshold retries: " + throughputThresholdMaxRetries); }
- long throughputThresholdTimeLimit = getConf().getLong("fetcher.throughput.threshold.check.after", -1);
-
+ int throughputThresholdPages = getConf().getInt(
+ "fetcher.throughput.threshold.pages", -1);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: throughput threshold: " + throughputThresholdPages);
+ }
+ int throughputThresholdMaxRetries = getConf().getInt(
+ "fetcher.throughput.threshold.retries", 5);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: throughput threshold retries: "
+ + throughputThresholdMaxRetries);
+ }
+ long throughputThresholdTimeLimit = getConf().getLong(
+ "fetcher.throughput.threshold.check.after", -1);
+
int targetBandwidth = getConf().getInt("fetcher.bandwidth.target", -1) * 1000;
int maxNumThreads = getConf().getInt("fetcher.maxNum.threads", threadCount);
- if (maxNumThreads < threadCount){
- LOG.info("fetcher.maxNum.threads can't be < than "+ threadCount + " : using "+threadCount+" instead");
+ if (maxNumThreads < threadCount) {
+ LOG.info("fetcher.maxNum.threads can't be < than " + threadCount
+ + " : using " + threadCount + " instead");
maxNumThreads = threadCount;
}
- int bandwidthTargetCheckEveryNSecs = getConf().getInt("fetcher.bandwidth.target.check.everyNSecs", 30);
- if (bandwidthTargetCheckEveryNSecs < 1){
+ int bandwidthTargetCheckEveryNSecs = getConf().getInt(
+ "fetcher.bandwidth.target.check.everyNSecs", 30);
+ if (bandwidthTargetCheckEveryNSecs < 1) {
LOG.info("fetcher.bandwidth.target.check.everyNSecs can't be < to 1 : using 1 instead");
bandwidthTargetCheckEveryNSecs = 1;
}
-
+
int maxThreadsPerQueue = getConf().getInt("fetcher.threads.per.queue", 1);
-
+
int bandwidthTargetCheckCounter = 0;
long bytesAtLastBWTCheck = 0l;
-
- do { // wait for threads to exit
+
+ do { // wait for threads to exit
pagesLastSec = pages.get();
- bytesLastSec = (int)bytes.get();
+ bytesLastSec = (int) bytes.get();
try {
Thread.sleep(1000);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
pagesLastSec = pages.get() - pagesLastSec;
- bytesLastSec = (int)bytes.get() - bytesLastSec;
+ bytesLastSec = (int) bytes.get() - bytesLastSec;
reporter.incrCounter("FetcherStatus", "bytes_downloaded", bytesLastSec);
reportStatus(pagesLastSec, bytesLastSec);
- LOG.info("-activeThreads=" + activeThreads + ", spinWaiting=" + spinWaiting.get()
- + ", fetchQueues.totalSize=" + fetchQueues.getTotalSize()+ ", fetchQueues.getQueueCount="+fetchQueues.getQueueCount());
+ LOG.info("-activeThreads=" + activeThreads + ", spinWaiting="
+ + spinWaiting.get() + ", fetchQueues.totalSize="
+ + fetchQueues.getTotalSize() + ", fetchQueues.getQueueCount="
+ + fetchQueues.getQueueCount());
if (!feeder.isAlive() && fetchQueues.getTotalSize() < 5) {
fetchQueues.dump();
}
// if throughput threshold is enabled
- if (throughputThresholdTimeLimit < System.currentTimeMillis() && throughputThresholdPages != -1) {
+ if (throughputThresholdTimeLimit < System.currentTimeMillis()
+ && throughputThresholdPages != -1) {
// Check if we're dropping below the threshold
if (pagesLastSec < throughputThresholdPages) {
throughputThresholdNumRetries++;
- LOG.warn(Integer.toString(throughputThresholdNumRetries) + ": dropping below configured threshold of " + Integer.toString(throughputThresholdPages) + " pages per second");
+ LOG.warn(Integer.toString(throughputThresholdNumRetries)
+ + ": dropping below configured threshold of "
+ + Integer.toString(throughputThresholdPages)
+ + " pages per second");
// Quit if we dropped below threshold too many times
if (throughputThresholdNumRetries == throughputThresholdMaxRetries) {
@@ -1273,42 +1377,55 @@ public class Fetcher extends Configured implements Tool,
// Disable the threshold checker
throughputThresholdPages = -1;
- // Empty the queues cleanly and get number of items that were dropped
+ // Empty the queues cleanly and get number of items that were
+ // dropped
int hitByThrougputThreshold = fetchQueues.emptyQueues();
- if (hitByThrougputThreshold != 0) reporter.incrCounter("FetcherStatus",
- "hitByThrougputThreshold", hitByThrougputThreshold);
+ if (hitByThrougputThreshold != 0)
+ reporter.incrCounter("FetcherStatus", "hitByThrougputThreshold",
+ hitByThrougputThreshold);
}
}
}
-
+
// adjust the number of threads if a target bandwidth has been set
- if (targetBandwidth>0) {
- if (bandwidthTargetCheckCounter < bandwidthTargetCheckEveryNSecs) bandwidthTargetCheckCounter++;
- else if (bandwidthTargetCheckCounter == bandwidthTargetCheckEveryNSecs){
- long bpsSinceLastCheck = ((bytes.get() - bytesAtLastBWTCheck) * 8)/bandwidthTargetCheckEveryNSecs;
+ if (targetBandwidth > 0) {
+ if (bandwidthTargetCheckCounter < bandwidthTargetCheckEveryNSecs)
+ bandwidthTargetCheckCounter++;
+ else if (bandwidthTargetCheckCounter == bandwidthTargetCheckEveryNSecs) {
+ long bpsSinceLastCheck = ((bytes.get() - bytesAtLastBWTCheck) * 8)
+ / bandwidthTargetCheckEveryNSecs;
bytesAtLastBWTCheck = bytes.get();
bandwidthTargetCheckCounter = 0;
int averageBdwPerThread = 0;
- if (activeThreads.get()>0)
- averageBdwPerThread = Math.round(bpsSinceLastCheck/activeThreads.get());
+ if (activeThreads.get() > 0)
+ averageBdwPerThread = Math.round(bpsSinceLastCheck
+ / activeThreads.get());
- LOG.info("averageBdwPerThread : "+(averageBdwPerThread/1000) + " kbps");
+ LOG.info("averageBdwPerThread : " + (averageBdwPerThread / 1000)
+ + " kbps");
- if (bpsSinceLastCheck < targetBandwidth && averageBdwPerThread > 0){
+ if (bpsSinceLastCheck < targetBandwidth && averageBdwPerThread > 0) {
// check whether it is worth doing e.g. more queues than threads
- if ((fetchQueues.getQueueCount() * maxThreadsPerQueue) > activeThreads.get()){
-
+ if ((fetchQueues.getQueueCount() * maxThreadsPerQueue) > activeThreads
+ .get()) {
+
long remainingBdw = targetBandwidth - bpsSinceLastCheck;
- int additionalThreads = Math.round(remainingBdw/averageBdwPerThread);
+ int additionalThreads = Math.round(remainingBdw
+ / averageBdwPerThread);
int availableThreads = maxNumThreads - activeThreads.get();
- // determine the number of available threads (min between availableThreads and additionalThreads)
- additionalThreads = (availableThreads < additionalThreads ? availableThreads:additionalThreads);
- LOG.info("Has space for more threads ("+(bpsSinceLastCheck/1000) +" vs "+(targetBandwidth/1000)+" kbps) \t=> adding "+additionalThreads+" new threads");
+ // determine the number of available threads (min between
+ // availableThreads and additionalThreads)
+ additionalThreads = (availableThreads < additionalThreads ? availableThreads
+ : additionalThreads);
+ LOG.info("Has space for more threads ("
+ + (bpsSinceLastCheck / 1000) + " vs "
+ + (targetBandwidth / 1000) + " kbps) \t=> adding "
+ + additionalThreads + " new threads");
// activate new threads
for (int i = 0; i < additionalThreads; i++) {
FetcherThread thread = new FetcherThread(getConf());
@@ -1316,14 +1433,18 @@ public class Fetcher extends Configured implements Tool,
thread.start();
}
}
- }
- else if (bpsSinceLastCheck > targetBandwidth && averageBdwPerThread > 0){
- // if the bandwidth we're using is greater then the expected bandwidth, we have to stop some threads
+ } else if (bpsSinceLastCheck > targetBandwidth
+ && averageBdwPerThread > 0) {
+ // if the bandwidth we're using is greater then the expected
+ // bandwidth, we have to stop some threads
long excessBdw = bpsSinceLastCheck - targetBandwidth;
- int excessThreads = Math.round(excessBdw/averageBdwPerThread);
- LOG.info("Exceeding target bandwidth ("+bpsSinceLastCheck/1000 +" vs "+(targetBandwidth/1000)+" kbps). \t=> excessThreads = "+excessThreads);
+ int excessThreads = Math.round(excessBdw / averageBdwPerThread);
+ LOG.info("Exceeding target bandwidth (" + bpsSinceLastCheck / 1000
+ + " vs " + (targetBandwidth / 1000)
+ + " kbps). \t=> excessThreads = " + excessThreads);
// keep at least one
- if (excessThreads >= fetcherThreads.size()) excessThreads = 0;
+ if (excessThreads >= fetcherThreads.size())
+ excessThreads = 0;
// de-activates threads
for (int i = 0; i < excessThreads; i++) {
FetcherThread thread = fetcherThreads.removeLast();
@@ -1336,18 +1457,20 @@ public class Fetcher extends Configured implements Tool,
// check timelimit
if (!feeder.isAlive()) {
int hitByTimeLimit = fetchQueues.checkTimelimit();
- if (hitByTimeLimit != 0) reporter.incrCounter("FetcherStatus",
- "hitByTimeLimit", hitByTimeLimit);
+ if (hitByTimeLimit != 0)
+ reporter.incrCounter("FetcherStatus", "hitByTimeLimit",
+ hitByTimeLimit);
}
// some requests seem to hang, despite all intentions
if ((System.currentTimeMillis() - lastRequestStart.get()) > timeout) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Aborting with "+activeThreads+" hung threads.");
+ LOG.warn("Aborting with " + activeThreads + " hung threads.");
for (int i = 0; i < fetcherThreads.size(); i++) {
FetcherThread thread = fetcherThreads.get(i);
if (thread.isAlive()) {
- LOG.warn("Thread #" + i + " hung while processing " + thread.reprUrl);
+ LOG.warn("Thread #" + i + " hung while processing "
+ + thread.reprUrl);
if (LOG.isDebugEnabled()) {
StackTraceElement[] stack = thread.getStackTrace();
StringBuilder sb = new StringBuilder();
@@ -1368,8 +1491,7 @@ public class Fetcher extends Configured implements Tool,
}
- public void fetch(Path segment, int threads)
- throws IOException {
+ public void fetch(Path segment, int threads) throws IOException {
checkConfiguration();
@@ -1390,24 +1512,31 @@ public class Fetcher extends Configured implements Tool,
getConf().setLong("fetcher.timelimit", timelimit);
}
- // Set the time limit after which the throughput threshold feature is enabled
- timelimit = getConf().getLong("fetcher.throughput.threshold.check.after", 10);
+ // Set the time limit after which the throughput threshold feature is
+ // enabled
+ timelimit = getConf().getLong("fetcher.throughput.threshold.check.after",
+ 10);
timelimit = System.currentTimeMillis() + (timelimit * 60 * 1000);
getConf().setLong("fetcher.throughput.threshold.check.after", timelimit);
int maxOutlinkDepth = getConf().getInt("fetcher.follow.outlinks.depth", -1);
if (maxOutlinkDepth > 0) {
- LOG.info("Fetcher: following outlinks up to depth: " + Integer.toString(maxOutlinkDepth));
+ LOG.info("Fetcher: following outlinks up to depth: "
+ + Integer.toString(maxOutlinkDepth));
- int maxOutlinkDepthNumLinks = getConf().getInt("fetcher.follow.outlinks.num.links", 4);
- int outlinksDepthDivisor = getConf().getInt("fetcher.follow.outlinks.depth.divisor", 2);
+ int maxOutlinkDepthNumLinks = getConf().getInt(
+ "fetcher.follow.outlinks.num.links", 4);
+ int outlinksDepthDivisor = getConf().getInt(
+ "fetcher.follow.outlinks.depth.divisor", 2);
int totalOutlinksToFollow = 0;
for (int i = 0; i < maxOutlinkDepth; i++) {
- totalOutlinksToFollow += (int)Math.floor(outlinksDepthDivisor / (i + 1) * maxOutlinkDepthNumLinks);
+ totalOutlinksToFollow += (int) Math.floor(outlinksDepthDivisor
+ / (i + 1) * maxOutlinkDepthNumLinks);
}
- LOG.info("Fetcher: maximum outlinks to follow: " + Integer.toString(totalOutlinksToFollow));
+ LOG.info("Fetcher: maximum outlinks to follow: "
+ + Integer.toString(totalOutlinksToFollow));
}
JobConf job = new NutchJob(getConf());
@@ -1419,7 +1548,8 @@ public class Fetcher extends Configured implements Tool,
// for politeness, don't permit parallel execution of a single task
job.setSpeculativeExecution(false);
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.GENERATE_DIR_NAME));
job.setInputFormat(InputFormat.class);
job.setMapRunnerClass(Fetcher.class);
@@ -1432,10 +1562,10 @@ public class Fetcher extends Configured implements Tool,
JobClient.runJob(job);
long end = System.currentTimeMillis();
- LOG.info("Fetcher: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("Fetcher: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
-
/** Run the fetcher. */
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new Fetcher(), args);
@@ -1456,9 +1586,9 @@ public class Fetcher extends Configured implements Tool,
int threads = getConf().getInt("fetcher.threads.fetch", 10);
boolean parsing = false;
- for (int i = 1; i < args.length; i++) { // parse command line
- if (args[i].equals("-threads")) { // found -threads option
- threads = Integer.parseInt(args[++i]);
+ for (int i = 1; i < args.length; i++) { // parse command line
+ if (args[i].equals("-threads")) { // found -threads option
+ threads = Integer.parseInt(args[++i]);
}
}
diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
index 49528b286..44d36e460 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
@@ -48,74 +48,68 @@ public class FetcherOutputFormat implements OutputFormat<Text, NutchWritable> {
public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException {
Path out = FileOutputFormat.getOutputPath(job);
if ((out == null) && (job.getNumReduceTasks() != 0)) {
- throw new InvalidJobConfException(
- "Output directory not set in JobConf.");
+ throw new InvalidJobConfException("Output directory not set in JobConf.");
}
if (fs == null) {
- fs = out.getFileSystem(job);
+ fs = out.getFileSystem(job);
}
if (fs.exists(new Path(out, CrawlDatum.FETCH_DIR_NAME)))
- throw new IOException("Segment already fetched!");
+ throw new IOException("Segment already fetched!");
}
public RecordWriter<Text, NutchWritable> getRecordWriter(final FileSystem fs,
- final JobConf job,
- final String name,
- final Progressable progress) throws IOException {
+ final JobConf job, final String name, final Progressable progress)
+ throws IOException {
Path out = FileOutputFormat.getOutputPath(job);
- final Path fetch =
- new Path(new Path(out, CrawlDatum.FETCH_DIR_NAME), name);
- final Path content =
- new Path(new Path(out, Content.DIR_NAME), name);
-
- final CompressionType compType = SequenceFileOutputFormat.getOutputCompressionType(job);
-
- final MapFile.Writer fetchOut =
- new MapFile.Writer(job, fs, fetch.toString(), Text.class, CrawlDatum.class,
- compType, progress);
-
+ final Path fetch = new Path(new Path(out, CrawlDatum.FETCH_DIR_NAME), name);
+ final Path content = new Path(new Path(out, Content.DIR_NAME), name);
+
+ final CompressionType compType = SequenceFileOutputFormat
+ .getOutputCompressionType(job);
+
+ final MapFile.Writer fetchOut = new MapFile.Writer(job, fs,
+ fetch.toString(), Text.class, CrawlDatum.class, compType, progress);
+
return new RecordWriter<Text, NutchWritable>() {
- private MapFile.Writer contentOut;
- private RecordWriter<Text, Parse> parseOut;
-
- {
- if (Fetcher.isStoringContent(job)) {
- contentOut = new MapFile.Writer(job, fs, content.toString(),
- Text.class, Content.class,
- compType, progress);
- }
-
- if (Fetcher.isParsing(job)) {
- parseOut = new ParseOutputFormat().getRecordWriter(fs, job, name, progress);
- }
+ private MapFile.Writer contentOut;
+ private RecordWriter<Text, Parse> parseOut;
+
+ {
+ if (Fetcher.isStoringContent(job)) {
+ contentOut = new MapFile.Writer(job, fs, content.toString(),
+ Text.class, Content.class, compType, progress);
}
- public void write(Text key, NutchWritable value)
- throws IOException {
-
- Writable w = value.get();
-
- if (w instanceof CrawlDatum)
- fetchOut.append(key, w);
- else if (w instanceof Content && contentOut != null)
- contentOut.append(key, w);
- else if (w instanceof Parse && parseOut != null)
- parseOut.write(key, (Parse)w);
+ if (Fetcher.isParsing(job)) {
+ parseOut = new ParseOutputFormat().getRecordWriter(fs, job, name,
+ progress);
}
+ }
+
+ public void write(Text key, NutchWritable value) throws IOException {
- public void close(Reporter reporter) throws IOException {
- fetchOut.close();
- if (contentOut != null) {
- contentOut.close();
- }
- if (parseOut != null) {
- parseOut.close(reporter);
- }
+ Writable w = value.get();
+
+ if (w instanceof CrawlDatum)
+ fetchOut.append(key, w);
+ else if (w instanceof Content && contentOut != null)
+ contentOut.append(key, w);
+ else if (w instanceof Parse && parseOut != null)
+ parseOut.write(key, (Parse) w);
+ }
+
+ public void close(Reporter reporter) throws IOException {
+ fetchOut.close();
+ if (contentOut != null) {
+ contentOut.close();
+ }
+ if (parseOut != null) {
+ parseOut.close(reporter);
}
+ }
- };
+ };
- }
+ }
}
-
diff --git a/src/java/org/apache/nutch/fetcher/OldFetcher.java b/src/java/org/apache/nutch/fetcher/OldFetcher.java
index 778c48798..ef2fc8409 100644
--- a/src/java/org/apache/nutch/fetcher/OldFetcher.java
+++ b/src/java/org/apache/nutch/fetcher/OldFetcher.java
@@ -43,28 +43,28 @@ import org.apache.nutch.parse.*;
import org.apache.nutch.scoring.ScoringFilters;
import org.apache.nutch.util.*;
-
/** The fetcher. Most of the work is done by plugins. */
-public class OldFetcher extends Configured implements Tool, MapRunnable<WritableComparable<?>, Writable, Text, NutchWritable> {
+public class OldFetcher extends Configured implements Tool,
+ MapRunnable<WritableComparable<?>, Writable, Text, NutchWritable> {
public static final Logger LOG = LoggerFactory.getLogger(OldFetcher.class);
-
+
public static final int PERM_REFRESH_TIME = 5;
public static final String CONTENT_REDIR = "content";
public static final String PROTOCOL_REDIR = "protocol";
- public static class InputFormat extends SequenceFileInputFormat<WritableComparable<?>, Writable> {
+ public static class InputFormat extends
+ SequenceFileInputFormat<WritableComparable<?>, Writable> {
/** Don't split inputs, to keep things polite. */
- public InputSplit[] getSplits(JobConf job, int nSplits)
- throws IOException {
+ public InputSplit[] getSplits(JobConf job, int nSplits) throws IOException {
FileStatus[] files = listStatus(job);
InputSplit[] splits = new InputSplit[files.length];
for (int i = 0; i < files.length; i++) {
FileStatus cur = files[i];
- splits[i] = new FileSplit(cur.getPath(), 0,
- cur.getLen(), (String[])null);
+ splits[i] = new FileSplit(cur.getPath(), 0, cur.getLen(),
+ (String[]) null);
}
return splits;
}
@@ -81,9 +81,9 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
private long start = System.currentTimeMillis(); // start time of fetcher run
private long lastRequestStart = start;
- private long bytes; // total bytes fetched
- private int pages; // total pages fetched
- private int errors; // total pages errored
+ private long bytes; // total bytes fetched
+ private int pages; // total pages fetched
+ private int errors; // total pages errored
private boolean storingContent;
private boolean parsing;
@@ -100,8 +100,8 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
private String reprUrl;
public FetcherThread(Configuration conf) {
- this.setDaemon(true); // don't hang JVM on exit
- this.setName("FetcherThread"); // use an informative name
+ this.setDaemon(true); // don't hang JVM on exit
+ this.setName("FetcherThread"); // use an informative name
this.conf = conf;
this.urlFilters = new URLFilters(conf);
this.scfilters = new ScoringFilters(conf);
@@ -112,26 +112,28 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
@SuppressWarnings("fallthrough")
public void run() {
- synchronized (OldFetcher.this) {activeThreads++;} // count threads
-
+ synchronized (OldFetcher.this) {
+ activeThreads++;
+ } // count threads
+
try {
Text key = new Text();
CrawlDatum datum = new CrawlDatum();
-
+
while (true) {
// TODO : NUTCH-258 ...
// If something bad happened, then exit
// if (conf.getBoolean("fetcher.exit", false)) {
- // break;
+ // break;
// ]
-
- try { // get next entry from input
+
+ try { // get next entry from input
if (!input.next(key, datum)) {
- break; // at eof, exit
+ break; // at eof, exit
}
} catch (IOException e) {
if (LOG.isErrorEnabled()) {
- LOG.error("fetcher caught:"+e.toString());
+ LOG.error("fetcher caught:" + e.toString());
}
break;
}
@@ -143,8 +145,8 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
// url may be changed through redirects.
Text url = new Text(key);
- Text reprUrlWritable =
- (Text) datum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
+ Text reprUrlWritable = (Text) datum.getMetaData().get(
+ Nutch.WRITABLE_REPR_URL_KEY);
if (reprUrlWritable == null) {
reprUrl = key.toString();
} else {
@@ -152,7 +154,9 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
}
try {
- if (LOG.isInfoEnabled()) { LOG.info("fetching " + url); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("fetching " + url);
+ }
// fetch the page
redirectCount = 0;
@@ -161,7 +165,8 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
LOG.debug("redirectCount=" + redirectCount);
}
redirecting = false;
- Protocol protocol = this.protocolFactory.getProtocol(url.toString());
+ Protocol protocol = this.protocolFactory.getProtocol(url
+ .toString());
ProtocolOutput output = protocol.getProtocolOutput(url, datum);
ProtocolStatus status = output.getStatus();
Content content = output.getContent();
@@ -173,22 +178,22 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
new Text(reprUrl));
}
- switch(status.getCode()) {
+ switch (status.getCode()) {
- case ProtocolStatus.SUCCESS: // got a page
- pstatus = output(url, datum, content, status, CrawlDatum.STATUS_FETCH_SUCCESS);
+ case ProtocolStatus.SUCCESS: // got a page
+ pstatus = output(url, datum, content, status,
+ CrawlDatum.STATUS_FETCH_SUCCESS);
updateStatus(content.getContent().length);
- if (pstatus != null && pstatus.isSuccess() &&
- pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
+ if (pstatus != null && pstatus.isSuccess()
+ && pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
String newUrl = pstatus.getMessage();
int refreshTime = Integer.valueOf(pstatus.getArgs()[1]);
url = handleRedirect(url, datum, urlString, newUrl,
- refreshTime < PERM_REFRESH_TIME,
- CONTENT_REDIR);
+ refreshTime < PERM_REFRESH_TIME, CONTENT_REDIR);
}
break;
- case ProtocolStatus.MOVED: // redirect
+ case ProtocolStatus.MOVED: // redirect
case ProtocolStatus.TEMP_MOVED:
int code;
boolean temp;
@@ -201,22 +206,22 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
}
output(url, datum, content, status, code);
String newUrl = status.getMessage();
- url = handleRedirect(url, datum, urlString, newUrl,
- temp, PROTOCOL_REDIR);
+ url = handleRedirect(url, datum, urlString, newUrl, temp,
+ PROTOCOL_REDIR);
break;
// failures - increase the retry counter
case ProtocolStatus.EXCEPTION:
logError(url, status.getMessage());
- /* FALLTHROUGH */
- case ProtocolStatus.RETRY: // retry
+ /* FALLTHROUGH */
+ case ProtocolStatus.RETRY: // retry
case ProtocolStatus.WOULDBLOCK:
case ProtocolStatus.BLOCKED:
output(url, datum, null, status, CrawlDatum.STATUS_FETCH_RETRY);
break;
-
+
// permanent failures
- case ProtocolStatus.GONE: // gone
+ case ProtocolStatus.GONE: // gone
case ProtocolStatus.NOTFOUND:
case ProtocolStatus.ACCESS_DENIED:
case ProtocolStatus.ROBOTS_DENIED:
@@ -224,9 +229,10 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
break;
case ProtocolStatus.NOTMODIFIED:
- output(url, datum, null, status, CrawlDatum.STATUS_FETCH_NOTMODIFIED);
+ output(url, datum, null, status,
+ CrawlDatum.STATUS_FETCH_NOTMODIFIED);
break;
-
+
default:
if (LOG.isWarnEnabled()) {
LOG.warn("Unknown ProtocolStatus: " + status.getCode());
@@ -243,27 +249,27 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
} while (redirecting && (redirectCount < maxRedirect));
-
- } catch (Throwable t) { // unexpected exception
+ } catch (Throwable t) { // unexpected exception
logError(url, t.toString());
output(url, datum, null, null, CrawlDatum.STATUS_FETCH_RETRY);
-
+
}
}
} catch (Throwable e) {
if (LOG.isErrorEnabled()) {
- LOG.error("fetcher caught:"+e.toString());
+ LOG.error("fetcher caught:" + e.toString());
}
} finally {
- synchronized (OldFetcher.this) {activeThreads--;} // count threads
+ synchronized (OldFetcher.this) {
+ activeThreads--;
+ } // count threads
}
}
- private Text handleRedirect(Text url, CrawlDatum datum,
- String urlString, String newUrl,
- boolean temp, String redirType)
- throws MalformedURLException, URLFilterException {
+ private Text handleRedirect(Text url, CrawlDatum datum, String urlString,
+ String newUrl, boolean temp, String redirType)
+ throws MalformedURLException, URLFilterException {
newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);
newUrl = urlFilters.filter(newUrl);
if (newUrl != null && !newUrl.equals(urlString)) {
@@ -273,8 +279,8 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
redirecting = true;
redirectCount++;
if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching now)");
+ LOG.debug(" - " + redirType + " redirect to " + url
+ + " (fetching now)");
}
return url;
} else {
@@ -285,15 +291,15 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
}
output(url, newDatum, null, null, CrawlDatum.STATUS_LINKED);
if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " +
- url + " (fetching later)");
+ LOG.debug(" - " + redirType + " redirect to " + url
+ + " (fetching later)");
}
return null;
}
} else {
if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect skipped: " +
- (newUrl != null ? "to same url" : "filtered"));
+ LOG.debug(" - " + redirType + " redirect skipped: "
+ + (newUrl != null ? "to same url" : "filtered"));
}
return null;
}
@@ -303,17 +309,18 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
if (LOG.isInfoEnabled()) {
LOG.info("fetch of " + url + " failed with: " + message);
}
- synchronized (OldFetcher.this) { // record failure
+ synchronized (OldFetcher.this) { // record failure
errors++;
}
}
- private ParseStatus output(Text key, CrawlDatum datum,
- Content content, ProtocolStatus pstatus, int status) {
+ private ParseStatus output(Text key, CrawlDatum datum, Content content,
+ ProtocolStatus pstatus, int status) {
datum.setStatus(status);
datum.setFetchTime(System.currentTimeMillis());
- if (pstatus != null) datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
+ if (pstatus != null)
+ datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
ParseResult parseResult = null;
if (content != null) {
@@ -328,27 +335,31 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
}
}
- /* Note: Fetcher will only follow meta-redirects coming from the
- * original URL. */
+ /*
+ * Note: Fetcher will only follow meta-redirects coming from the
+ * original URL.
+ */
if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {
try {
parseResult = this.parseUtil.parse(content);
} catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": " + StringUtils.stringifyException(e));
+ LOG.warn("Error parsing: " + key + ": "
+ + StringUtils.stringifyException(e));
}
if (parseResult == null) {
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content,
- new ParseStatus().getEmptyParse(conf));
+ byte[] signature = SignatureFactory.getSignature(getConf())
+ .calculate(content, new ParseStatus().getEmptyParse(conf));
datum.setSignature(signature);
}
}
-
- /* Store status code in content So we can read this value during
- * parsing (as a separate job) and decide to parse or not.
+
+ /*
+ * Store status code in content So we can read this value during parsing
+ * (as a separate job) and decide to parse or not.
*/
- content.getMetadata().add(Nutch.FETCH_STATUS_KEY, Integer.toString(status));
+ content.getMetadata().add(Nutch.FETCH_STATUS_KEY,
+ Integer.toString(status));
}
try {
@@ -360,7 +371,7 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
Text url = entry.getKey();
Parse parse = entry.getValue();
ParseStatus parseStatus = parse.getData().getStatus();
-
+
if (!parseStatus.isSuccess()) {
LOG.warn("Error parsing: " + key + ": " + parseStatus);
parse = parseStatus.getEmptyParse(getConf());
@@ -368,16 +379,16 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
// Calculate page signature. For non-parsing fetchers this will
// be done in ParseSegment
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content, parse);
+ byte[] signature = SignatureFactory.getSignature(getConf())
+ .calculate(content, parse);
// Ensure segment name and score are in parseData metadata
- parse.getData().getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
- segmentName);
- parse.getData().getContentMeta().set(Nutch.SIGNATURE_KEY,
- StringUtil.toHexString(signature));
+ parse.getData().getContentMeta()
+ .set(Nutch.SEGMENT_NAME_KEY, segmentName);
+ parse.getData().getContentMeta()
+ .set(Nutch.SIGNATURE_KEY, StringUtil.toHexString(signature));
// Pass fetch time to content meta
- parse.getData().getContentMeta().set(Nutch.FETCH_TIME_KEY,
- Long.toString(datum.getFetchTime()));
+ parse.getData().getContentMeta()
+ .set(Nutch.FETCH_TIME_KEY, Long.toString(datum.getFetchTime()));
if (url.equals(key))
datum.setSignature(signature);
try {
@@ -387,14 +398,13 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
}
}
- output.collect(url, new NutchWritable(
- new ParseImpl(new ParseText(parse.getText()),
- parse.getData(), parse.isCanonical())));
+ output.collect(url, new NutchWritable(new ParseImpl(new ParseText(
+ parse.getText()), parse.getData(), parse.isCanonical())));
}
}
} catch (IOException e) {
if (LOG.isErrorEnabled()) {
- LOG.error("fetcher caught:"+e.toString());
+ LOG.error("fetcher caught:" + e.toString());
}
}
@@ -404,10 +414,10 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
if (p != null) {
return p.getData().getStatus();
}
- }
+ }
return null;
}
-
+
}
private synchronized void updateStatus(int bytesInPage) throws IOException {
@@ -418,23 +428,22 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
private void reportStatus() throws IOException {
String status;
synchronized (this) {
- long elapsed = (System.currentTimeMillis() - start)/1000;
- status =
- pages+" pages, "+errors+" errors, "
- + Math.round(((float)pages*10)/elapsed)/10.0+" pages/s, "
- + Math.round(((((float)bytes)*8)/1024)/elapsed)+" kb/s, ";
+ long elapsed = (System.currentTimeMillis() - start) / 1000;
+ status = pages + " pages, " + errors + " errors, "
+ + Math.round(((float) pages * 10) / elapsed) / 10.0 + " pages/s, "
+ + Math.round(((((float) bytes) * 8) / 1024) / elapsed) + " kb/s, ";
}
reporter.setStatus(status);
}
public OldFetcher() {
-
+
}
-
+
public OldFetcher(Configuration conf) {
setConf(conf);
}
-
+
public void configure(JobConf job) {
setConf(job);
@@ -442,12 +451,13 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
this.storingContent = isStoringContent(job);
this.parsing = isParsing(job);
-// if (job.getBoolean("fetcher.verbose", false)) {
-// LOG.setLevel(Level.FINE);
-// }
+ // if (job.getBoolean("fetcher.verbose", false)) {
+ // LOG.setLevel(Level.FINE);
+ // }
}
- public void close() {}
+ public void close() {
+ }
public static boolean isParsing(Configuration conf) {
return conf.getBoolean("fetcher.parse", true);
@@ -457,29 +467,33 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
return conf.getBoolean("fetcher.store.content", true);
}
- public void run(RecordReader<WritableComparable<?>, Writable> input, OutputCollector<Text, NutchWritable> output,
- Reporter reporter) throws IOException {
+ public void run(RecordReader<WritableComparable<?>, Writable> input,
+ OutputCollector<Text, NutchWritable> output, Reporter reporter)
+ throws IOException {
this.input = input;
this.output = output;
this.reporter = reporter;
this.maxRedirect = getConf().getInt("http.redirect.max", 3);
-
+
int threadCount = getConf().getInt("fetcher.threads.fetch", 10);
- if (LOG.isInfoEnabled()) { LOG.info("OldFetcher: threads: " + threadCount); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("OldFetcher: threads: " + threadCount);
+ }
- for (int i = 0; i < threadCount; i++) { // spawn threads
+ for (int i = 0; i < threadCount; i++) { // spawn threads
new FetcherThread(getConf()).start();
}
// select a timeout that avoids a task timeout
- long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/2;
+ long timeout = getConf().getInt("mapred.task.timeout", 10 * 60 * 1000) / 2;
- do { // wait for threads to exit
+ do { // wait for threads to exit
try {
Thread.sleep(1000);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
reportStatus();
@@ -487,18 +501,17 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
synchronized (this) {
if ((System.currentTimeMillis() - lastRequestStart) > timeout) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Aborting with "+activeThreads+" hung threads.");
+ LOG.warn("Aborting with " + activeThreads + " hung threads.");
}
return;
}
}
} while (activeThreads > 0);
-
+
}
- public void fetch(Path segment, int threads)
- throws IOException {
+ public void fetch(Path segment, int threads) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -516,7 +529,8 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
// for politeness, don't permit parallel execution of a single task
job.setSpeculativeExecution(false);
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.GENERATE_DIR_NAME));
job.setInputFormat(InputFormat.class);
job.setMapRunnerClass(OldFetcher.class);
@@ -528,16 +542,17 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
JobClient.runJob(job);
long end = System.currentTimeMillis();
- LOG.info("OldFetcher: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("OldFetcher: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
-
/** Run the fetcher. */
public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new OldFetcher(), args);
+ int res = ToolRunner.run(NutchConfiguration.create(), new OldFetcher(),
+ args);
System.exit(res);
}
-
+
public int run(String[] args) throws Exception {
String usage = "Usage: OldFetcher <segment> [-threads n] [-noParsing]";
@@ -546,15 +561,16 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
System.err.println(usage);
return -1;
}
-
+
Path segment = new Path(args[0]);
int threads = getConf().getInt("fetcher.threads.fetch", 10);
boolean parsing = true;
- for (int i = 1; i < args.length; i++) { // parse command line
- if (args[i].equals("-threads")) { // found -threads option
- threads = Integer.parseInt(args[++i]);
- } else if (args[i].equals("-noParsing")) parsing = false;
+ for (int i = 1; i < args.length; i++) { // parse command line
+ if (args[i].equals("-threads")) { // found -threads option
+ threads = Integer.parseInt(args[++i]);
+ } else if (args[i].equals("-noParsing"))
+ parsing = false;
}
getConf().setInt("fetcher.threads.fetch", threads);
@@ -562,7 +578,7 @@ public class OldFetcher extends Configured implements Tool, MapRunnable<Writable
getConf().setBoolean("fetcher.parse", parsing);
}
try {
- fetch(segment, threads); // run the Fetcher
+ fetch(segment, threads); // run the Fetcher
return 0;
} catch (Exception e) {
LOG.error("OldFetcher: " + StringUtils.stringifyException(e));
diff --git a/src/java/org/apache/nutch/indexer/CleaningJob.java b/src/java/org/apache/nutch/indexer/CleaningJob.java
index f7bea135c..c16003a33 100644
--- a/src/java/org/apache/nutch/indexer/CleaningJob.java
+++ b/src/java/org/apache/nutch/indexer/CleaningJob.java
@@ -45,169 +45,166 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * The class scans CrawlDB looking for entries with status DB_GONE (404) or
- * DB_DUPLICATE and
- * sends delete requests to indexers for those documents.
+ * The class scans CrawlDB looking for entries with status DB_GONE (404) or
+ * DB_DUPLICATE and sends delete requests to indexers for those documents.
*/
public class CleaningJob implements Tool {
- public static final Logger LOG = LoggerFactory.getLogger(CleaningJob.class);
- private Configuration conf;
+ public static final Logger LOG = LoggerFactory.getLogger(CleaningJob.class);
+ private Configuration conf;
+
+ @Override
+ public Configuration getConf() {
+ return conf;
+ }
+
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
+
+ public static class DBFilter implements
+ Mapper<Text, CrawlDatum, ByteWritable, Text> {
+ private ByteWritable OUT = new ByteWritable(CrawlDatum.STATUS_DB_GONE);
@Override
- public Configuration getConf() {
- return conf;
+ public void configure(JobConf arg0) {
}
@Override
- public void setConf(Configuration conf) {
- this.conf = conf;
+ public void close() throws IOException {
}
- public static class DBFilter implements
- Mapper<Text, CrawlDatum, ByteWritable, Text> {
- private ByteWritable OUT = new ByteWritable(CrawlDatum.STATUS_DB_GONE);
+ @Override
+ public void map(Text key, CrawlDatum value,
+ OutputCollector<ByteWritable, Text> output, Reporter reporter)
+ throws IOException {
+
+ if (value.getStatus() == CrawlDatum.STATUS_DB_GONE
+ || value.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
+ output.collect(OUT, key);
+ }
+ }
+ }
- @Override
- public void configure(JobConf arg0) {
- }
+ public static class DeleterReducer implements
+ Reducer<ByteWritable, Text, Text, ByteWritable> {
+ private static final int NUM_MAX_DELETE_REQUEST = 1000;
+ private int numDeletes = 0;
+ private int totalDeleted = 0;
- @Override
- public void close() throws IOException {
- }
+ private boolean noCommit = false;
- @Override
- public void map(Text key, CrawlDatum value,
- OutputCollector<ByteWritable, Text> output, Reporter reporter)
- throws IOException {
+ IndexWriters writers = null;
- if (value.getStatus() == CrawlDatum.STATUS_DB_GONE || value.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
- output.collect(OUT, key);
- }
- }
+ @Override
+ public void configure(JobConf job) {
+ writers = new IndexWriters(job);
+ try {
+ writers.open(job, "Deletion");
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ noCommit = job.getBoolean("noCommit", false);
}
- public static class DeleterReducer implements
- Reducer<ByteWritable, Text, Text, ByteWritable> {
- private static final int NUM_MAX_DELETE_REQUEST = 1000;
- private int numDeletes = 0;
- private int totalDeleted = 0;
-
- private boolean noCommit = false;
-
- IndexWriters writers = null;
-
- @Override
- public void configure(JobConf job) {
- writers = new IndexWriters(job);
- try {
- writers.open(job, "Deletion");
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- noCommit = job.getBoolean("noCommit", false);
- }
-
- @Override
- public void close() throws IOException {
- // BUFFERING OF CALLS TO INDEXER SHOULD BE HANDLED AT INDEXER LEVEL
- // if (numDeletes > 0) {
- // LOG.info("CleaningJob: deleting " + numDeletes + " documents");
- // // TODO updateRequest.process(solr);
- // totalDeleted += numDeletes;
- // }
-
- writers.close();
-
- if (totalDeleted > 0 && !noCommit) {
- writers.commit();
- }
-
- LOG.info("CleaningJob: deleted a total of " + totalDeleted
- + " documents");
- }
-
- @Override
- public void reduce(ByteWritable key, Iterator<Text> values,
- OutputCollector<Text, ByteWritable> output, Reporter reporter)
- throws IOException {
- while (values.hasNext()) {
- Text document = values.next();
- writers.delete(document.toString());
- totalDeleted++;
- reporter.incrCounter("CleaningJobStatus", "Deleted documents",
- 1);
- // if (numDeletes >= NUM_MAX_DELETE_REQUEST) {
- // LOG.info("CleaningJob: deleting " + numDeletes
- // + " documents");
- // // TODO updateRequest.process(solr);
- // // TODO updateRequest = new UpdateRequest();
- // writers.delete(key.toString());
- // totalDeleted += numDeletes;
- // numDeletes = 0;
- // }
- }
- }
+ @Override
+ public void close() throws IOException {
+ // BUFFERING OF CALLS TO INDEXER SHOULD BE HANDLED AT INDEXER LEVEL
+ // if (numDeletes > 0) {
+ // LOG.info("CleaningJob: deleting " + numDeletes + " documents");
+ // // TODO updateRequest.process(solr);
+ // totalDeleted += numDeletes;
+ // }
+
+ writers.close();
+
+ if (totalDeleted > 0 && !noCommit) {
+ writers.commit();
+ }
+
+ LOG.info("CleaningJob: deleted a total of " + totalDeleted + " documents");
}
- public void delete(String crawldb, boolean noCommit) throws IOException {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- long start = System.currentTimeMillis();
- LOG.info("CleaningJob: starting at " + sdf.format(start));
-
- JobConf job = new NutchJob(getConf());
-
- FileInputFormat.addInputPath(job, new Path(crawldb,
- CrawlDb.CURRENT_NAME));
- job.setBoolean("noCommit", noCommit);
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setOutputFormat(NullOutputFormat.class);
- job.setMapOutputKeyClass(ByteWritable.class);
- job.setMapOutputValueClass(Text.class);
- job.setMapperClass(DBFilter.class);
- job.setReducerClass(DeleterReducer.class);
-
- job.setJobName("CleaningJob");
-
- // need to expicitely allow deletions
- job.setBoolean(IndexerMapReduce.INDEXER_DELETE, true);
-
- JobClient.runJob(job);
-
- long end = System.currentTimeMillis();
- LOG.info("CleaningJob: finished at " + sdf.format(end) + ", elapsed: "
- + TimingUtil.elapsedTime(start, end));
+ @Override
+ public void reduce(ByteWritable key, Iterator<Text> values,
+ OutputCollector<Text, ByteWritable> output, Reporter reporter)
+ throws IOException {
+ while (values.hasNext()) {
+ Text document = values.next();
+ writers.delete(document.toString());
+ totalDeleted++;
+ reporter.incrCounter("CleaningJobStatus", "Deleted documents", 1);
+ // if (numDeletes >= NUM_MAX_DELETE_REQUEST) {
+ // LOG.info("CleaningJob: deleting " + numDeletes
+ // + " documents");
+ // // TODO updateRequest.process(solr);
+ // // TODO updateRequest = new UpdateRequest();
+ // writers.delete(key.toString());
+ // totalDeleted += numDeletes;
+ // numDeletes = 0;
+ // }
+ }
+ }
+ }
+
+ public void delete(String crawldb, boolean noCommit) throws IOException {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ long start = System.currentTimeMillis();
+ LOG.info("CleaningJob: starting at " + sdf.format(start));
+
+ JobConf job = new NutchJob(getConf());
+
+ FileInputFormat.addInputPath(job, new Path(crawldb, CrawlDb.CURRENT_NAME));
+ job.setBoolean("noCommit", noCommit);
+ job.setInputFormat(SequenceFileInputFormat.class);
+ job.setOutputFormat(NullOutputFormat.class);
+ job.setMapOutputKeyClass(ByteWritable.class);
+ job.setMapOutputValueClass(Text.class);
+ job.setMapperClass(DBFilter.class);
+ job.setReducerClass(DeleterReducer.class);
+
+ job.setJobName("CleaningJob");
+
+ // need to expicitely allow deletions
+ job.setBoolean(IndexerMapReduce.INDEXER_DELETE, true);
+
+ JobClient.runJob(job);
+
+ long end = System.currentTimeMillis();
+ LOG.info("CleaningJob: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
+ }
+
+ public int run(String[] args) throws IOException {
+ if (args.length < 1) {
+ String usage = "Usage: CleaningJob <crawldb> [-noCommit]";
+ LOG.error("Missing crawldb. " + usage);
+ System.err.println(usage);
+ IndexWriters writers = new IndexWriters(getConf());
+ System.err.println(writers.describe());
+ return 1;
}
- public int run(String[] args) throws IOException {
- if (args.length < 1) {
- String usage = "Usage: CleaningJob <crawldb> [-noCommit]";
- LOG.error("Missing crawldb. "+usage);
- System.err.println(usage);
- IndexWriters writers = new IndexWriters(getConf());
- System.err.println(writers.describe());
- return 1;
- }
-
- boolean noCommit = false;
- if (args.length == 2 && args[1].equals("-noCommit")) {
- noCommit = true;
- }
-
- try {
- delete(args[0], noCommit);
- } catch (final Exception e) {
- LOG.error("CleaningJob: " + StringUtils.stringifyException(e));
- System.err.println("ERROR CleaningJob: "
- + StringUtils.stringifyException(e));
- return -1;
- }
- return 0;
+ boolean noCommit = false;
+ if (args.length == 2 && args[1].equals("-noCommit")) {
+ noCommit = true;
}
- public static void main(String[] args) throws Exception {
- int result = ToolRunner.run(NutchConfiguration.create(),
- new CleaningJob(), args);
- System.exit(result);
+ try {
+ delete(args[0], noCommit);
+ } catch (final Exception e) {
+ LOG.error("CleaningJob: " + StringUtils.stringifyException(e));
+ System.err.println("ERROR CleaningJob: "
+ + StringUtils.stringifyException(e));
+ return -1;
}
+ return 0;
+ }
+
+ public static void main(String[] args) throws Exception {
+ int result = ToolRunner.run(NutchConfiguration.create(), new CleaningJob(),
+ args);
+ System.exit(result);
+ }
}
diff --git a/src/java/org/apache/nutch/indexer/IndexWriter.java b/src/java/org/apache/nutch/indexer/IndexWriter.java
index b43d17582..fbbf2e8ca 100644
--- a/src/java/org/apache/nutch/indexer/IndexWriter.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriter.java
@@ -24,22 +24,24 @@ import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.plugin.Pluggable;
public interface IndexWriter extends Pluggable, Configurable {
- /** The name of the extension point. */
- final static String X_POINT_ID = IndexWriter.class.getName();
-
- public void open(JobConf job, String name) throws IOException;
+ /** The name of the extension point. */
+ final static String X_POINT_ID = IndexWriter.class.getName();
- public void write(NutchDocument doc) throws IOException;
+ public void open(JobConf job, String name) throws IOException;
- public void delete(String key) throws IOException;
-
- public void update(NutchDocument doc) throws IOException;
+ public void write(NutchDocument doc) throws IOException;
- public void commit() throws IOException;
-
- public void close() throws IOException;
+ public void delete(String key) throws IOException;
- /** Returns a String describing the IndexWriter instance and the specific parameters it can take */
- public String describe();
-}
+ public void update(NutchDocument doc) throws IOException;
+
+ public void commit() throws IOException;
+ public void close() throws IOException;
+
+ /**
+ * Returns a String describing the IndexWriter instance and the specific
+ * parameters it can take
+ */
+ public String describe();
+}
diff --git a/src/java/org/apache/nutch/indexer/IndexWriters.java b/src/java/org/apache/nutch/indexer/IndexWriters.java
index e05a0eadb..681812bcc 100644
--- a/src/java/org/apache/nutch/indexer/IndexWriters.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriters.java
@@ -33,116 +33,113 @@ import org.slf4j.LoggerFactory;
/** Creates and caches {@link IndexWriter} implementing plugins. */
public class IndexWriters {
- public final static Logger LOG = LoggerFactory
- .getLogger(IndexWriters.class);
+ public final static Logger LOG = LoggerFactory.getLogger(IndexWriters.class);
- private IndexWriter[] indexWriters;
+ private IndexWriter[] indexWriters;
- public IndexWriters(Configuration conf) {
- ObjectCache objectCache = ObjectCache.get(conf);
- synchronized (objectCache) {
- this.indexWriters = (IndexWriter[]) objectCache
- .getObject(IndexWriter.class.getName());
- if (this.indexWriters == null) {
- try {
- ExtensionPoint point = PluginRepository.get(conf)
- .getExtensionPoint(IndexWriter.X_POINT_ID);
- if (point == null)
- throw new RuntimeException(IndexWriter.X_POINT_ID
- + " not found.");
- Extension[] extensions = point.getExtensions();
- HashMap<String, IndexWriter> indexerMap = new HashMap<String, IndexWriter>();
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- IndexWriter writer = (IndexWriter) extension
- .getExtensionInstance();
- LOG.info("Adding " + writer.getClass().getName());
- if (!indexerMap.containsKey(writer.getClass().getName())) {
- indexerMap.put(writer.getClass().getName(), writer);
- }
- }
- objectCache.setObject(IndexWriter.class.getName(), indexerMap
- .values().toArray(new IndexWriter[0]));
- } catch (PluginRuntimeException e) {
- throw new RuntimeException(e);
- }
- this.indexWriters = (IndexWriter[]) objectCache
- .getObject(IndexWriter.class.getName());
- }
- }
- }
+ public IndexWriters(Configuration conf) {
+ ObjectCache objectCache = ObjectCache.get(conf);
+ synchronized (objectCache) {
+ this.indexWriters = (IndexWriter[]) objectCache
+ .getObject(IndexWriter.class.getName());
+ if (this.indexWriters == null) {
+ try {
+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(
+ IndexWriter.X_POINT_ID);
+ if (point == null)
+ throw new RuntimeException(IndexWriter.X_POINT_ID + " not found.");
+ Extension[] extensions = point.getExtensions();
+ HashMap<String, IndexWriter> indexerMap = new HashMap<String, IndexWriter>();
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ IndexWriter writer = (IndexWriter) extension.getExtensionInstance();
+ LOG.info("Adding " + writer.getClass().getName());
+ if (!indexerMap.containsKey(writer.getClass().getName())) {
+ indexerMap.put(writer.getClass().getName(), writer);
+ }
+ }
+ objectCache.setObject(IndexWriter.class.getName(), indexerMap
+ .values().toArray(new IndexWriter[0]));
+ } catch (PluginRuntimeException e) {
+ throw new RuntimeException(e);
+ }
+ this.indexWriters = (IndexWriter[]) objectCache
+ .getObject(IndexWriter.class.getName());
+ }
+ }
+ }
- public void open(JobConf job, String name) throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].open(job, name);
- } catch (IOException ioe) {
- throw ioe;
- }
- }
- }
+ public void open(JobConf job, String name) throws IOException {
+ for (int i = 0; i < this.indexWriters.length; i++) {
+ try {
+ this.indexWriters[i].open(job, name);
+ } catch (IOException ioe) {
+ throw ioe;
+ }
+ }
+ }
- public void write(NutchDocument doc) throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].write(doc);
- } catch (IOException ioe) {
- throw ioe;
- }
- }
- }
+ public void write(NutchDocument doc) throws IOException {
+ for (int i = 0; i < this.indexWriters.length; i++) {
+ try {
+ this.indexWriters[i].write(doc);
+ } catch (IOException ioe) {
+ throw ioe;
+ }
+ }
+ }
- public void update(NutchDocument doc) throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].update(doc);
- } catch (IOException ioe) {
- throw ioe;
- }
- }
- }
+ public void update(NutchDocument doc) throws IOException {
+ for (int i = 0; i < this.indexWriters.length; i++) {
+ try {
+ this.indexWriters[i].update(doc);
+ } catch (IOException ioe) {
+ throw ioe;
+ }
+ }
+ }
- public void delete(String key) throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].delete(key);
- } catch (IOException ioe) {
- throw ioe;
- }
- }
- }
+ public void delete(String key) throws IOException {
+ for (int i = 0; i < this.indexWriters.length; i++) {
+ try {
+ this.indexWriters[i].delete(key);
+ } catch (IOException ioe) {
+ throw ioe;
+ }
+ }
+ }
- public void close() throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].close();
- } catch (IOException ioe) {
- throw ioe;
- }
- }
- }
+ public void close() throws IOException {
+ for (int i = 0; i < this.indexWriters.length; i++) {
+ try {
+ this.indexWriters[i].close();
+ } catch (IOException ioe) {
+ throw ioe;
+ }
+ }
+ }
- public void commit() throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].commit();
- } catch (IOException ioe) {
- throw ioe;
- }
- }
- }
+ public void commit() throws IOException {
+ for (int i = 0; i < this.indexWriters.length; i++) {
+ try {
+ this.indexWriters[i].commit();
+ } catch (IOException ioe) {
+ throw ioe;
+ }
+ }
+ }
- // lists the active IndexWriters and their configuration
- public String describe() throws IOException {
- StringBuffer buffer = new StringBuffer();
- if (this.indexWriters.length == 0)
- buffer.append("No IndexWriters activated - check your configuration\n");
- else
- buffer.append("Active IndexWriters :\n");
- for (int i = 0; i < this.indexWriters.length; i++) {
- buffer.append(this.indexWriters[i].describe()).append("\n");
- }
- return buffer.toString();
- }
+ // lists the active IndexWriters and their configuration
+ public String describe() throws IOException {
+ StringBuffer buffer = new StringBuffer();
+ if (this.indexWriters.length == 0)
+ buffer.append("No IndexWriters activated - check your configuration\n");
+ else
+ buffer.append("Active IndexWriters :\n");
+ for (int i = 0; i < this.indexWriters.length; i++) {
+ buffer.append(this.indexWriters[i].describe()).append("\n");
+ }
+ return buffer.toString();
+ }
}
diff --git a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java b/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
index 67cd4f02a..050109e7b 100644
--- a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
+++ b/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
@@ -50,11 +50,12 @@ import org.apache.nutch.parse.ParseText;
import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.scoring.ScoringFilters;
-public class IndexerMapReduce extends Configured
-implements Mapper<Text, Writable, Text, NutchWritable>,
- Reducer<Text, NutchWritable, Text, NutchIndexAction> {
+public class IndexerMapReduce extends Configured implements
+ Mapper<Text, Writable, Text, NutchWritable>,
+ Reducer<Text, NutchWritable, Text, NutchIndexAction> {
- public static final Logger LOG = LoggerFactory.getLogger(IndexerMapReduce.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(IndexerMapReduce.class);
public static final String INDEXER_PARAMS = "indexer.additional.params";
public static final String INDEXER_DELETE = "indexer.delete";
@@ -82,14 +83,16 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
this.filters = new IndexingFilters(getConf());
this.scfilters = new ScoringFilters(getConf());
this.delete = job.getBoolean(INDEXER_DELETE, false);
- this.deleteRobotsNoIndex = job.getBoolean(INDEXER_DELETE_ROBOTS_NOINDEX, false);
+ this.deleteRobotsNoIndex = job.getBoolean(INDEXER_DELETE_ROBOTS_NOINDEX,
+ false);
this.skip = job.getBoolean(INDEXER_SKIP_NOTMODIFIED, false);
normalize = job.getBoolean(URL_NORMALIZING, false);
filter = job.getBoolean(URL_FILTERING, false);
if (normalize) {
- urlNormalizers = new URLNormalizers(getConf(), URLNormalizers.SCOPE_INDEXER);
+ urlNormalizers = new URLNormalizers(getConf(),
+ URLNormalizers.SCOPE_INDEXER);
}
if (filter) {
@@ -99,9 +102,10 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
/**
* Normalizes and trims extra whitespace from the given url.
- *
- * @param url The url to normalize.
- *
+ *
+ * @param url
+ * The url to normalize.
+ *
* @return The normalized url.
*/
private String normalizeUrl(String url) {
@@ -114,11 +118,10 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
try {
// normalize and trim the url
- normalized = urlNormalizers.normalize(url,
- URLNormalizers.SCOPE_INDEXER);
+ normalized = urlNormalizers
+ .normalize(url, URLNormalizers.SCOPE_INDEXER);
normalized = normalized.trim();
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.warn("Skipping " + url + ":" + e);
normalized = null;
}
@@ -129,9 +132,10 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
/**
* Filters the given url.
- *
- * @param url The url to filter.
- *
+ *
+ * @param url
+ * The url to filter.
+ *
* @return The filtered url or null.
*/
private String filterUrl(String url) {
@@ -149,7 +153,8 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
}
public void map(Text key, Writable value,
- OutputCollector<Text, NutchWritable> output, Reporter reporter) throws IOException {
+ OutputCollector<Text, NutchWritable> output, Reporter reporter)
+ throws IOException {
String urlString = filterUrl(normalizeUrl(key.toString()));
if (urlString == null) {
@@ -162,8 +167,8 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
}
public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<Text, NutchIndexAction> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, NutchIndexAction> output, Reporter reporter)
+ throws IOException {
Inlinks inlinks = null;
CrawlDatum dbDatum = null;
CrawlDatum fetchDatum = null;
@@ -173,26 +178,25 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
while (values.hasNext()) {
final Writable value = values.next().get(); // unwrap
if (value instanceof Inlinks) {
- inlinks = (Inlinks)value;
+ inlinks = (Inlinks) value;
} else if (value instanceof CrawlDatum) {
- final CrawlDatum datum = (CrawlDatum)value;
+ final CrawlDatum datum = (CrawlDatum) value;
if (CrawlDatum.hasDbStatus(datum)) {
dbDatum = datum;
- }
- else if (CrawlDatum.hasFetchStatus(datum)) {
+ } else if (CrawlDatum.hasFetchStatus(datum)) {
// don't index unmodified (empty) pages
if (datum.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
fetchDatum = datum;
}
- } else if (CrawlDatum.STATUS_LINKED == datum.getStatus() ||
- CrawlDatum.STATUS_SIGNATURE == datum.getStatus() ||
- CrawlDatum.STATUS_PARSE_META == datum.getStatus()) {
+ } else if (CrawlDatum.STATUS_LINKED == datum.getStatus()
+ || CrawlDatum.STATUS_SIGNATURE == datum.getStatus()
+ || CrawlDatum.STATUS_PARSE_META == datum.getStatus()) {
continue;
} else {
- throw new RuntimeException("Unexpected status: "+datum.getStatus());
+ throw new RuntimeException("Unexpected status: " + datum.getStatus());
}
} else if (value instanceof ParseData) {
- parseData = (ParseData)value;
+ parseData = (ParseData) value;
// Handle robots meta? https://issues.apache.org/jira/browse/NUTCH-1434
if (deleteRobotsNoIndex) {
@@ -200,64 +204,70 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
String robotsMeta = parseData.getMeta("robots");
// Has it a noindex for this url?
- if (robotsMeta != null && robotsMeta.toLowerCase().indexOf("noindex") != -1) {
+ if (robotsMeta != null
+ && robotsMeta.toLowerCase().indexOf("noindex") != -1) {
// Delete it!
- NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE);
+ NutchIndexAction action = new NutchIndexAction(null,
+ NutchIndexAction.DELETE);
output.collect(key, action);
return;
}
}
} else if (value instanceof ParseText) {
- parseText = (ParseText)value;
+ parseText = (ParseText) value;
} else if (LOG.isWarnEnabled()) {
- LOG.warn("Unrecognized type: "+value.getClass());
+ LOG.warn("Unrecognized type: " + value.getClass());
}
}
-
+
// Whether to delete GONE or REDIRECTS
- if (delete && fetchDatum != null && dbDatum != null) {
- if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_GONE || dbDatum.getStatus() == CrawlDatum.STATUS_DB_GONE) {
+ if (delete && fetchDatum != null && dbDatum != null) {
+ if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_GONE
+ || dbDatum.getStatus() == CrawlDatum.STATUS_DB_GONE) {
reporter.incrCounter("IndexerStatus", "Documents deleted", 1);
- NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE);
+ NutchIndexAction action = new NutchIndexAction(null,
+ NutchIndexAction.DELETE);
output.collect(key, action);
return;
}
-
- if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM ||
- fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP ||
- dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_PERM ||
- dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_TEMP) {
+
+ if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM
+ || fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP
+ || dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_PERM
+ || dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_TEMP) {
reporter.incrCounter("IndexerStatus", "Deleted redirects", 1);
reporter.incrCounter("IndexerStatus", "Perm redirects deleted", 1);
- NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE);
+ NutchIndexAction action = new NutchIndexAction(null,
+ NutchIndexAction.DELETE);
output.collect(key, action);
return;
}
}
- if (fetchDatum == null || dbDatum == null
- || parseText == null || parseData == null) {
- return; // only have inlinks
+ if (fetchDatum == null || dbDatum == null || parseText == null
+ || parseData == null) {
+ return; // only have inlinks
}
// Whether to delete pages marked as duplicates
if (delete && dbDatum.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
reporter.incrCounter("IndexerStatus", "Duplicates deleted", 1);
- NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE);
+ NutchIndexAction action = new NutchIndexAction(null,
+ NutchIndexAction.DELETE);
output.collect(key, action);
return;
}
-
+
// Whether to skip DB_NOTMODIFIED pages
if (skip && dbDatum.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
reporter.incrCounter("IndexerStatus", "Skipped", 1);
return;
}
- if (!parseData.getStatus().isSuccess() ||
- fetchDatum.getStatus() != CrawlDatum.STATUS_FETCH_SUCCESS) {
+ if (!parseData.getStatus().isSuccess()
+ || fetchDatum.getStatus() != CrawlDatum.STATUS_FETCH_SUCCESS) {
return;
}
@@ -276,11 +286,13 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
try {
// extract information from dbDatum and pass it to
// fetchDatum so that indexing filters can use it
- final Text url = (Text) dbDatum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
+ final Text url = (Text) dbDatum.getMetaData().get(
+ Nutch.WRITABLE_REPR_URL_KEY);
if (url != null) {
// Representation URL also needs normalization and filtering.
// If repr URL is excluded by filters we still accept this document
- // but represented by its primary URL ("key") which has passed URL filters.
+ // but represented by its primary URL ("key") which has passed URL
+ // filters.
String urlString = filterUrl(normalizeUrl(url.toString()));
if (urlString != null) {
url.set(urlString);
@@ -290,7 +302,9 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
// run indexing filters
doc = this.filters.filter(doc, parse, key, fetchDatum, inlinks);
} catch (final IndexingException e) {
- if (LOG.isWarnEnabled()) { LOG.warn("Error indexing "+key+": "+e); }
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Error indexing " + key + ": " + e);
+ }
reporter.incrCounter("IndexerStatus", "Errors", 1);
return;
}
@@ -304,8 +318,8 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
float boost = 1.0f;
// run scoring filters
try {
- boost = this.scfilters.indexerScore(key, doc, dbDatum,
- fetchDatum, parse, inlinks, boost);
+ boost = this.scfilters.indexerScore(key, doc, dbDatum, fetchDatum, parse,
+ inlinks, boost);
} catch (final ScoringFilterException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Error calculating score " + key + ": " + e);
@@ -323,30 +337,32 @@ implements Mapper<Text, Writable, Text, NutchWritable>,
output.collect(key, action);
}
- public void close() throws IOException { }
+ public void close() throws IOException {
+ }
public static void initMRJob(Path crawlDb, Path linkDb,
- Collection<Path> segments,
- JobConf job) {
+ Collection<Path> segments, JobConf job) {
LOG.info("IndexerMapReduce: crawldb: " + crawlDb);
-
- if (linkDb!=null)
+
+ if (linkDb != null)
LOG.info("IndexerMapReduce: linkdb: " + linkDb);
for (final Path segment : segments) {
LOG.info("IndexerMapReduces: adding segment: " + segment);
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.FETCH_DIR_NAME));
- FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.PARSE_DIR_NAME));
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.FETCH_DIR_NAME));
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.PARSE_DIR_NAME));
FileInputFormat.addInputPath(job, new Path(segment, ParseData.DIR_NAME));
FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME));
}
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
-
- if (linkDb!=null)
- FileInputFormat.addInputPath(job, new Path(linkDb, LinkDb.CURRENT_NAME));
-
+
+ if (linkDb != null)
+ FileInputFormat.addInputPath(job, new Path(linkDb, LinkDb.CURRENT_NAME));
+
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(IndexerMapReduce.class);
diff --git a/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java b/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
index 6b4b068e5..baa9ce619 100644
--- a/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
+++ b/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
@@ -27,31 +27,31 @@ import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
public class IndexerOutputFormat extends
- FileOutputFormat<Text, NutchIndexAction> {
+ FileOutputFormat<Text, NutchIndexAction> {
- @Override
- public RecordWriter<Text, NutchIndexAction> getRecordWriter(
- FileSystem ignored, JobConf job, String name, Progressable progress)
- throws IOException {
+ @Override
+ public RecordWriter<Text, NutchIndexAction> getRecordWriter(
+ FileSystem ignored, JobConf job, String name, Progressable progress)
+ throws IOException {
- final IndexWriters writers = new IndexWriters(job);
+ final IndexWriters writers = new IndexWriters(job);
- writers.open(job, name);
+ writers.open(job, name);
- return new RecordWriter<Text, NutchIndexAction>() {
+ return new RecordWriter<Text, NutchIndexAction>() {
- public void close(Reporter reporter) throws IOException {
- writers.close();
- }
+ public void close(Reporter reporter) throws IOException {
+ writers.close();
+ }
- public void write(Text key, NutchIndexAction indexAction)
- throws IOException {
- if (indexAction.action == NutchIndexAction.ADD) {
- writers.write(indexAction.doc);
- } else if (indexAction.action == NutchIndexAction.DELETE) {
- writers.delete(key.toString());
- }
- }
- };
- }
+ public void write(Text key, NutchIndexAction indexAction)
+ throws IOException {
+ if (indexAction.action == NutchIndexAction.ADD) {
+ writers.write(indexAction.doc);
+ } else if (indexAction.action == NutchIndexAction.DELETE) {
+ writers.delete(key.toString());
+ }
+ }
+ };
+ }
}
diff --git a/src/java/org/apache/nutch/indexer/IndexingFilter.java b/src/java/org/apache/nutch/indexer/IndexingFilter.java
index 589db4c46..2dcdefffd 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFilter.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFilter.java
@@ -28,9 +28,9 @@ import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.plugin.Pluggable;
-
-/** Extension point for indexing. Permits one to add metadata to the indexed
- * fields. All plugins found which implement this extension point are run
+/**
+ * Extension point for indexing. Permits one to add metadata to the indexed
+ * fields. All plugins found which implement this extension point are run
* sequentially on the parse.
*/
public interface IndexingFilter extends Pluggable, Configurable {
@@ -57,6 +57,6 @@ public interface IndexingFilter extends Pluggable, Configurable {
* document should be discarded)
* @throws IndexingException
*/
- NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks)
- throws IndexingException;
+ NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException;
}
diff --git a/src/java/org/apache/nutch/indexer/IndexingFilters.java b/src/java/org/apache/nutch/indexer/IndexingFilters.java
index 66e248a22..334fcad31 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFilters.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFilters.java
@@ -28,12 +28,13 @@ import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.hadoop.io.Text;
-/** Creates and caches {@link IndexingFilter} implementing plugins.*/
+/** Creates and caches {@link IndexingFilter} implementing plugins. */
public class IndexingFilters {
public static final String INDEXINGFILTER_ORDER = "indexingfilter.order";
- public final static Logger LOG = LoggerFactory.getLogger(IndexingFilters.class);
+ public final static Logger LOG = LoggerFactory
+ .getLogger(IndexingFilters.class);
private IndexingFilter[] indexingFilters;
@@ -44,12 +45,13 @@ public class IndexingFilters {
}
/** Run all defined filters. */
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum,
- Inlinks inlinks) throws IndexingException {
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
for (int i = 0; i < this.indexingFilters.length; i++) {
doc = this.indexingFilters[i].filter(doc, parse, url, datum, inlinks);
// break the loop if an indexing filter discards the doc
- if (doc == null) return null;
+ if (doc == null)
+ return null;
}
return doc;
diff --git a/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java b/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
index 0dc292b8e..b7dab22af 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
package org.apache.nutch.indexer;
import java.util.List;
@@ -46,16 +46,19 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Reads and parses a URL and run the indexers on it. Displays the fields obtained and the first
- * 100 characters of their value
- *
- * Tested with e.g. ./nutch org.apache.nutch.indexer.IndexingFiltersChecker http://www.lemonde.fr
+ * Reads and parses a URL and run the indexers on it. Displays the fields
+ * obtained and the first 100 characters of their value
+ *
+ * Tested with e.g. ./nutch org.apache.nutch.indexer.IndexingFiltersChecker
+ * http://www.lemonde.fr
+ *
* @author Julien Nioche
**/
public class IndexingFiltersChecker extends Configured implements Tool {
- public static final Logger LOG = LoggerFactory.getLogger(IndexingFiltersChecker.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(IndexingFiltersChecker.class);
public IndexingFiltersChecker() {
@@ -95,12 +98,13 @@ public class IndexingFiltersChecker extends Configured implements Tool {
CrawlDatum datum = new CrawlDatum();
ProtocolOutput output = protocol.getProtocolOutput(new Text(url), datum);
-
+
if (!output.getStatus().isSuccess()) {
- System.out.println("Fetch failed with protocol status: " + output.getStatus());
+ System.out.println("Fetch failed with protocol status: "
+ + output.getStatus());
return 0;
}
-
+
Content content = output.getContent();
if (content == null) {
@@ -115,7 +119,8 @@ public class IndexingFiltersChecker extends Configured implements Tool {
}
// store the guessed content type in the crawldatum
- datum.getMetaData().put(new Text(Metadata.CONTENT_TYPE), new Text(contentType));
+ datum.getMetaData().put(new Text(Metadata.CONTENT_TYPE),
+ new Text(contentType));
if (ParseSegment.isTruncated(content)) {
LOG.warn("Content is truncated, parse may fail!");
@@ -162,7 +167,7 @@ public class IndexingFiltersChecker extends Configured implements Tool {
System.out.println("Document discarded by indexing filter");
return 0;
}
-
+
for (String fname : doc.getFieldNames()) {
List<Object> values = doc.getField(fname).getValues();
if (values != null) {
@@ -173,14 +178,14 @@ public class IndexingFiltersChecker extends Configured implements Tool {
}
}
}
-
- if (conf.getBoolean("doIndex", false) && doc!=null){
+
+ if (conf.getBoolean("doIndex", false) && doc != null) {
IndexWriters writers = new IndexWriters(getConf());
writers.open(new JobConf(getConf()), "IndexingFilterChecker");
writers.write(doc);
writers.close();
}
-
+
return 0;
}
diff --git a/src/java/org/apache/nutch/indexer/IndexingJob.java b/src/java/org/apache/nutch/indexer/IndexingJob.java
index 8478df808..208641898 100644
--- a/src/java/org/apache/nutch/indexer/IndexingJob.java
+++ b/src/java/org/apache/nutch/indexer/IndexingJob.java
@@ -46,145 +46,143 @@ import org.slf4j.LoggerFactory;
public class IndexingJob extends Configured implements Tool {
- public static Logger LOG = LoggerFactory.getLogger(IndexingJob.class);
+ public static Logger LOG = LoggerFactory.getLogger(IndexingJob.class);
- public IndexingJob() {
- super(null);
- }
+ public IndexingJob() {
+ super(null);
+ }
- public IndexingJob(Configuration conf) {
- super(conf);
- }
+ public IndexingJob(Configuration conf) {
+ super(conf);
+ }
- public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit) throws IOException {
- index(crawlDb, linkDb, segments, noCommit, false, null);
- }
+ public void index(Path crawlDb, Path linkDb, List<Path> segments,
+ boolean noCommit) throws IOException {
+ index(crawlDb, linkDb, segments, noCommit, false, null);
+ }
- public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit, boolean deleteGone) throws IOException {
- index(crawlDb, linkDb, segments, noCommit, deleteGone, null);
- }
+ public void index(Path crawlDb, Path linkDb, List<Path> segments,
+ boolean noCommit, boolean deleteGone) throws IOException {
+ index(crawlDb, linkDb, segments, noCommit, deleteGone, null);
+ }
- public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit, boolean deleteGone, String params)
- throws IOException {
- index(crawlDb, linkDb, segments, noCommit, deleteGone, params, false,
- false);
- }
+ public void index(Path crawlDb, Path linkDb, List<Path> segments,
+ boolean noCommit, boolean deleteGone, String params) throws IOException {
+ index(crawlDb, linkDb, segments, noCommit, deleteGone, params, false, false);
+ }
- public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit, boolean deleteGone, String params,
- boolean filter, boolean normalize) throws IOException {
+ public void index(Path crawlDb, Path linkDb, List<Path> segments,
+ boolean noCommit, boolean deleteGone, String params, boolean filter,
+ boolean normalize) throws IOException {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- long start = System.currentTimeMillis();
- LOG.info("Indexer: starting at " + sdf.format(start));
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ long start = System.currentTimeMillis();
+ LOG.info("Indexer: starting at " + sdf.format(start));
- final JobConf job = new NutchJob(getConf());
- job.setJobName("Indexer");
+ final JobConf job = new NutchJob(getConf());
+ job.setJobName("Indexer");
- LOG.info("Indexer: deleting gone documents: " + deleteGone);
- LOG.info("Indexer: URL filtering: " + filter);
- LOG.info("Indexer: URL normalizing: " + normalize);
-
- IndexWriters writers = new IndexWriters(getConf());
- LOG.info(writers.describe());
+ LOG.info("Indexer: deleting gone documents: " + deleteGone);
+ LOG.info("Indexer: URL filtering: " + filter);
+ LOG.info("Indexer: URL normalizing: " + normalize);
- IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job);
+ IndexWriters writers = new IndexWriters(getConf());
+ LOG.info(writers.describe());
- // NOW PASSED ON THE COMMAND LINE AS A HADOOP PARAM
- // job.set(SolrConstants.SERVER_URL, solrUrl);
+ IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job);
- job.setBoolean(IndexerMapReduce.INDEXER_DELETE, deleteGone);
- job.setBoolean(IndexerMapReduce.URL_FILTERING, filter);
- job.setBoolean(IndexerMapReduce.URL_NORMALIZING, normalize);
+ // NOW PASSED ON THE COMMAND LINE AS A HADOOP PARAM
+ // job.set(SolrConstants.SERVER_URL, solrUrl);
- if (params != null) {
- job.set(IndexerMapReduce.INDEXER_PARAMS, params);
- }
+ job.setBoolean(IndexerMapReduce.INDEXER_DELETE, deleteGone);
+ job.setBoolean(IndexerMapReduce.URL_FILTERING, filter);
+ job.setBoolean(IndexerMapReduce.URL_NORMALIZING, normalize);
- job.setReduceSpeculativeExecution(false);
-
- final Path tmp = new Path("tmp_" + System.currentTimeMillis() + "-"
- + new Random().nextInt());
-
- FileOutputFormat.setOutputPath(job, tmp);
- try {
- JobClient.runJob(job);
- // do the commits once and for all the reducers in one go
- if (!noCommit) {
- writers.open(job,"commit");
- writers.commit();
- }
- long end = System.currentTimeMillis();
- LOG.info("Indexer: finished at " + sdf.format(end) + ", elapsed: "
- + TimingUtil.elapsedTime(start, end));
- } finally {
- FileSystem.get(job).delete(tmp, true);
- }
+ if (params != null) {
+ job.set(IndexerMapReduce.INDEXER_PARAMS, params);
}
- public int run(String[] args) throws Exception {
- if (args.length < 2) {
- System.err
- .println("Usage: Indexer <crawldb> [-linkdb <linkdb>] [-params k1=v1&k2=v2...] (<segment> ... | -dir <segments>) [-noCommit] [-deleteGone] [-filter] [-normalize]");
- IndexWriters writers = new IndexWriters(getConf());
- System.err.println(writers.describe());
- return -1;
- }
-
- final Path crawlDb = new Path(args[0]);
- Path linkDb = null;
-
- final List<Path> segments = new ArrayList<Path>();
- String params = null;
-
- boolean noCommit = false;
- boolean deleteGone = false;
- boolean filter = false;
- boolean normalize = false;
-
- for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-linkdb")) {
- linkDb = new Path(args[++i]);
- } else if (args[i].equals("-dir")) {
- Path dir = new Path(args[++i]);
- FileSystem fs = dir.getFileSystem(getConf());
- FileStatus[] fstats = fs.listStatus(dir,
- HadoopFSUtil.getPassDirectoriesFilter(fs));
- Path[] files = HadoopFSUtil.getPaths(fstats);
- for (Path p : files) {
- segments.add(p);
- }
- } else if (args[i].equals("-noCommit")) {
- noCommit = true;
- } else if (args[i].equals("-deleteGone")) {
- deleteGone = true;
- } else if (args[i].equals("-filter")) {
- filter = true;
- } else if (args[i].equals("-normalize")) {
- normalize = true;
- } else if (args[i].equals("-params")) {
- params = args[++i];
- } else {
- segments.add(new Path(args[i]));
- }
- }
+ job.setReduceSpeculativeExecution(false);
+
+ final Path tmp = new Path("tmp_" + System.currentTimeMillis() + "-"
+ + new Random().nextInt());
+
+ FileOutputFormat.setOutputPath(job, tmp);
+ try {
+ JobClient.runJob(job);
+ // do the commits once and for all the reducers in one go
+ if (!noCommit) {
+ writers.open(job, "commit");
+ writers.commit();
+ }
+ long end = System.currentTimeMillis();
+ LOG.info("Indexer: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
+ } finally {
+ FileSystem.get(job).delete(tmp, true);
+ }
+ }
+
+ public int run(String[] args) throws Exception {
+ if (args.length < 2) {
+ System.err
+ .println("Usage: Indexer <crawldb> [-linkdb <linkdb>] [-params k1=v1&k2=v2...] (<segment> ... | -dir <segments>) [-noCommit] [-deleteGone] [-filter] [-normalize]");
+ IndexWriters writers = new IndexWriters(getConf());
+ System.err.println(writers.describe());
+ return -1;
+ }
- try {
- index(crawlDb, linkDb, segments, noCommit, deleteGone, params,
- filter, normalize);
- return 0;
- } catch (final Exception e) {
- LOG.error("Indexer: " + StringUtils.stringifyException(e));
- return -1;
+ final Path crawlDb = new Path(args[0]);
+ Path linkDb = null;
+
+ final List<Path> segments = new ArrayList<Path>();
+ String params = null;
+
+ boolean noCommit = false;
+ boolean deleteGone = false;
+ boolean filter = false;
+ boolean normalize = false;
+
+ for (int i = 1; i < args.length; i++) {
+ if (args[i].equals("-linkdb")) {
+ linkDb = new Path(args[++i]);
+ } else if (args[i].equals("-dir")) {
+ Path dir = new Path(args[++i]);
+ FileSystem fs = dir.getFileSystem(getConf());
+ FileStatus[] fstats = fs.listStatus(dir,
+ HadoopFSUtil.getPassDirectoriesFilter(fs));
+ Path[] files = HadoopFSUtil.getPaths(fstats);
+ for (Path p : files) {
+ segments.add(p);
}
+ } else if (args[i].equals("-noCommit")) {
+ noCommit = true;
+ } else if (args[i].equals("-deleteGone")) {
+ deleteGone = true;
+ } else if (args[i].equals("-filter")) {
+ filter = true;
+ } else if (args[i].equals("-normalize")) {
+ normalize = true;
+ } else if (args[i].equals("-params")) {
+ params = args[++i];
+ } else {
+ segments.add(new Path(args[i]));
+ }
}
- public static void main(String[] args) throws Exception {
- final int res = ToolRunner.run(NutchConfiguration.create(),
- new IndexingJob(), args);
- System.exit(res);
+ try {
+ index(crawlDb, linkDb, segments, noCommit, deleteGone, params, filter,
+ normalize);
+ return 0;
+ } catch (final Exception e) {
+ LOG.error("Indexer: " + StringUtils.stringifyException(e));
+ return -1;
}
+ }
+
+ public static void main(String[] args) throws Exception {
+ final int res = ToolRunner.run(NutchConfiguration.create(),
+ new IndexingJob(), args);
+ System.exit(res);
+ }
}
diff --git a/src/java/org/apache/nutch/indexer/NutchDocument.java b/src/java/org/apache/nutch/indexer/NutchDocument.java
index 9265853b0..efdde020f 100644
--- a/src/java/org/apache/nutch/indexer/NutchDocument.java
+++ b/src/java/org/apache/nutch/indexer/NutchDocument.java
@@ -31,12 +31,12 @@ import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.nutch.metadata.Metadata;
-/** A {@link NutchDocument} is the unit of indexing.*/
-public class NutchDocument
-implements Writable, Iterable<Entry<String, NutchField>> {
+/** A {@link NutchDocument} is the unit of indexing. */
+public class NutchDocument implements Writable,
+ Iterable<Entry<String, NutchField>> {
public static final byte VERSION = 2;
-
+
private Map<String, NutchField> fields;
private Metadata documentMeta;
@@ -127,8 +127,8 @@ implements Writable, Iterable<Entry<String, NutchField>> {
out.writeFloat(weight);
documentMeta.write(out);
}
-
- public String toString() {
+
+ public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("doc {\n");
for (Map.Entry<String, NutchField> entry : fields.entrySet()) {
diff --git a/src/java/org/apache/nutch/indexer/NutchField.java b/src/java/org/apache/nutch/indexer/NutchField.java
index 110401a56..33911e1ba 100644
--- a/src/java/org/apache/nutch/indexer/NutchField.java
+++ b/src/java/org/apache/nutch/indexer/NutchField.java
@@ -28,32 +28,33 @@ import java.util.List;
import org.apache.hadoop.io.*;
/**
- * This class represents a multi-valued field with a weight.
- * Values are arbitrary objects.
+ * This class represents a multi-valued field with a weight. Values are
+ * arbitrary objects.
*/
public class NutchField implements Writable {
private float weight;
private List<Object> values = new ArrayList<Object>();
-
- public NutchField() { }
-
+
+ public NutchField() {
+ }
+
public NutchField(Object value) {
this(value, 1.0f);
}
-
+
public NutchField(Object value, float weight) {
this.weight = weight;
if (value instanceof Collection) {
- values.addAll((Collection<?>)value);
+ values.addAll((Collection<?>) value);
} else {
values.add(value);
}
}
-
+
public void add(Object value) {
values.add(value);
}
-
+
public float getWeight() {
return weight;
}
@@ -65,7 +66,7 @@ public class NutchField implements Writable {
public List<Object> getValues() {
return values;
}
-
+
public void reset() {
weight = 1.0f;
values.clear();
@@ -73,13 +74,13 @@ public class NutchField implements Writable {
@Override
public Object clone() throws CloneNotSupportedException {
- NutchField result = (NutchField)super.clone();
+ NutchField result = (NutchField) super.clone();
result.weight = weight;
result.values = values;
return result;
}
-
+
@Override
public void readFields(DataInput in) throws IOException {
weight = in.readFloat();
@@ -87,7 +88,7 @@ public class NutchField implements Writable {
values = new ArrayList<Object>();
for (int i = 0; i < count; i++) {
String type = Text.readString(in);
-
+
if (type.equals("java.lang.String")) {
values.add(Text.readString(in));
} else if (type.equals("java.lang.Boolean")) {
@@ -109,26 +110,26 @@ public class NutchField implements Writable {
out.writeFloat(weight);
out.writeInt(values.size());
for (Object value : values) {
-
+
Text.writeString(out, value.getClass().getName());
-
+
if (value instanceof Boolean) {
- out.writeBoolean((Boolean)value);
+ out.writeBoolean((Boolean) value);
} else if (value instanceof Integer) {
- out.writeInt((Integer)value);
+ out.writeInt((Integer) value);
} else if (value instanceof Long) {
- out.writeLong((Long)value);
+ out.writeLong((Long) value);
} else if (value instanceof Float) {
- out.writeFloat((Float)value);
+ out.writeFloat((Float) value);
} else if (value instanceof String) {
- Text.writeString(out, (String)value);
+ Text.writeString(out, (String) value);
} else if (value instanceof Date) {
- Date date = (Date)value;
+ Date date = (Date) value;
out.writeLong(date.getTime());
}
}
}
-
+
public String toString() {
return values.toString();
}
diff --git a/src/java/org/apache/nutch/indexer/NutchIndexAction.java b/src/java/org/apache/nutch/indexer/NutchIndexAction.java
index d7975c256..679d7846d 100644
--- a/src/java/org/apache/nutch/indexer/NutchIndexAction.java
+++ b/src/java/org/apache/nutch/indexer/NutchIndexAction.java
@@ -25,8 +25,8 @@ import org.apache.hadoop.io.Writable;
import org.apache.nutch.indexer.NutchDocument;
/**
- * A {@link NutchIndexAction} is the new unit of indexing holding the
- * document and action information.
+ * A {@link NutchIndexAction} is the new unit of indexing holding the document
+ * and action information.
*/
public class NutchIndexAction implements Writable {
diff --git a/src/java/org/apache/nutch/metadata/CreativeCommons.java b/src/java/org/apache/nutch/metadata/CreativeCommons.java
index c359c292d..f9c425bc0 100644
--- a/src/java/org/apache/nutch/metadata/CreativeCommons.java
+++ b/src/java/org/apache/nutch/metadata/CreativeCommons.java
@@ -16,21 +16,20 @@
*/
package org.apache.nutch.metadata;
-
/**
* A collection of Creative Commons properties names.
- *
+ *
* @see <a href="http://www.creativecommons.org/">creativecommons.org</a>
- *
+ *
* @author Chris Mattmann
* @author J&eacute;r&ocirc;me Charron
*/
public interface CreativeCommons {
-
+
public final static String LICENSE_URL = "License-Url";
-
+
public final static String LICENSE_LOCATION = "License-Location";
-
+
public final static String WORK_TYPE = "Work-Type";
-
+
}
diff --git a/src/java/org/apache/nutch/metadata/DublinCore.java b/src/java/org/apache/nutch/metadata/DublinCore.java
index dce3df316..9724d8026 100644
--- a/src/java/org/apache/nutch/metadata/DublinCore.java
+++ b/src/java/org/apache/nutch/metadata/DublinCore.java
@@ -16,149 +16,146 @@
*/
package org.apache.nutch.metadata;
-
/**
* A collection of Dublin Core metadata names.
- *
- * @see <a href="http://dublincore.org">dublincore.org</a>
- *
+ *
+ * @see <a href="http://dublincore.org">dublincore.org</a>
+ *
* @author Chris Mattmann
* @author J&eacute;r&ocirc;me Charron
*/
public interface DublinCore {
-
-
+
/**
- * Typically, Format may include the media-type or dimensions of the
- * resource. Format may be used to determine the software, hardware or other
- * equipment needed to display or operate the resource. Examples of
- * dimensions include size and duration. Recommended best practice is to
- * select a value from a controlled vocabulary (for example, the list of
- * Internet Media Types [MIME] defining computer media formats).
+ * Typically, Format may include the media-type or dimensions of the resource.
+ * Format may be used to determine the software, hardware or other equipment
+ * needed to display or operate the resource. Examples of dimensions include
+ * size and duration. Recommended best practice is to select a value from a
+ * controlled vocabulary (for example, the list of Internet Media Types [MIME]
+ * defining computer media formats).
*/
public static final String FORMAT = "format";
-
+
/**
- * Recommended best practice is to identify the resource by means of a
- * string or number conforming to a formal identification system. Example
- * formal identification systems include the Uniform Resource Identifier
- * (URI) (including the Uniform Resource Locator (URL)), the Digital Object
+ * Recommended best practice is to identify the resource by means of a string
+ * or number conforming to a formal identification system. Example formal
+ * identification systems include the Uniform Resource Identifier (URI)
+ * (including the Uniform Resource Locator (URL)), the Digital Object
* Identifier (DOI) and the International Standard Book Number (ISBN).
*/
public static final String IDENTIFIER = "identifier";
-
+
/**
* Date on which the resource was changed.
*/
public static final String MODIFIED = "modified";
-
+
/**
* An entity responsible for making contributions to the content of the
- * resource. Examples of a Contributor include a person, an organisation, or
- * a service. Typically, the name of a Contributor should be used to
- * indicate the entity.
+ * resource. Examples of a Contributor include a person, an organisation, or a
+ * service. Typically, the name of a Contributor should be used to indicate
+ * the entity.
*/
public static final String CONTRIBUTOR = "contributor";
-
+
/**
- * The extent or scope of the content of the resource. Coverage will
- * typically include spatial location (a place name or geographic
- * coordinates), temporal period (a period label, date, or date range) or
- * jurisdiction (such as a named administrative entity). Recommended best
- * practice is to select a value from a controlled vocabulary (for example,
- * the Thesaurus of Geographic Names [TGN]) and that, where appropriate,
- * named places or time periods be used in preference to numeric identifiers
- * such as sets of coordinates or date ranges.
+ * The extent or scope of the content of the resource. Coverage will typically
+ * include spatial location (a place name or geographic coordinates), temporal
+ * period (a period label, date, or date range) or jurisdiction (such as a
+ * named administrative entity). Recommended best practice is to select a
+ * value from a controlled vocabulary (for example, the Thesaurus of
+ * Geographic Names [TGN]) and that, where appropriate, named places or time
+ * periods be used in preference to numeric identifiers such as sets of
+ * coordinates or date ranges.
*/
public static final String COVERAGE = "coverage";
-
+
/**
* An entity primarily responsible for making the content of the resource.
* Examples of a Creator include a person, an organisation, or a service.
* Typically, the name of a Creator should be used to indicate the entity.
*/
public static final String CREATOR = "creator";
-
+
/**
* A date associated with an event in the life cycle of the resource.
- * Typically, Date will be associated with the creation or availability of
- * the resource. Recommended best practice for encoding the date value is
- * defined in a profile of ISO 8601 [W3CDTF] and follows the YYYY-MM-DD
- * format.
+ * Typically, Date will be associated with the creation or availability of the
+ * resource. Recommended best practice for encoding the date value is defined
+ * in a profile of ISO 8601 [W3CDTF] and follows the YYYY-MM-DD format.
*/
public static final String DATE = "date";
-
+
/**
* An account of the content of the resource. Description may include but is
* not limited to: an abstract, table of contents, reference to a graphical
* representation of content or a free-text account of the content.
*/
public static final String DESCRIPTION = "description";
-
+
/**
* A language of the intellectual content of the resource. Recommended best
* practice is to use RFC 3066 [RFC3066], which, in conjunction with ISO 639
- * [ISO639], defines two- and three-letter primary language tags with
- * optional subtags. Examples include "en" or "eng" for English, "akk" for
- * Akkadian, and "en-GB" for English used in the United Kingdom.
+ * [ISO639], defines two- and three-letter primary language tags with optional
+ * subtags. Examples include "en" or "eng" for English, "akk" for Akkadian,
+ * and "en-GB" for English used in the United Kingdom.
*/
public static final String LANGUAGE = "language";
-
+
/**
* An entity responsible for making the resource available. Examples of a
* Publisher include a person, an organisation, or a service. Typically, the
* name of a Publisher should be used to indicate the entity.
*/
public static final String PUBLISHER = "publisher";
-
+
/**
* A reference to a related resource. Recommended best practice is to
* reference the resource by means of a string or number conforming to a
* formal identification system.
*/
public static final String RELATION = "relation";
-
+
/**
- * Information about rights held in and over the resource. Typically, a
- * Rights element will contain a rights management statement for the
- * resource, or reference a service providing such information. Rights
- * information often encompasses Intellectual Property Rights (IPR),
- * Copyright, and various Property Rights. If the Rights element is absent,
- * no assumptions can be made about the status of these and other rights
- * with respect to the resource.
+ * Information about rights held in and over the resource. Typically, a Rights
+ * element will contain a rights management statement for the resource, or
+ * reference a service providing such information. Rights information often
+ * encompasses Intellectual Property Rights (IPR), Copyright, and various
+ * Property Rights. If the Rights element is absent, no assumptions can be
+ * made about the status of these and other rights with respect to the
+ * resource.
*/
public static final String RIGHTS = "rights";
-
+
/**
* A reference to a resource from which the present resource is derived. The
* present resource may be derived from the Source resource in whole or in
- * part. Recommended best practice is to reference the resource by means of
- * a string or number conforming to a formal identification system.
+ * part. Recommended best practice is to reference the resource by means of a
+ * string or number conforming to a formal identification system.
*/
public static final String SOURCE = "source";
-
+
/**
* The topic of the content of the resource. Typically, a Subject will be
- * expressed as keywords, key phrases or classification codes that describe
- * a topic of the resource. Recommended best practice is to select a value
- * from a controlled vocabulary or formal classification scheme.
+ * expressed as keywords, key phrases or classification codes that describe a
+ * topic of the resource. Recommended best practice is to select a value from
+ * a controlled vocabulary or formal classification scheme.
*/
public static final String SUBJECT = "subject";
-
+
/**
* A name given to the resource. Typically, a Title will be a name by which
* the resource is formally known.
*/
public static final String TITLE = "title";
-
+
/**
* The nature or genre of the content of the resource. Type includes terms
- * describing general categories, functions, genres, or aggregation levels
- * for content. Recommended best practice is to select a value from a
- * controlled vocabulary (for example, the DCMI Type Vocabulary [DCMITYPE]).
- * To describe the physical or digital manifestation of the resource, use
- * the Format element.
+ * describing general categories, functions, genres, or aggregation levels for
+ * content. Recommended best practice is to select a value from a controlled
+ * vocabulary (for example, the DCMI Type Vocabulary [DCMITYPE]). To describe
+ * the physical or digital manifestation of the resource, use the Format
+ * element.
*/
public static final String TYPE = "type";
-
+
}
diff --git a/src/java/org/apache/nutch/metadata/HttpHeaders.java b/src/java/org/apache/nutch/metadata/HttpHeaders.java
index 85845bf4a..78b87972d 100644
--- a/src/java/org/apache/nutch/metadata/HttpHeaders.java
+++ b/src/java/org/apache/nutch/metadata/HttpHeaders.java
@@ -20,32 +20,32 @@ import org.apache.hadoop.io.Text;
/**
* A collection of HTTP header names.
- *
- * @see <a href="http://rfc-ref.org/RFC-TEXTS/2616/">Hypertext Transfer
- * Protocol -- HTTP/1.1 (RFC 2616)</a>
+ *
+ * @see <a href="http://rfc-ref.org/RFC-TEXTS/2616/">Hypertext Transfer Protocol
+ * -- HTTP/1.1 (RFC 2616)</a>
*/
public interface HttpHeaders {
public final static String TRANSFER_ENCODING = "Transfer-Encoding";
-
+
public final static String CONTENT_ENCODING = "Content-Encoding";
-
+
public final static String CONTENT_LANGUAGE = "Content-Language";
public final static String CONTENT_LENGTH = "Content-Length";
-
+
public final static String CONTENT_LOCATION = "Content-Location";
-
+
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public final static String CONTENT_MD5 = "Content-MD5";
-
+
public final static String CONTENT_TYPE = "Content-Type";
public static final Text WRITABLE_CONTENT_TYPE = new Text(CONTENT_TYPE);
-
+
public final static String LAST_MODIFIED = "Last-Modified";
-
+
public final static String LOCATION = "Location";
}
diff --git a/src/java/org/apache/nutch/metadata/MetaWrapper.java b/src/java/org/apache/nutch/metadata/MetaWrapper.java
index 76db2d8e0..a43fa9dad 100644
--- a/src/java/org/apache/nutch/metadata/MetaWrapper.java
+++ b/src/java/org/apache/nutch/metadata/MetaWrapper.java
@@ -28,28 +28,29 @@ import org.apache.nutch.crawl.NutchWritable;
/**
* This is a simple decorator that adds metadata to any Writable-s that can be
* serialized by <tt>NutchWritable</tt>. This is useful when data needs to be
- * temporarily enriched during processing, but this
- * temporary metadata doesn't need to be permanently stored after the job is done.
+ * temporarily enriched during processing, but this temporary metadata doesn't
+ * need to be permanently stored after the job is done.
*
* @author Andrzej Bialecki
*/
public class MetaWrapper extends NutchWritable {
private Metadata metadata;
-
+
public MetaWrapper() {
super();
metadata = new Metadata();
}
-
+
public MetaWrapper(Writable instance, Configuration conf) {
super(instance);
metadata = new Metadata();
setConf(conf);
}
-
+
public MetaWrapper(Metadata metadata, Writable instance, Configuration conf) {
super(instance);
- if (metadata == null) metadata = new Metadata();
+ if (metadata == null)
+ metadata = new Metadata();
this.metadata = metadata;
setConf(conf);
}
@@ -60,43 +61,52 @@ public class MetaWrapper extends NutchWritable {
public Metadata getMetadata() {
return metadata;
}
-
+
/**
- * Add metadata. See {@link Metadata#add(String, String)} for more information.
- * @param name metadata name
- * @param value metadata value
+ * Add metadata. See {@link Metadata#add(String, String)} for more
+ * information.
+ *
+ * @param name
+ * metadata name
+ * @param value
+ * metadata value
*/
public void addMeta(String name, String value) {
metadata.add(name, value);
}
-
+
/**
- * Set metadata. See {@link Metadata#set(String, String)} for more information.
+ * Set metadata. See {@link Metadata#set(String, String)} for more
+ * information.
+ *
* @param name
* @param value
*/
public void setMeta(String name, String value) {
metadata.set(name, value);
}
-
+
/**
* Get metadata. See {@link Metadata#get(String)} for more information.
+ *
* @param name
* @return metadata value
*/
public String getMeta(String name) {
return metadata.get(name);
}
-
+
/**
- * Get multiple metadata. See {@link Metadata#getValues(String)} for more information.
+ * Get multiple metadata. See {@link Metadata#getValues(String)} for more
+ * information.
+ *
* @param name
* @return multiple values
*/
public String[] getMetaValues(String name) {
return metadata.getValues(name);
}
-
+
public void readFields(DataInput in) throws IOException {
super.readFields(in);
metadata = new Metadata();
diff --git a/src/java/org/apache/nutch/metadata/Metadata.java b/src/java/org/apache/nutch/metadata/Metadata.java
index 38d4dac88..f0bfcd379 100644
--- a/src/java/org/apache/nutch/metadata/Metadata.java
+++ b/src/java/org/apache/nutch/metadata/Metadata.java
@@ -30,15 +30,14 @@ import org.apache.hadoop.io.Writable;
/**
* A multi-valued metadata container.
*/
-public class Metadata implements Writable, CreativeCommons,
-DublinCore, HttpHeaders, Nutch, Feed {
+public class Metadata implements Writable, CreativeCommons, DublinCore,
+ HttpHeaders, Nutch, Feed {
/**
* A map of all metadata attributes.
*/
private Map<String, String[]> metadata = null;
-
/**
* Constructs a new, empty metadata.
*/
@@ -48,9 +47,10 @@ DublinCore, HttpHeaders, Nutch, Feed {
/**
* Returns true if named value is multivalued.
- * @param name name of metadata
- * @return true is named value is multivalued, false if single
- * value or null
+ *
+ * @param name
+ * name of metadata
+ * @return true is named value is multivalued, false if single value or null
*/
public boolean isMultiValued(final String name) {
return metadata.get(name) != null && metadata.get(name).length > 1;
@@ -58,6 +58,7 @@ DublinCore, HttpHeaders, Nutch, Feed {
/**
* Returns an array of the names contained in the metadata.
+ *
* @return Metadata names
*/
public String[] names() {
@@ -65,11 +66,11 @@ DublinCore, HttpHeaders, Nutch, Feed {
}
/**
- * Get the value associated to a metadata name.
- * If many values are assiociated to the specified name, then the first
- * one is returned.
- *
- * @param name of the metadata.
+ * Get the value associated to a metadata name. If many values are assiociated
+ * to the specified name, then the first one is returned.
+ *
+ * @param name
+ * of the metadata.
* @return the value associated to the specified metadata name.
*/
public String get(final String name) {
@@ -83,13 +84,15 @@ DublinCore, HttpHeaders, Nutch, Feed {
/**
* Get the values associated to a metadata name.
- * @param name of the metadata.
+ *
+ * @param name
+ * of the metadata.
* @return the values associated to a metadata name.
*/
public String[] getValues(final String name) {
return _getValues(name);
}
-
+
private String[] _getValues(final String name) {
String[] values = metadata.get(name);
if (values == null) {
@@ -99,12 +102,13 @@ DublinCore, HttpHeaders, Nutch, Feed {
}
/**
- * Add a metadata name/value mapping.
- * Add the specified value to the list of values associated to the
- * specified metadata name.
- *
- * @param name the metadata name.
- * @param value the metadata value.
+ * Add a metadata name/value mapping. Add the specified value to the list of
+ * values associated to the specified metadata name.
+ *
+ * @param name
+ * the metadata name.
+ * @param value
+ * the metadata value.
*/
public void add(final String name, final String value) {
String[] values = metadata.get(name);
@@ -120,31 +124,37 @@ DublinCore, HttpHeaders, Nutch, Feed {
/**
* Copy All key-value pairs from properties.
- * @param properties properties to copy from
+ *
+ * @param properties
+ * properties to copy from
*/
public void setAll(Properties properties) {
Enumeration<?> names = properties.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
- metadata.put(name, new String[]{properties.getProperty(name)});
+ metadata.put(name, new String[] { properties.getProperty(name) });
}
}
/**
- * Set metadata name/value.
- * Associate the specified value to the specified metadata name. If some
- * previous values were associated to this name, they are removed.
- *
- * @param name the metadata name.
- * @param value the metadata value.
+ * Set metadata name/value. Associate the specified value to the specified
+ * metadata name. If some previous values were associated to this name, they
+ * are removed.
+ *
+ * @param name
+ * the metadata name.
+ * @param value
+ * the metadata value.
*/
public void set(String name, String value) {
- metadata.put(name, new String[]{value});
+ metadata.put(name, new String[] { value });
}
/**
* Remove a metadata and all its associated values.
- * @param name metadata name to remove
+ *
+ * @param name
+ * metadata name to remove
*/
public void remove(String name) {
metadata.remove(name);
@@ -152,12 +162,13 @@ DublinCore, HttpHeaders, Nutch, Feed {
/**
* Returns the number of metadata names in this metadata.
+ *
* @return number of metadata names
*/
public int size() {
return metadata.size();
}
-
+
/** Remove all mappings from metadata. */
public void clear() {
metadata.clear();
@@ -165,7 +176,9 @@ DublinCore, HttpHeaders, Nutch, Feed {
public boolean equals(Object o) {
- if (o == null) { return false; }
+ if (o == null) {
+ return false;
+ }
Metadata other = null;
try {
@@ -174,7 +187,9 @@ DublinCore, HttpHeaders, Nutch, Feed {
return false;
}
- if (other.size() != size()) { return false; }
+ if (other.size() != size()) {
+ return false;
+ }
String[] names = names();
for (int i = 0; i < names.length; i++) {
@@ -198,10 +213,7 @@ DublinCore, HttpHeaders, Nutch, Feed {
for (int i = 0; i < names.length; i++) {
String[] values = _getValues(names[i]);
for (int j = 0; j < values.length; j++) {
- buf.append(names[i])
- .append("=")
- .append(values[j])
- .append(" ");
+ buf.append(names[i]).append("=").append(values[j]).append(" ");
}
}
return buf.toString();
diff --git a/src/java/org/apache/nutch/metadata/Nutch.java b/src/java/org/apache/nutch/metadata/Nutch.java
index 88e1deee0..cb9012da1 100644
--- a/src/java/org/apache/nutch/metadata/Nutch.java
+++ b/src/java/org/apache/nutch/metadata/Nutch.java
@@ -18,20 +18,17 @@ package org.apache.nutch.metadata;
import org.apache.hadoop.io.Text;
-
/**
* A collection of Nutch internal metadata constants.
- *
+ *
* @author Chris Mattmann
* @author J&eacute;r&ocirc;me Charron
*/
public interface Nutch {
-
- public static final String ORIGINAL_CHAR_ENCODING =
- "OriginalCharEncoding";
-
- public static final String CHAR_ENCODING_FOR_CONVERSION =
- "CharEncodingForConversion";
+
+ public static final String ORIGINAL_CHAR_ENCODING = "OriginalCharEncoding";
+
+ public static final String CHAR_ENCODING_FOR_CONVERSION = "CharEncodingForConversion";
public static final String SIGNATURE_KEY = "nutch.content.digest";
@@ -41,17 +38,22 @@ public interface Nutch {
public static final String GENERATE_TIME_KEY = "_ngt_";
- public static final Text WRITABLE_GENERATE_TIME_KEY = new Text(GENERATE_TIME_KEY);
+ public static final Text WRITABLE_GENERATE_TIME_KEY = new Text(
+ GENERATE_TIME_KEY);
public static final String PROTO_STATUS_KEY = "_pst_";
- public static final Text WRITABLE_PROTO_STATUS_KEY = new Text(PROTO_STATUS_KEY);
-
+ public static final Text WRITABLE_PROTO_STATUS_KEY = new Text(
+ PROTO_STATUS_KEY);
+
public static final String FETCH_TIME_KEY = "_ftk_";
-
+
public static final String FETCH_STATUS_KEY = "_fst_";
- /** Sites may request that search engines don't provide access to cached documents. */
+ /**
+ * Sites may request that search engines don't provide access to cached
+ * documents.
+ */
public static final String CACHING_FORBIDDEN_KEY = "caching.forbidden";
/** Show both original forbidden content and summaries (default). */
@@ -70,5 +72,6 @@ public interface Nutch {
/** Used by AdaptiveFetchSchedule to maintain custom fetch interval */
public static final String FIXED_INTERVAL_KEY = "fixedInterval";
- public static final Text WRITABLE_FIXED_INTERVAL_KEY = new Text(FIXED_INTERVAL_KEY);
+ public static final Text WRITABLE_FIXED_INTERVAL_KEY = new Text(
+ FIXED_INTERVAL_KEY);
}
diff --git a/src/java/org/apache/nutch/metadata/SpellCheckedMetadata.java b/src/java/org/apache/nutch/metadata/SpellCheckedMetadata.java
index 29358ed9c..164ca1d23 100644
--- a/src/java/org/apache/nutch/metadata/SpellCheckedMetadata.java
+++ b/src/java/org/apache/nutch/metadata/SpellCheckedMetadata.java
@@ -33,7 +33,7 @@ public class SpellCheckedMetadata extends Metadata {
/**
* Treshold divider.
- *
+ *
* <code>threshold = searched.length() / TRESHOLD_DIVIDER;</code>
*/
private static final int TRESHOLD_DIVIDER = 3;
@@ -52,7 +52,7 @@ public class SpellCheckedMetadata extends Metadata {
// Uses following array to fill the metanames index and the
// metanames list.
- Class<?>[] spellthese = {HttpHeaders.class};
+ Class<?>[] spellthese = { HttpHeaders.class };
for (Class<?> spellCheckedNames : spellthese) {
for (Field field : spellCheckedNames.getFields()) {
@@ -73,7 +73,7 @@ public class SpellCheckedMetadata extends Metadata {
/**
* Normalizes String.
- *
+ *
* @param str
* the string to normalize
* @return normalized String
@@ -102,7 +102,7 @@ public class SpellCheckedMetadata extends Metadata {
* </ul>
* If no matching with a well-known metadata name is found, then the original
* name is returned.
- *
+ *
* @param name
* Name to normalize
* @return normalized name
diff --git a/src/java/org/apache/nutch/net/URLFilter.java b/src/java/org/apache/nutch/net/URLFilter.java
index 41622607b..01efbcdfe 100644
--- a/src/java/org/apache/nutch/net/URLFilter.java
+++ b/src/java/org/apache/nutch/net/URLFilter.java
@@ -23,17 +23,18 @@ import org.apache.hadoop.conf.Configurable;
// Nutch imports
import org.apache.nutch.plugin.Pluggable;
-
/**
- * Interface used to limit which URLs enter Nutch.
- * Used by the injector and the db updater.
+ * Interface used to limit which URLs enter Nutch. Used by the injector and the
+ * db updater.
*/
public interface URLFilter extends Pluggable, Configurable {
/** The name of the extension point. */
public final static String X_POINT_ID = URLFilter.class.getName();
- /* Interface for a filter that transforms a URL: it can pass the
- original URL through or "delete" the URL by returning null */
+ /*
+ * Interface for a filter that transforms a URL: it can pass the original URL
+ * through or "delete" the URL by returning null
+ */
public String filter(String urlString);
}
diff --git a/src/java/org/apache/nutch/net/URLFilterChecker.java b/src/java/org/apache/nutch/net/URLFilterChecker.java
index 0c46ebd10..89a3d00a8 100644
--- a/src/java/org/apache/nutch/net/URLFilterChecker.java
+++ b/src/java/org/apache/nutch/net/URLFilterChecker.java
@@ -38,23 +38,23 @@ public class URLFilterChecker {
private Configuration conf;
public URLFilterChecker(Configuration conf) {
- this.conf = conf;
+ this.conf = conf;
}
private void checkOne(String filterName) throws Exception {
URLFilter filter = null;
- ExtensionPoint point =
- PluginRepository.get(conf).getExtensionPoint(URLFilter.X_POINT_ID);
+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(
+ URLFilter.X_POINT_ID);
if (point == null)
- throw new RuntimeException(URLFilter.X_POINT_ID+" not found.");
+ throw new RuntimeException(URLFilter.X_POINT_ID + " not found.");
Extension[] extensions = point.getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
- filter = (URLFilter)extension.getExtensionInstance();
+ filter = (URLFilter) extension.getExtensionInstance();
if (filter.getClass().getName().equals(filterName)) {
break;
} else {
@@ -63,19 +63,19 @@ public class URLFilterChecker {
}
if (filter == null)
- throw new RuntimeException("Filter "+filterName+" not found.");
+ throw new RuntimeException("Filter " + filterName + " not found.");
// jerome : should we keep this behavior?
- //if (LogFormatter.hasLoggedSevere())
- // throw new RuntimeException("Severe error encountered.");
+ // if (LogFormatter.hasLoggedSevere())
+ // throw new RuntimeException("Severe error encountered.");
- System.out.println("Checking URLFilter "+filterName);
+ System.out.println("Checking URLFilter " + filterName);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
- while((line=in.readLine())!=null) {
- String out=filter.filter(line);
- if(out!=null) {
+ while ((line = in.readLine()) != null) {
+ String out = filter.filter(line);
+ if (out != null) {
System.out.print("+");
System.out.println(out);
} else {
@@ -90,10 +90,10 @@ public class URLFilterChecker {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
- while((line=in.readLine())!=null) {
+ while ((line = in.readLine()) != null) {
URLFilters filters = new URLFilters(this.conf);
String out = filters.filter(line);
- if(out!=null) {
+ if (out != null) {
System.out.print("+");
System.out.println(out);
} else {
@@ -105,8 +105,8 @@ public class URLFilterChecker {
public static void main(String[] args) throws Exception {
- String usage = "Usage: URLFilterChecker (-filterName filterName | -allCombined) \n"
- + "Tool takes a list of URLs, one per line, passed via STDIN.\n";
+ String usage = "Usage: URLFilterChecker (-filterName filterName | -allCombined) \n"
+ + "Tool takes a list of URLs, one per line, passed via STDIN.\n";
if (args.length == 0) {
System.err.println(usage);
diff --git a/src/java/org/apache/nutch/net/URLFilters.java b/src/java/org/apache/nutch/net/URLFilters.java
index 97e6e0b79..3deccca8e 100644
--- a/src/java/org/apache/nutch/net/URLFilters.java
+++ b/src/java/org/apache/nutch/net/URLFilters.java
@@ -20,16 +20,15 @@ package org.apache.nutch.net;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.plugin.PluginRepository;
-/** Creates and caches {@link URLFilter} implementing plugins.*/
+/** Creates and caches {@link URLFilter} implementing plugins. */
public class URLFilters {
public static final String URLFILTER_ORDER = "urlfilter.order";
private URLFilter[] filters;
public URLFilters(Configuration conf) {
- this.filters = (URLFilter[]) PluginRepository.get(conf)
- .getOrderedPlugins(URLFilter.class, URLFilter.X_POINT_ID,
- URLFILTER_ORDER);
+ this.filters = (URLFilter[]) PluginRepository.get(conf).getOrderedPlugins(
+ URLFilter.class, URLFilter.X_POINT_ID, URLFILTER_ORDER);
}
/** Run all defined filters. Assume logical AND. */
diff --git a/src/java/org/apache/nutch/net/URLNormalizer.java b/src/java/org/apache/nutch/net/URLNormalizer.java
index bc24c9222..78ccb27f3 100644
--- a/src/java/org/apache/nutch/net/URLNormalizer.java
+++ b/src/java/org/apache/nutch/net/URLNormalizer.java
@@ -21,13 +21,17 @@ import java.net.MalformedURLException;
import org.apache.hadoop.conf.Configurable;
-/** Interface used to convert URLs to normal form and optionally perform substitutions */
+/**
+ * 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, String scope) throws MalformedURLException;
+ public String normalize(String urlString, String scope)
+ throws MalformedURLException;
}
diff --git a/src/java/org/apache/nutch/net/URLNormalizerChecker.java b/src/java/org/apache/nutch/net/URLNormalizerChecker.java
index 77a7b14a2..d8f1c6e33 100644
--- a/src/java/org/apache/nutch/net/URLNormalizerChecker.java
+++ b/src/java/org/apache/nutch/net/URLNormalizerChecker.java
@@ -36,23 +36,23 @@ public class URLNormalizerChecker {
private Configuration conf;
public URLNormalizerChecker(Configuration conf) {
- this.conf = conf;
+ this.conf = conf;
}
private void checkOne(String normalizerName, String scope) throws Exception {
URLNormalizer normalizer = null;
- ExtensionPoint point =
- PluginRepository.get(conf).getExtensionPoint(URLNormalizer.X_POINT_ID);
+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(
+ URLNormalizer.X_POINT_ID);
if (point == null)
- throw new RuntimeException(URLNormalizer.X_POINT_ID+" not found.");
+ throw new RuntimeException(URLNormalizer.X_POINT_ID + " not found.");
Extension[] extensions = point.getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
- normalizer = (URLNormalizer)extension.getExtensionInstance();
+ normalizer = (URLNormalizer) extension.getExtensionInstance();
if (normalizer.getClass().getName().equals(normalizerName)) {
break;
} else {
@@ -61,7 +61,8 @@ public class URLNormalizerChecker {
}
if (normalizer == null)
- throw new RuntimeException("URLNormalizer "+normalizerName+" not found.");
+ throw new RuntimeException("URLNormalizer " + normalizerName
+ + " not found.");
System.out.println("Checking URLNormalizer " + normalizerName);
@@ -79,7 +80,7 @@ public class URLNormalizerChecker {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
URLNormalizers normalizers = new URLNormalizers(conf, scope);
- while((line = in.readLine()) != null) {
+ while ((line = in.readLine()) != null) {
String out = normalizers.normalize(line, scope);
System.out.println(out);
}
@@ -88,7 +89,7 @@ public class URLNormalizerChecker {
public static void main(String[] args) throws Exception {
String usage = "Usage: URLNormalizerChecker [-normalizer <normalizerName>] [-scope <scope>]"
- + "\n\tscope can be one of: default,partition,generate_host_count,fetcher,crawldb,linkdb,inject,outlink";
+ + "\n\tscope can be one of: default,partition,generate_host_count,fetcher,crawldb,linkdb,inject,outlink";
String normalizerName = null;
String scope = URLNormalizers.SCOPE_DEFAULT;
@@ -103,7 +104,8 @@ public class URLNormalizerChecker {
}
}
- URLNormalizerChecker checker = new URLNormalizerChecker(NutchConfiguration.create());
+ URLNormalizerChecker checker = new URLNormalizerChecker(
+ NutchConfiguration.create());
if (normalizerName != null) {
checker.checkOne(normalizerName, scope);
} else {
diff --git a/src/java/org/apache/nutch/net/URLNormalizers.java b/src/java/org/apache/nutch/net/URLNormalizers.java
index 876069a11..7a343538b 100644
--- a/src/java/org/apache/nutch/net/URLNormalizers.java
+++ b/src/java/org/apache/nutch/net/URLNormalizers.java
@@ -43,47 +43,63 @@ import org.apache.nutch.util.ObjectCache;
* 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
+ * <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
- * <code>org.apache.nutch.net.urlnormalizer.pass.PassURLNormalizer</code> 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
+ * missing, default settings are used for the global scope.
+ * </p>
+ * <p>
+ * In case no normalizers are required for any given scope, a
+ * <code>org.apache.nutch.net.urlnormalizer.pass.PassURLNormalizer</code> 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>
+ * 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.
+
+ /**
+ * 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.URLPartitioner}. */
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
+ /**
+ * Scope used by {@link org.apache.nutch.fetcher.Fetcher} when processing
* redirect URLs.
*/
public static final String SCOPE_FETCHER = "fetcher";
@@ -93,16 +109,21 @@ public final class URLNormalizers {
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. */
+ /**
+ * Scope used when constructing new {@link org.apache.nutch.parse.Outlink}
+ * instances.
+ */
public static final String SCOPE_OUTLINK = "outlink";
/** Scope used when indexing URLs. */
public static final String SCOPE_INDEXER = "indexer";
- public static final Logger LOG = LoggerFactory.getLogger(URLNormalizers.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(URLNormalizers.class);
/* Empty extension list for caching purposes. */
- private final List<Extension> EMPTY_EXTENSION_LIST = Collections.<Extension>emptyList();
-
+ private final List<Extension> EMPTY_EXTENSION_LIST = Collections
+ .<Extension> emptyList();
+
private final URLNormalizer[] EMPTY_NORMALIZERS = new URLNormalizer[0];
private Configuration conf;
@@ -110,37 +131,39 @@ public final class URLNormalizers {
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);
+ URLNormalizer.X_POINT_ID);
ObjectCache objectCache = ObjectCache.get(conf);
-
+
if (this.extensionPoint == null) {
throw new RuntimeException("x point " + URLNormalizer.X_POINT_ID
- + " not found.");
+ + " not found.");
}
- normalizers = (URLNormalizer[])objectCache.getObject(URLNormalizer.X_POINT_ID + "_" + scope);
+ normalizers = (URLNormalizer[]) objectCache
+ .getObject(URLNormalizer.X_POINT_ID + "_" + scope);
if (normalizers == null) {
normalizers = getURLNormalizers(scope);
}
if (normalizers == EMPTY_NORMALIZERS) {
- normalizers = (URLNormalizer[])objectCache.getObject(URLNormalizer.X_POINT_ID + "_" + SCOPE_DEFAULT);
+ normalizers = (URLNormalizer[]) objectCache
+ .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.
+ * 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
@@ -152,12 +175,13 @@ public final class URLNormalizers {
URLNormalizer[] getURLNormalizers(String scope) {
List<Extension> extensions = getExtensions(scope);
ObjectCache objectCache = ObjectCache.get(conf);
-
+
if (extensions == EMPTY_EXTENSION_LIST) {
return EMPTY_NORMALIZERS;
}
-
- List<URLNormalizer> normalizers = new Vector<URLNormalizer>(extensions.size());
+
+ List<URLNormalizer> normalizers = new Vector<URLNormalizer>(
+ extensions.size());
Iterator<Extension> it = extensions.iterator();
while (it.hasNext()) {
@@ -175,14 +199,13 @@ public final class URLNormalizers {
} 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");
+ + "initializing url normalizer plugin "
+ + ext.getDescriptor().getPluginId()
+ + " instance in getURLNormalizers "
+ + "function: attempting to continue instantiating plugins");
}
}
- return normalizers.toArray(new URLNormalizer[normalizers
- .size()]);
+ return normalizers.toArray(new URLNormalizer[normalizers.size()]);
}
/**
@@ -197,9 +220,8 @@ public final class URLNormalizers {
@SuppressWarnings("unchecked")
private List<Extension> getExtensions(String scope) {
ObjectCache objectCache = ObjectCache.get(conf);
- List<Extension> extensions =
- (List<Extension>) objectCache.getObject(URLNormalizer.X_POINT_ID + "_x_"
- + scope);
+ List<Extension> extensions = (List<Extension>) objectCache
+ .getObject(URLNormalizer.X_POINT_ID + "_x_" + scope);
// Just compare the reference:
// if this is the empty list, we know we will find no extension.
@@ -210,11 +232,13 @@ public final class URLNormalizers {
if (extensions == null) {
extensions = findExtensions(scope);
if (extensions != null) {
- objectCache.setObject(URLNormalizer.X_POINT_ID + "_x_" + scope, extensions);
+ objectCache.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.
- objectCache.setObject(URLNormalizer.X_POINT_ID + "_x_" + scope, EMPTY_EXTENSION_LIST);
+ objectCache.setObject(URLNormalizer.X_POINT_ID + "_x_" + scope,
+ EMPTY_EXTENSION_LIST);
extensions = EMPTY_EXTENSION_LIST;
}
}
@@ -234,7 +258,8 @@ public final class URLNormalizers {
String[] orders = null;
String orderlist = conf.get("urlnormalizer.order." + scope);
- if (orderlist == null) orderlist = conf.get("urlnormalizer.order");
+ if (orderlist == null)
+ orderlist = conf.get("urlnormalizer.order");
if (orderlist != null && !orderlist.trim().equals("")) {
orders = orderlist.trim().split("\\s+");
}
@@ -272,13 +297,17 @@ public final class URLNormalizers {
/**
* Normalize
- * @param urlString The URL string to normalize.
- * @param scope The given scope.
+ *
+ * @param urlString
+ * The URL string to normalize.
+ * @param scope
+ * The given scope.
* @return A normalized String, using the given <code>scope</code>
- * @throws MalformedURLException If the given URL string is malformed.
+ * @throws MalformedURLException
+ * If the given URL string is malformed.
*/
public String normalize(String urlString, String scope)
- throws MalformedURLException {
+ throws MalformedURLException {
// optionally loop several times, and break if no further changes
String initialString = urlString;
for (int k = 0; k < loopCount; k++) {
@@ -287,7 +316,8 @@ public final class URLNormalizers {
return null;
urlString = this.normalizers[i].normalize(urlString, scope);
}
- if (initialString.equals(urlString)) break;
+ if (initialString.equals(urlString))
+ break;
initialString = urlString;
}
return urlString;
diff --git a/src/java/org/apache/nutch/net/package-info.java b/src/java/org/apache/nutch/net/package-info.java
index 4a2b35375..19e0111e8 100644
--- a/src/java/org/apache/nutch/net/package-info.java
+++ b/src/java/org/apache/nutch/net/package-info.java
@@ -20,3 +20,4 @@
* and {@link org.apache.nutch.net.URLNormalizer normalizers}.
*/
package org.apache.nutch.net;
+
diff --git a/src/java/org/apache/nutch/net/protocols/HttpDateFormat.java b/src/java/org/apache/nutch/net/protocols/HttpDateFormat.java
index 21662f095..5f4115b6d 100644
--- a/src/java/org/apache/nutch/net/protocols/HttpDateFormat.java
+++ b/src/java/org/apache/nutch/net/protocols/HttpDateFormat.java
@@ -26,15 +26,15 @@ import java.text.ParseException;
/**
* class to handle HTTP dates.
- *
+ *
* Modified from FastHttpDateFormat.java in jakarta-tomcat.
- *
+ *
* @author John Xing
*/
public class HttpDateFormat {
- protected static SimpleDateFormat format =
- new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
+ protected static SimpleDateFormat format = new SimpleDateFormat(
+ "EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
/**
* HTTP date uses TimeZone GMT
@@ -43,29 +43,29 @@ public class HttpDateFormat {
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
- //HttpDate (long t) {
- //}
-
- //HttpDate (String s) {
- //}
-
-// /**
-// * Get the current date in HTTP format.
-// */
-// public static String getCurrentDate() {
-//
-// long now = System.currentTimeMillis();
-// if ((now - currentDateGenerated) > 1000) {
-// synchronized (format) {
-// if ((now - currentDateGenerated) > 1000) {
-// currentDateGenerated = now;
-// currentDate = format.format(new Date(now));
-// }
-// }
-// }
-// return currentDate;
-//
-// }
+ // HttpDate (long t) {
+ // }
+
+ // HttpDate (String s) {
+ // }
+
+ // /**
+ // * Get the current date in HTTP format.
+ // */
+ // public static String getCurrentDate() {
+ //
+ // long now = System.currentTimeMillis();
+ // if ((now - currentDateGenerated) > 1000) {
+ // synchronized (format) {
+ // if ((now - currentDateGenerated) > 1000) {
+ // currentDateGenerated = now;
+ // currentDate = format.format(new Date(now));
+ // }
+ // }
+ // }
+ // return currentDate;
+ //
+ // }
/**
* Get the HTTP format of the specified date.
diff --git a/src/java/org/apache/nutch/net/protocols/ProtocolException.java b/src/java/org/apache/nutch/net/protocols/ProtocolException.java
index 089820f90..0ae3776f3 100644
--- a/src/java/org/apache/nutch/net/protocols/ProtocolException.java
+++ b/src/java/org/apache/nutch/net/protocols/ProtocolException.java
@@ -21,13 +21,13 @@ import java.io.Serializable;
/**
* Base exception for all protocol handlers
+ *
* @deprecated Use {@link org.apache.nutch.protocol.ProtocolException} instead.
*/
@Deprecated
@SuppressWarnings("serial")
public class ProtocolException extends Exception implements Serializable {
-
public ProtocolException() {
super();
}
diff --git a/src/java/org/apache/nutch/net/protocols/Response.java b/src/java/org/apache/nutch/net/protocols/Response.java
index 4bca7881d..efff14b4c 100644
--- a/src/java/org/apache/nutch/net/protocols/Response.java
+++ b/src/java/org/apache/nutch/net/protocols/Response.java
@@ -23,12 +23,11 @@ import java.net.URL;
import org.apache.nutch.metadata.HttpHeaders;
import org.apache.nutch.metadata.Metadata;
-
/**
- * A response interface. Makes all protocols model HTTP.
+ * A response interface. Makes all protocols model HTTP.
*/
public interface Response extends HttpHeaders {
-
+
/** Returns the URL used to retrieve this response. */
public URL getUrl();
@@ -40,7 +39,7 @@ public interface Response extends HttpHeaders {
/** Returns all the headers. */
public Metadata getHeaders();
-
+
/** Returns the full content of the response. */
public byte[] getContent();
diff --git a/src/java/org/apache/nutch/net/protocols/package-info.java b/src/java/org/apache/nutch/net/protocols/package-info.java
index 0ed5cb25c..8823f5b2b 100644
--- a/src/java/org/apache/nutch/net/protocols/package-info.java
+++ b/src/java/org/apache/nutch/net/protocols/package-info.java
@@ -20,3 +20,4 @@
* interface, sea also {@link org.apache.nutch.protocol}.
*/
package org.apache.nutch.net.protocols;
+
diff --git a/src/java/org/apache/nutch/parse/HTMLMetaTags.java b/src/java/org/apache/nutch/parse/HTMLMetaTags.java
index a5b8a77fc..c36c036f0 100644
--- a/src/java/org/apache/nutch/parse/HTMLMetaTags.java
+++ b/src/java/org/apache/nutch/parse/HTMLMetaTags.java
@@ -24,8 +24,8 @@ import java.util.Properties;
import org.apache.nutch.metadata.Metadata;
/**
- * This class holds the information about HTML "meta" tags extracted from
- * a page. Some special tags have convenience methods for easy checking.
+ * This class holds the information about HTML "meta" tags extracted from a
+ * page. Some special tags have convenience methods for easy checking.
*/
public class HTMLMetaTags {
private boolean noIndex = false;
@@ -45,7 +45,7 @@ public class HTMLMetaTags {
private Metadata generalTags = new Metadata();
private Properties httpEquivTags = new Properties();
-
+
/**
* Sets all boolean values to <code>false</code>. Clears all other tags.
*/
@@ -156,8 +156,8 @@ public class HTMLMetaTags {
}
/**
- * A convenience method. Returns the current value of <code>refreshTime</code>.
- * The value may be invalid if {@link #getRefresh()}returns
+ * A convenience method. Returns the current value of <code>refreshTime</code>
+ * . The value may be invalid if {@link #getRefresh()}returns
* <code>false</code>.
*/
public int getRefreshTime() {
@@ -179,16 +179,12 @@ public class HTMLMetaTags {
public Properties getHttpEquivTags() {
return httpEquivTags;
}
-
+
public String toString() {
StringBuffer sb = new StringBuffer();
- sb.append("base=" + baseHref
- + ", noCache=" + noCache
- + ", noFollow=" + noFollow
- + ", noIndex=" + noIndex
- + ", refresh=" + refresh
- + ", refreshHref=" + refreshHref + "\n"
- );
+ sb.append("base=" + baseHref + ", noCache=" + noCache + ", noFollow="
+ + noFollow + ", noIndex=" + noIndex + ", refresh=" + refresh
+ + ", refreshHref=" + refreshHref + "\n");
sb.append(" * general tags:\n");
String[] names = generalTags.names();
for (String name : names) {
@@ -199,7 +195,7 @@ public class HTMLMetaTags {
Iterator<Object> it = httpEquivTags.keySet().iterator();
it = httpEquivTags.keySet().iterator();
while (it.hasNext()) {
- String key = (String)it.next();
+ String key = (String) it.next();
sb.append(" - " + key + "\t=\t" + httpEquivTags.get(key) + "\n");
}
return sb.toString();
diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilter.java b/src/java/org/apache/nutch/parse/HtmlParseFilter.java
index 18e81f41d..55b51aca6 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilter.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilter.java
@@ -27,16 +27,19 @@ import org.apache.hadoop.conf.Configurable;
import org.apache.nutch.plugin.Pluggable;
import org.apache.nutch.protocol.Content;
-
-/** Extension point for DOM-based HTML parsers. Permits one to add additional
- * metadata to HTML parses. All plugins found which implement this extension
+/**
+ * Extension point for DOM-based HTML parsers. Permits one to add additional
+ * metadata to HTML parses. All plugins found which implement this extension
* point are run sequentially on the parse.
*/
public interface HtmlParseFilter extends Pluggable, Configurable {
/** The name of the extension point. */
final static String X_POINT_ID = HtmlParseFilter.class.getName();
- /** Adds metadata or otherwise modifies a parse of HTML content, given
- * the DOM tree of a page. */
- ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc);
+ /**
+ * Adds metadata or otherwise modifies a parse of HTML content, given the DOM
+ * tree of a page.
+ */
+ ParseResult filter(Content content, ParseResult parseResult,
+ HTMLMetaTags metaTags, DocumentFragment doc);
}
diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilters.java b/src/java/org/apache/nutch/parse/HtmlParseFilters.java
index ce4581033..9dd9aadde 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilters.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilters.java
@@ -23,11 +23,11 @@ import org.apache.hadoop.conf.Configuration;
import org.w3c.dom.DocumentFragment;
-/** Creates and caches {@link HtmlParseFilter} implementing plugins.*/
+/** Creates and caches {@link HtmlParseFilter} implementing plugins. */
public class HtmlParseFilters {
private HtmlParseFilter[] htmlParseFilters;
-
+
public static final String HTMLPARSEFILTER_ORDER = "htmlparsefilter.order";
public HtmlParseFilters(Configuration conf) {
@@ -37,13 +37,14 @@ public class HtmlParseFilters {
}
/** Run all defined filters. */
- public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) {
+ public ParseResult filter(Content content, ParseResult parseResult,
+ HTMLMetaTags metaTags, DocumentFragment doc) {
// loop on each filter
- for (int i = 0 ; i < this.htmlParseFilters.length; i++) {
+ for (int i = 0; i < this.htmlParseFilters.length; i++) {
// call filter interface
- parseResult =
- htmlParseFilters[i].filter(content, parseResult, metaTags, doc);
+ parseResult = htmlParseFilters[i].filter(content, parseResult, metaTags,
+ doc);
// any failure on parse obj, return
if (!parseResult.isSuccess()) {
diff --git a/src/java/org/apache/nutch/parse/Outlink.java b/src/java/org/apache/nutch/parse/Outlink.java
index ecf125d02..f60c288c2 100644
--- a/src/java/org/apache/nutch/parse/Outlink.java
+++ b/src/java/org/apache/nutch/parse/Outlink.java
@@ -30,103 +30,102 @@ import org.apache.hadoop.io.Writable;
/* An outgoing link from a page. */
public class Outlink implements Writable {
- private String toUrl;
- private String anchor;
- private MapWritable md;
-
- public Outlink() {
- }
-
- public Outlink(String toUrl, String anchor) throws MalformedURLException {
- this.toUrl = toUrl;
- if (anchor == null)
- anchor = "";
- this.anchor = anchor;
- md = null;
- }
-
- public void readFields(DataInput in) throws IOException {
- toUrl = Text.readString(in);
- anchor = Text.readString(in);
- boolean hasMD = in.readBoolean();
- if (hasMD) {
- md = new org.apache.hadoop.io.MapWritable();
- md.readFields(in);
- } else
- md = null;
- }
-
- /** Skips over one Outlink in the input. */
- public static void skip(DataInput in) throws IOException {
- Text.skip(in); // skip toUrl
- Text.skip(in); // skip anchor
- boolean hasMD = in.readBoolean();
- if (hasMD) {
- MapWritable metadata = new org.apache.hadoop.io.MapWritable();
- metadata.readFields(in);
- ;
- }
- }
-
- public void write(DataOutput out) throws IOException {
- Text.writeString(out, toUrl);
- Text.writeString(out, anchor);
- if (md != null && md.size() > 0) {
- out.writeBoolean(true);
- md.write(out);
- } else {
- out.writeBoolean(false);
- }
+ private String toUrl;
+ private String anchor;
+ private MapWritable md;
+
+ public Outlink() {
+ }
+
+ public Outlink(String toUrl, String anchor) throws MalformedURLException {
+ this.toUrl = toUrl;
+ if (anchor == null)
+ anchor = "";
+ this.anchor = anchor;
+ md = null;
+ }
+
+ public void readFields(DataInput in) throws IOException {
+ toUrl = Text.readString(in);
+ anchor = Text.readString(in);
+ boolean hasMD = in.readBoolean();
+ if (hasMD) {
+ md = new org.apache.hadoop.io.MapWritable();
+ md.readFields(in);
+ } else
+ md = null;
+ }
+
+ /** Skips over one Outlink in the input. */
+ public static void skip(DataInput in) throws IOException {
+ Text.skip(in); // skip toUrl
+ Text.skip(in); // skip anchor
+ boolean hasMD = in.readBoolean();
+ if (hasMD) {
+ MapWritable metadata = new org.apache.hadoop.io.MapWritable();
+ metadata.readFields(in);
+ ;
}
-
- public static Outlink read(DataInput in) throws IOException {
- Outlink outlink = new Outlink();
- outlink.readFields(in);
- return outlink;
- }
-
- public String getToUrl() {
- return toUrl;
+ }
+
+ public void write(DataOutput out) throws IOException {
+ Text.writeString(out, toUrl);
+ Text.writeString(out, anchor);
+ if (md != null && md.size() > 0) {
+ out.writeBoolean(true);
+ md.write(out);
+ } else {
+ out.writeBoolean(false);
}
-
- public void setUrl(String toUrl) {
- this.toUrl = toUrl;
- }
-
- public String getAnchor() {
- return anchor;
- }
-
- public MapWritable getMetadata() {
- return md;
- }
-
- public void setMetadata(MapWritable md) {
- this.md = md;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof Outlink))
- return false;
- Outlink other = (Outlink) o;
- return this.toUrl.equals(other.toUrl)
- && this.anchor.equals(other.anchor);
- }
-
- public String toString() {
- StringBuffer repr = new StringBuffer("toUrl: ");
- repr.append(toUrl);
- repr.append(" anchor: ");
- repr.append(anchor);
- if (md != null && !md.isEmpty()) {
- for (Entry<Writable, Writable> e : md.entrySet()) {
- repr.append(" ");
- repr.append(e.getKey());
- repr.append(": ");
- repr.append(e.getValue());
- }
- }
- return repr.toString();
+ }
+
+ public static Outlink read(DataInput in) throws IOException {
+ Outlink outlink = new Outlink();
+ outlink.readFields(in);
+ return outlink;
+ }
+
+ public String getToUrl() {
+ return toUrl;
+ }
+
+ public void setUrl(String toUrl) {
+ this.toUrl = toUrl;
+ }
+
+ public String getAnchor() {
+ return anchor;
+ }
+
+ public MapWritable getMetadata() {
+ return md;
+ }
+
+ public void setMetadata(MapWritable md) {
+ this.md = md;
+ }
+
+ public boolean equals(Object o) {
+ if (!(o instanceof Outlink))
+ return false;
+ Outlink other = (Outlink) o;
+ return this.toUrl.equals(other.toUrl) && this.anchor.equals(other.anchor);
+ }
+
+ public String toString() {
+ StringBuffer repr = new StringBuffer("toUrl: ");
+ repr.append(toUrl);
+ repr.append(" anchor: ");
+ repr.append(anchor);
+ if (md != null && !md.isEmpty()) {
+ for (Entry<Writable, Writable> e : md.entrySet()) {
+ repr.append(" ");
+ repr.append(e.getKey());
+ repr.append(": ");
+ repr.append(e.getValue());
+ }
}
+ return repr.toString();
+ }
}
diff --git a/src/java/org/apache/nutch/parse/OutlinkExtractor.java b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
index dd14bcb59..2181683e4 100644
--- a/src/java/org/apache/nutch/parse/OutlinkExtractor.java
+++ b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
@@ -34,8 +34,8 @@ import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
/**
- * Extractor to extract {@link org.apache.nutch.parse.Outlink}s
- * / URLs from plain text using Regular Expressions.
+ * Extractor to extract {@link org.apache.nutch.parse.Outlink}s / URLs from
+ * plain text using Regular Expressions.
*
* @see <a
* href="http://wiki.java.net/bin/view/Javapedia/RegularExpressions">Comparison
@@ -48,23 +48,26 @@ import org.apache.oro.text.regex.Perl5Matcher;
* @since 0.7
*/
public class OutlinkExtractor {
- private static final Logger LOG = LoggerFactory.getLogger(OutlinkExtractor.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(OutlinkExtractor.class);
/**
* Regex pattern to get URLs within a plain text.
*
* @see <a
* href="http://www.truerwords.net/articles/ut/urlactivation.html">http://www.truerwords.net/articles/ut/urlactivation.html
+
* </a>
*/
- private static final String URL_PATTERN =
- "([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)";
+ private static final String URL_PATTERN = "([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)";
/**
- * Extracts <code>Outlink</code> from given plain text.
- * Applying this method to non-plain-text can result in extremely lengthy
- * runtimes for parasitic cases (postscript is a known example).
- * @param plainText the plain text from wich URLs should be extracted.
+ * Extracts <code>Outlink</code> from given plain text. Applying this method
+ * to non-plain-text can result in extremely lengthy runtimes for parasitic
+ * cases (postscript is a known example).
+ *
+ * @param plainText
+ * the plain text from wich URLs should be extracted.
*
* @return Array of <code>Outlink</code>s within found in plainText
*/
@@ -73,15 +76,18 @@ public class OutlinkExtractor {
}
/**
- * Extracts <code>Outlink</code> from given plain text and adds anchor
- * to the extracted <code>Outlink</code>s
+ * Extracts <code>Outlink</code> from given plain text and adds anchor to the
+ * extracted <code>Outlink</code>s
*
- * @param plainText the plain text from wich URLs should be extracted.
- * @param anchor the anchor of the url
+ * @param plainText
+ * the plain text from wich URLs should be extracted.
+ * @param anchor
+ * the anchor of the url
*
* @return Array of <code>Outlink</code>s within found in plainText
*/
- public static Outlink[] getOutlinks(final String plainText, String anchor, Configuration conf) {
+ public static Outlink[] getOutlinks(final String plainText, String anchor,
+ Configuration conf) {
long start = System.currentTimeMillis();
final List<Outlink> outlinks = new ArrayList<Outlink>();
@@ -97,11 +103,11 @@ public class OutlinkExtractor {
MatchResult result;
String url;
- //loop the matches
+ // loop the matches
while (matcher.contains(input, pattern)) {
// if this is taking too long, stop matching
- // (SHOULD really check cpu time used so that heavily loaded systems
- // do not unnecessarily hit this limit.)
+ // (SHOULD really check cpu time used so that heavily loaded systems
+ // do not unnecessarily hit this limit.)
if (System.currentTimeMillis() - start >= 60000L) {
if (LOG.isWarnEnabled()) {
LOG.warn("Time limit exceeded for getOutLinks");
@@ -117,13 +123,16 @@ public class OutlinkExtractor {
}
}
} catch (Exception ex) {
- // if the matcher fails (perhaps a malformed URL) we just log it and move on
- if (LOG.isErrorEnabled()) { LOG.error("getOutlinks", ex); }
+ // if the matcher fails (perhaps a malformed URL) we just log it and move
+ // on
+ if (LOG.isErrorEnabled()) {
+ LOG.error("getOutlinks", ex);
+ }
}
final Outlink[] retval;
- //create array of the Outlinks
+ // create array of the Outlinks
if (outlinks != null && outlinks.size() > 0) {
retval = outlinks.toArray(new Outlink[0]);
} else {
@@ -132,7 +141,6 @@ public class OutlinkExtractor {
return retval;
}
-
/**
* Extracts outlinks from a plain text. <br />
@@ -162,7 +170,7 @@ public class OutlinkExtractor {
// url = re.getParen(0);
//
// if (LOG.isTraceEnabled()) {
- // LOG.trace("Extracted url: " + url);
+ // LOG.trace("Extracted url: " + url);
// }
//
// try {
@@ -192,9 +200,8 @@ public class OutlinkExtractor {
}
/**
- * Extracts outlinks from a plain text.
- * </p>
- * This Method takes the JDK5 Regexp API.
+ * Extracts outlinks from a plain text. </p> This Method takes the JDK5 Regexp
+ * API.
*
* @param plainText
*
@@ -243,5 +250,5 @@ public class OutlinkExtractor {
//
// return retval;
}
-
+
}
diff --git a/src/java/org/apache/nutch/parse/Parse.java b/src/java/org/apache/nutch/parse/Parse.java
index 9096bf1a8..9a3344501 100644
--- a/src/java/org/apache/nutch/parse/Parse.java
+++ b/src/java/org/apache/nutch/parse/Parse.java
@@ -17,18 +17,22 @@
package org.apache.nutch.parse;
-/** The result of parsing a page's raw content.
+/**
+ * The result of parsing a page's raw content.
+ *
* @see Parser#getParse(Content)
*/
public interface Parse {
-
- /** The textual content of the page. This is indexed, searched, and used when
- * generating snippets.*/
+
+ /**
+ * The textual content of the page. This is indexed, searched, and used when
+ * generating snippets.
+ */
String getText();
/** Other data extracted from the page. */
ParseData getData();
-
+
/** Indicates if the parse is coming from a url or a sub-url */
boolean isCanonical();
}
diff --git a/src/java/org/apache/nutch/parse/ParseCallable.java b/src/java/org/apache/nutch/parse/ParseCallable.java
index 23e094853..12cae8a65 100644
--- a/src/java/org/apache/nutch/parse/ParseCallable.java
+++ b/src/java/org/apache/nutch/parse/ParseCallable.java
@@ -24,7 +24,7 @@ import org.apache.nutch.protocol.Content;
class ParseCallable implements Callable<ParseResult> {
private Parser p;
private Content content;
-
+
public ParseCallable(Parser p, Content content) {
this.p = p;
this.content = content;
@@ -33,5 +33,5 @@ class ParseCallable implements Callable<ParseResult> {
@Override
public ParseResult call() throws Exception {
return p.getParse(content);
- }
+ }
}
\ No newline at end of file
diff --git a/src/java/org/apache/nutch/parse/ParseData.java b/src/java/org/apache/nutch/parse/ParseData.java
index 95497fe11..818926994 100644
--- a/src/java/org/apache/nutch/parse/ParseData.java
+++ b/src/java/org/apache/nutch/parse/ParseData.java
@@ -30,8 +30,9 @@ import org.apache.hadoop.fs.FileSystem;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.util.NutchConfiguration;
-
-/** Data extracted from a page's content.
+/**
+ * Data extracted from a page's content.
+ *
* @see Parse#getData()
*/
public final class ParseData extends VersionedWritable {
@@ -45,19 +46,19 @@ public final class ParseData extends VersionedWritable {
private Metadata parseMeta;
private ParseStatus status;
private byte version = VERSION;
-
+
public ParseData() {
contentMeta = new Metadata();
parseMeta = new Metadata();
}
public ParseData(ParseStatus status, String title, Outlink[] outlinks,
- Metadata contentMeta) {
+ Metadata contentMeta) {
this(status, title, outlinks, contentMeta, new Metadata());
}
-
+
public ParseData(ParseStatus status, String title, Outlink[] outlinks,
- Metadata contentMeta, Metadata parseMeta) {
+ Metadata contentMeta, Metadata parseMeta) {
this.status = status;
this.title = title;
this.outlinks = outlinks;
@@ -70,25 +71,34 @@ public final class ParseData extends VersionedWritable {
//
/** The status of parsing the page. */
- public ParseStatus getStatus() { return status; }
-
+ public ParseStatus getStatus() {
+ return status;
+ }
+
/** The title of the page. */
- public String getTitle() { return title; }
+ public String getTitle() {
+ return title;
+ }
/** The outlinks of the page. */
- public Outlink[] getOutlinks() { return outlinks; }
+ public Outlink[] getOutlinks() {
+ return outlinks;
+ }
/** The original Metadata retrieved from content */
- public Metadata getContentMeta() { return contentMeta; }
+ public Metadata getContentMeta() {
+ return contentMeta;
+ }
/**
- * Other content properties.
- * This is the place to find format-specific properties.
- * Different parser implementations for different content types will populate
- * this differently.
+ * Other content properties. This is the place to find format-specific
+ * properties. Different parser implementations for different content types
+ * will populate this differently.
*/
- public Metadata getParseMeta() { return parseMeta; }
-
+ public Metadata getParseMeta() {
+ return parseMeta;
+ }
+
public void setParseMeta(Metadata parseMeta) {
this.parseMeta = parseMeta;
}
@@ -96,11 +106,12 @@ public final class ParseData extends VersionedWritable {
public void setOutlinks(Outlink[] outlinks) {
this.outlinks = outlinks;
}
-
+
/**
- * Get a metadata single value.
- * This method first looks for the metadata value in the parse metadata. If no
- * value is found it the looks for the metadata in the content metadata.
+ * Get a metadata single value. This method first looks for the metadata value
+ * in the parse metadata. If no value is found it the looks for the metadata
+ * in the content metadata.
+ *
* @see #getContentMeta()
* @see #getParseMeta()
*/
@@ -111,12 +122,14 @@ public final class ParseData extends VersionedWritable {
}
return value;
}
-
+
//
// Writable methods
//
- public byte getVersion() { return version; }
+ public byte getVersion() {
+ return version;
+ }
public final void readFields(DataInput in) throws IOException {
@@ -125,16 +138,16 @@ public final class ParseData extends VersionedWritable {
if (version != VERSION)
throw new VersionMismatchException(VERSION, version);
status = ParseStatus.read(in);
- title = Text.readString(in); // read title
+ title = Text.readString(in); // read title
- int numOutlinks = in.readInt();
+ int numOutlinks = in.readInt();
outlinks = new Outlink[numOutlinks];
for (int i = 0; i < numOutlinks; i++) {
outlinks[i] = Outlink.read(in);
}
-
+
if (version < 3) {
- int propertyCount = in.readInt(); // read metadata
+ int propertyCount = in.readInt(); // read metadata
contentMeta.clear();
for (int i = 0; i < propertyCount; i++) {
contentMeta.add(Text.readString(in), Text.readString(in));
@@ -150,15 +163,15 @@ public final class ParseData extends VersionedWritable {
}
public final void write(DataOutput out) throws IOException {
- out.writeByte(VERSION); // write version
- status.write(out); // write status
- Text.writeString(out, title); // write title
+ out.writeByte(VERSION); // write version
+ status.write(out); // write status
+ Text.writeString(out, title); // write title
- out.writeInt(outlinks.length); // write outlinks
+ out.writeInt(outlinks.length); // write outlinks
for (int i = 0; i < outlinks.length; i++) {
outlinks[i].write(out);
}
- contentMeta.write(out); // write content metadata
+ contentMeta.write(out); // write content metadata
parseMeta.write(out);
}
@@ -175,38 +188,36 @@ public final class ParseData extends VersionedWritable {
public boolean equals(Object o) {
if (!(o instanceof ParseData))
return false;
- ParseData other = (ParseData)o;
- return
- this.status.equals(other.status) &&
- this.title.equals(other.title) &&
- Arrays.equals(this.outlinks, other.outlinks) &&
- this.contentMeta.equals(other.contentMeta) &&
- this.parseMeta.equals(other.parseMeta);
+ ParseData other = (ParseData) o;
+ return this.status.equals(other.status) && this.title.equals(other.title)
+ && Arrays.equals(this.outlinks, other.outlinks)
+ && this.contentMeta.equals(other.contentMeta)
+ && this.parseMeta.equals(other.parseMeta);
}
public String toString() {
StringBuffer buffer = new StringBuffer();
- buffer.append("Version: " + version + "\n" );
- buffer.append("Status: " + status + "\n" );
- buffer.append("Title: " + title + "\n" );
+ buffer.append("Version: " + version + "\n");
+ buffer.append("Status: " + status + "\n");
+ buffer.append("Title: " + title + "\n");
if (outlinks != null) {
- buffer.append("Outlinks: " + outlinks.length + "\n" );
+ buffer.append("Outlinks: " + outlinks.length + "\n");
for (int i = 0; i < outlinks.length; i++) {
buffer.append(" outlink: " + outlinks[i] + "\n");
}
}
- buffer.append("Content Metadata: " + contentMeta + "\n" );
- buffer.append("Parse Metadata: " + parseMeta + "\n" );
+ buffer.append("Content Metadata: " + contentMeta + "\n");
+ buffer.append("Parse Metadata: " + parseMeta + "\n");
return buffer.toString();
}
public static void main(String argv[]) throws Exception {
String usage = "ParseData (-local | -dfs <namenode:port>) recno segment";
-
+
if (argv.length < 3) {
System.out.println("usage:" + usage);
return;
@@ -214,13 +225,12 @@ public final class ParseData extends VersionedWritable {
Options opts = new Options();
Configuration conf = NutchConfiguration.create();
-
- GenericOptionsParser parser =
- new GenericOptionsParser(conf, opts, argv);
-
+
+ GenericOptionsParser parser = new GenericOptionsParser(conf, opts, argv);
+
String[] remainingArgs = parser.getRemainingArgs();
FileSystem fs = FileSystem.get(conf);
-
+
try {
int recno = Integer.parseInt(remainingArgs[0]);
String segment = remainingArgs[1];
diff --git a/src/java/org/apache/nutch/parse/ParseImpl.java b/src/java/org/apache/nutch/parse/ParseImpl.java
index 4c9847508..dc72769eb 100644
--- a/src/java/org/apache/nutch/parse/ParseImpl.java
+++ b/src/java/org/apache/nutch/parse/ParseImpl.java
@@ -20,8 +20,9 @@ package org.apache.nutch.parse;
import java.io.*;
import org.apache.hadoop.io.*;
-
-/** The result of parsing a page's raw content.
+/**
+ * The result of parsing a page's raw content.
+ *
* @see Parser#getParse(Content)
*/
public class ParseImpl implements Parse, Writable {
@@ -29,7 +30,8 @@ public class ParseImpl implements Parse, Writable {
private ParseData data;
private boolean isCanonical;
- public ParseImpl() {}
+ public ParseImpl() {
+ }
public ParseImpl(Parse parse) {
this(new ParseText(parse.getText()), parse.getData(), true);
@@ -38,7 +40,7 @@ public class ParseImpl implements Parse, Writable {
public ParseImpl(String text, ParseData data) {
this(new ParseText(text), data, true);
}
-
+
public ParseImpl(ParseText text, ParseData data) {
this(text, data, true);
}
@@ -49,12 +51,18 @@ public class ParseImpl implements Parse, Writable {
this.isCanonical = isCanonical;
}
- public String getText() { return text.getText(); }
+ public String getText() {
+ return text.getText();
+ }
+
+ public ParseData getData() {
+ return data;
+ }
- public ParseData getData() { return data; }
+ public boolean isCanonical() {
+ return isCanonical;
+ }
- public boolean isCanonical() { return isCanonical; }
-
public final void write(DataOutput out) throws IOException {
out.writeBoolean(isCanonical);
text.write(out);
diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
index 6b25ac7c5..3c8f4c53f 100644
--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java
+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
@@ -47,7 +47,8 @@ import org.apache.hadoop.util.Progressable;
/* Parse content in a segment. */
public class ParseOutputFormat implements OutputFormat<Text, Parse> {
- private static final Logger LOG = LoggerFactory.getLogger(ParseOutputFormat.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(ParseOutputFormat.class);
private URLFilters filters;
private URLNormalizers normalizers;
@@ -56,16 +57,16 @@ public class ParseOutputFormat implements OutputFormat<Text, Parse> {
private static class SimpleEntry implements Entry<Text, CrawlDatum> {
private Text key;
private CrawlDatum value;
-
+
public SimpleEntry(Text key, CrawlDatum value) {
this.key = key;
this.value = value;
}
-
+
public Text getKey() {
return key;
}
-
+
public CrawlDatum getValue() {
return value;
}
@@ -77,93 +78,92 @@ public class ParseOutputFormat implements OutputFormat<Text, Parse> {
}
public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException {
- Path out = FileOutputFormat.getOutputPath(job);
- if ((out == null) && (job.getNumReduceTasks() != 0)) {
- throw new InvalidJobConfException(
- "Output directory not set in JobConf.");
- }
- if (fs == null) {
- fs = out.getFileSystem(job);
- }
- if (fs.exists(new Path(out, CrawlDatum.PARSE_DIR_NAME)))
- throw new IOException("Segment already parsed!");
+ Path out = FileOutputFormat.getOutputPath(job);
+ if ((out == null) && (job.getNumReduceTasks() != 0)) {
+ throw new InvalidJobConfException("Output directory not set in JobConf.");
+ }
+ if (fs == null) {
+ fs = out.getFileSystem(job);
+ }
+ if (fs.exists(new Path(out, CrawlDatum.PARSE_DIR_NAME)))
+ throw new IOException("Segment already parsed!");
}
public RecordWriter<Text, Parse> getRecordWriter(FileSystem fs, JobConf job,
- String name, Progressable progress) throws IOException {
+ String name, Progressable progress) throws IOException {
- if(job.getBoolean("parse.filter.urls", true)) {
+ if (job.getBoolean("parse.filter.urls", true)) {
filters = new URLFilters(job);
}
- if(job.getBoolean("parse.normalize.urls", true)) {
+ if (job.getBoolean("parse.normalize.urls", true)) {
normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_OUTLINK);
}
this.scfilters = new ScoringFilters(job);
final int interval = job.getInt("db.fetch.interval.default", 2592000);
- final boolean ignoreExternalLinks = job.getBoolean("db.ignore.external.links", false);
+ final boolean ignoreExternalLinks = job.getBoolean(
+ "db.ignore.external.links", false);
int maxOutlinksPerPage = job.getInt("db.max.outlinks.per.page", 100);
final boolean isParsing = job.getBoolean("fetcher.parse", true);
final int maxOutlinks = (maxOutlinksPerPage < 0) ? Integer.MAX_VALUE
- : maxOutlinksPerPage;
- final CompressionType compType = SequenceFileOutputFormat.getOutputCompressionType(job);
+ : maxOutlinksPerPage;
+ final CompressionType compType = SequenceFileOutputFormat
+ .getOutputCompressionType(job);
Path out = FileOutputFormat.getOutputPath(job);
-
+
Path text = new Path(new Path(out, ParseText.DIR_NAME), name);
Path data = new Path(new Path(out, ParseData.DIR_NAME), name);
Path crawl = new Path(new Path(out, CrawlDatum.PARSE_DIR_NAME), name);
-
- final String[] parseMDtoCrawlDB = job.get("db.parsemeta.to.crawldb","").split(" *, *");
-
- final MapFile.Writer textOut =
- new MapFile.Writer(job, fs, text.toString(), Text.class, ParseText.class,
- CompressionType.RECORD, progress);
-
- final MapFile.Writer dataOut =
- new MapFile.Writer(job, fs, data.toString(), Text.class, ParseData.class,
- compType, progress);
-
- final SequenceFile.Writer crawlOut =
- SequenceFile.createWriter(fs, job, crawl, Text.class, CrawlDatum.class,
- compType, progress);
-
+
+ final String[] parseMDtoCrawlDB = job.get("db.parsemeta.to.crawldb", "")
+ .split(" *, *");
+
+ final MapFile.Writer textOut = new MapFile.Writer(job, fs, text.toString(),
+ Text.class, ParseText.class, CompressionType.RECORD, progress);
+
+ final MapFile.Writer dataOut = new MapFile.Writer(job, fs, data.toString(),
+ Text.class, ParseData.class, compType, progress);
+
+ final SequenceFile.Writer crawlOut = SequenceFile.createWriter(fs, job,
+ crawl, Text.class, CrawlDatum.class, compType, progress);
+
return new RecordWriter<Text, Parse>() {
+ public void write(Text key, Parse parse) throws IOException {
- public void write(Text key, Parse parse)
- throws IOException {
-
- String fromUrl = key.toString();
- String fromHost = null;
- textOut.append(key, new ParseText(parse.getText()));
-
- ParseData parseData = parse.getData();
- // recover the signature prepared by Fetcher or ParseSegment
- String sig = parseData.getContentMeta().get(Nutch.SIGNATURE_KEY);
- if (sig != null) {
- byte[] signature = StringUtil.fromHexString(sig);
- if (signature != null) {
- // append a CrawlDatum with a signature
- CrawlDatum d = new CrawlDatum(CrawlDatum.STATUS_SIGNATURE, 0);
- d.setSignature(signature);
- crawlOut.append(key, d);
- }
+ String fromUrl = key.toString();
+ String fromHost = null;
+ textOut.append(key, new ParseText(parse.getText()));
+
+ ParseData parseData = parse.getData();
+ // recover the signature prepared by Fetcher or ParseSegment
+ String sig = parseData.getContentMeta().get(Nutch.SIGNATURE_KEY);
+ if (sig != null) {
+ byte[] signature = StringUtil.fromHexString(sig);
+ if (signature != null) {
+ // append a CrawlDatum with a signature
+ CrawlDatum d = new CrawlDatum(CrawlDatum.STATUS_SIGNATURE, 0);
+ d.setSignature(signature);
+ crawlOut.append(key, d);
}
-
+ }
+
// see if the parse metadata contain things that we'd like
// to pass to the metadata of the crawlDB entry
CrawlDatum parseMDCrawlDatum = null;
for (String mdname : parseMDtoCrawlDB) {
String mdvalue = parse.getData().getParseMeta().get(mdname);
if (mdvalue != null) {
- if (parseMDCrawlDatum == null) parseMDCrawlDatum = new CrawlDatum(
- CrawlDatum.STATUS_PARSE_META, 0);
+ if (parseMDCrawlDatum == null)
+ parseMDCrawlDatum = new CrawlDatum(CrawlDatum.STATUS_PARSE_META,
+ 0);
parseMDCrawlDatum.getMetaData().put(new Text(mdname),
new Text(mdvalue));
}
}
- if (parseMDCrawlDatum != null) crawlOut.append(key, parseMDCrawlDatum);
+ if (parseMDCrawlDatum != null)
+ crawlOut.append(key, parseMDCrawlDatum);
if (ignoreExternalLinks) {
// need to determine fromHost (once for all outlinks)
@@ -198,91 +198,96 @@ public class ParseOutputFormat implements OutputFormat<Text, Parse> {
}
}
- // collect outlinks for subsequent db update
- Outlink[] links = parseData.getOutlinks();
- int outlinksToStore = Math.min(maxOutlinks, links.length);
-
- int validCount = 0;
- CrawlDatum adjust = null;
- List<Entry<Text, CrawlDatum>> targets = new ArrayList<Entry<Text, CrawlDatum>>(outlinksToStore);
- List<Outlink> outlinkList = new ArrayList<Outlink>(outlinksToStore);
- for (int i = 0; i < links.length && validCount < outlinksToStore; i++) {
- String toUrl = links[i].getToUrl();
-
- // Only normalize and filter if fetcher.parse = false
- if (!isParsing) {
- toUrl = ParseOutputFormat.filterNormalize(fromUrl, toUrl, fromHost, ignoreExternalLinks, filters, normalizers);
- if (toUrl == null) {
- continue;
- }
- }
+ // collect outlinks for subsequent db update
+ Outlink[] links = parseData.getOutlinks();
+ int outlinksToStore = Math.min(maxOutlinks, links.length);
- CrawlDatum target = new CrawlDatum(CrawlDatum.STATUS_LINKED, interval);
- Text targetUrl = new Text(toUrl);
-
- // see if the outlink has any metadata attached
- // and if so pass that to the crawldatum so that
- // the initial score or distribution can use that
- MapWritable outlinkMD = links[i].getMetadata();
- if (outlinkMD!=null){
- target.getMetaData().putAll(outlinkMD);
- }
-
- try {
- scfilters.initialScore(targetUrl, target);
- } catch (ScoringFilterException e) {
- LOG.warn("Cannot filter init score for url " + key +
- ", using default: " + e.getMessage());
- target.setScore(0.0f);
+ int validCount = 0;
+ CrawlDatum adjust = null;
+ List<Entry<Text, CrawlDatum>> targets = new ArrayList<Entry<Text, CrawlDatum>>(
+ outlinksToStore);
+ List<Outlink> outlinkList = new ArrayList<Outlink>(outlinksToStore);
+ for (int i = 0; i < links.length && validCount < outlinksToStore; i++) {
+ String toUrl = links[i].getToUrl();
+
+ // Only normalize and filter if fetcher.parse = false
+ if (!isParsing) {
+ toUrl = ParseOutputFormat.filterNormalize(fromUrl, toUrl, fromHost,
+ ignoreExternalLinks, filters, normalizers);
+ if (toUrl == null) {
+ continue;
}
+ }
- targets.add(new SimpleEntry(targetUrl, target));
+ CrawlDatum target = new CrawlDatum(CrawlDatum.STATUS_LINKED, interval);
+ Text targetUrl = new Text(toUrl);
- // OVerwrite URL in Outlink object with normalized URL (NUTCH-1174)
- links[i].setUrl(toUrl);
- outlinkList.add(links[i]);
- validCount++;
+ // see if the outlink has any metadata attached
+ // and if so pass that to the crawldatum so that
+ // the initial score or distribution can use that
+ MapWritable outlinkMD = links[i].getMetadata();
+ if (outlinkMD != null) {
+ target.getMetaData().putAll(outlinkMD);
}
try {
- // compute score contributions and adjustment to the original score
- adjust = scfilters.distributeScoreToOutlinks(key, parseData,
- targets, null, links.length);
+ scfilters.initialScore(targetUrl, target);
} catch (ScoringFilterException e) {
- LOG.warn("Cannot distribute score from " + key + ": " + e.getMessage());
- }
- for (Entry<Text, CrawlDatum> target : targets) {
- crawlOut.append(target.getKey(), target.getValue());
- }
- if (adjust != null) crawlOut.append(key, adjust);
-
- Outlink[] filteredLinks = outlinkList.toArray(new Outlink[outlinkList.size()]);
- parseData = new ParseData(parseData.getStatus(), parseData.getTitle(),
- filteredLinks, parseData.getContentMeta(),
- parseData.getParseMeta());
- dataOut.append(key, parseData);
- if (!parse.isCanonical()) {
- CrawlDatum datum = new CrawlDatum();
- datum.setStatus(CrawlDatum.STATUS_FETCH_SUCCESS);
- String timeString = parse.getData().getContentMeta().get(Nutch.FETCH_TIME_KEY);
- try {
- datum.setFetchTime(Long.parseLong(timeString));
- } catch (Exception e) {
- LOG.warn("Can't read fetch time for: " + key);
- datum.setFetchTime(System.currentTimeMillis());
- }
- crawlOut.append(key, datum);
+ LOG.warn("Cannot filter init score for url " + key
+ + ", using default: " + e.getMessage());
+ target.setScore(0.0f);
}
+
+ targets.add(new SimpleEntry(targetUrl, target));
+
+ // OVerwrite URL in Outlink object with normalized URL (NUTCH-1174)
+ links[i].setUrl(toUrl);
+ outlinkList.add(links[i]);
+ validCount++;
+ }
+
+ try {
+ // compute score contributions and adjustment to the original score
+ adjust = scfilters.distributeScoreToOutlinks(key, parseData, targets,
+ null, links.length);
+ } catch (ScoringFilterException e) {
+ LOG.warn("Cannot distribute score from " + key + ": "
+ + e.getMessage());
}
-
- public void close(Reporter reporter) throws IOException {
- textOut.close();
- dataOut.close();
- crawlOut.close();
+ for (Entry<Text, CrawlDatum> target : targets) {
+ crawlOut.append(target.getKey(), target.getValue());
}
-
- };
-
+ if (adjust != null)
+ crawlOut.append(key, adjust);
+
+ Outlink[] filteredLinks = outlinkList.toArray(new Outlink[outlinkList
+ .size()]);
+ parseData = new ParseData(parseData.getStatus(), parseData.getTitle(),
+ filteredLinks, parseData.getContentMeta(), parseData.getParseMeta());
+ dataOut.append(key, parseData);
+ if (!parse.isCanonical()) {
+ CrawlDatum datum = new CrawlDatum();
+ datum.setStatus(CrawlDatum.STATUS_FETCH_SUCCESS);
+ String timeString = parse.getData().getContentMeta()
+ .get(Nutch.FETCH_TIME_KEY);
+ try {
+ datum.setFetchTime(Long.parseLong(timeString));
+ } catch (Exception e) {
+ LOG.warn("Can't read fetch time for: " + key);
+ datum.setFetchTime(System.currentTimeMillis());
+ }
+ crawlOut.append(key, datum);
+ }
+ }
+
+ public void close(Reporter reporter) throws IOException {
+ textOut.close();
+ dataOut.close();
+ crawlOut.close();
+ }
+
+ };
+
}
public static String filterNormalize(String fromUrl, String toUrl,
@@ -311,12 +316,12 @@ public class ParseOutputFormat implements OutputFormat<Text, Parse> {
}
}
try {
- if(normalizers != null) {
- toUrl = normalizers.normalize(toUrl,
- urlNormalizerScope); // normalize the url
+ if (normalizers != null) {
+ toUrl = normalizers.normalize(toUrl, urlNormalizerScope); // normalize
+ // the url
}
if (filters != null) {
- toUrl = filters.filter(toUrl); // filter the url
+ toUrl = filters.filter(toUrl); // filter the url
}
if (toUrl == null) {
return null;
diff --git a/src/java/org/apache/nutch/parse/ParsePluginList.java b/src/java/org/apache/nutch/parse/ParsePluginList.java
index 22fd3cf9a..6ad0ac8c0 100644
--- a/src/java/org/apache/nutch/parse/ParsePluginList.java
+++ b/src/java/org/apache/nutch/parse/ParsePluginList.java
@@ -22,25 +22,23 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
/**
* This class represents a natural ordering for which parsing plugin should get
* called for a particular mimeType. It provides methods to store the
* parse-plugins.xml data, and methods to retreive the name of the appropriate
* parsing plugin for a contentType.
- *
+ *
* @author mattmann
* @version 1.0
*/
class ParsePluginList {
-
+
/* a map to link mimeType to an ordered list of parsing plugins */
private Map<String, List<String>> fMimeTypeToPluginMap = null;
-
+
/* A list of aliases */
private Map<String, String> aliases = null;
-
-
+
/**
* Constructs a new ParsePluginList
*/
@@ -48,7 +46,7 @@ class ParsePluginList {
fMimeTypeToPluginMap = new HashMap<String, List<String>>();
aliases = new HashMap<String, String>();
}
-
+
List<String> getPluginList(String mimeType) {
return fMimeTypeToPluginMap.get(mimeType);
}
@@ -56,18 +54,18 @@ class ParsePluginList {
void setAliases(Map<String, String> aliases) {
this.aliases = aliases;
}
-
+
Map<String, String> getAliases() {
return aliases;
}
-
+
void setPluginList(String mimeType, List<String> l) {
fMimeTypeToPluginMap.put(mimeType, l);
}
-
+
List<String> getSupportedMimeTypes() {
- return Arrays.asList(fMimeTypeToPluginMap.keySet().toArray(
- new String[] {}));
+ return Arrays
+ .asList(fMimeTypeToPluginMap.keySet().toArray(new String[] {}));
}
-
+
}
diff --git a/src/java/org/apache/nutch/parse/ParsePluginsReader.java b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
index 7f1987912..daf96e0b7 100644
--- a/src/java/org/apache/nutch/parse/ParsePluginsReader.java
+++ b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
@@ -42,50 +42,50 @@ import org.apache.hadoop.conf.Configuration;
// Nutch imports
import org.apache.nutch.util.NutchConfiguration;
-
/**
* A reader to load the information stored in the
* <code>$NUTCH_HOME/conf/parse-plugins.xml</code> file.
- *
+ *
* @author mattmann
* @version 1.0
*/
class ParsePluginsReader {
-
+
/* our log stream */
- public static final Logger LOG = LoggerFactory.getLogger(ParsePluginsReader.class);
-
+ public static final Logger LOG = LoggerFactory
+ .getLogger(ParsePluginsReader.class);
+
/** The property name of the parse-plugins location */
private static final String PP_FILE_PROP = "parse.plugin.file";
/** the parse-plugins file */
private String fParsePluginsFile = null;
-
/**
* Constructs a new ParsePluginsReader
*/
- public ParsePluginsReader() { }
-
+ public ParsePluginsReader() {
+ }
+
/**
* Reads the <code>parse-plugins.xml</code> file and returns the
* {@link #ParsePluginList} defined by it.
- *
+ *
* @return A {@link #ParsePluginList} specified by the
* <code>parse-plugins.xml</code> file.
* @throws Exception
- * If any parsing error occurs.
+ * If any parsing error occurs.
*/
public ParsePluginList parse(Configuration conf) {
-
+
ParsePluginList pList = new ParsePluginList();
-
+
// open up the XML file
DocumentBuilderFactory factory = null;
DocumentBuilder parser = null;
Document document = null;
InputSource inputSource = null;
-
+
InputStream ppInputStream = null;
if (fParsePluginsFile != null) {
URL parsePluginUrl = null;
@@ -94,56 +94,55 @@ class ParsePluginsReader {
ppInputStream = parsePluginUrl.openStream();
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to load parse plugins file from URL " +
- "[" + fParsePluginsFile + "]. Reason is [" + e + "]");
+ LOG.warn("Unable to load parse plugins file from URL " + "["
+ + fParsePluginsFile + "]. Reason is [" + e + "]");
}
return pList;
}
} else {
- ppInputStream = conf.getConfResourceAsInputStream(
- conf.get(PP_FILE_PROP));
+ ppInputStream = conf.getConfResourceAsInputStream(conf.get(PP_FILE_PROP));
}
-
+
inputSource = new InputSource(ppInputStream);
-
+
try {
factory = DocumentBuilderFactory.newInstance();
parser = factory.newDocumentBuilder();
document = parser.parse(inputSource);
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to parse [" + fParsePluginsFile + "]." +
- "Reason is [" + e + "]");
+ LOG.warn("Unable to parse [" + fParsePluginsFile + "]." + "Reason is ["
+ + e + "]");
}
return null;
}
-
+
Element parsePlugins = document.getDocumentElement();
-
+
// build up the alias hash map
Map<String, String> aliases = getAliases(parsePlugins);
// And store it on the parse plugin list
pList.setAliases(aliases);
-
+
// get all the mime type nodes
NodeList mimeTypes = parsePlugins.getElementsByTagName("mimeType");
-
+
// iterate through the mime types
for (int i = 0; i < mimeTypes.getLength(); i++) {
Element mimeType = (Element) mimeTypes.item(i);
String mimeTypeStr = mimeType.getAttribute("name");
-
+
// for each mimeType, get the plugin list
NodeList pluginList = mimeType.getElementsByTagName("plugin");
-
+
// iterate through the plugins, add them in order read
// OR if they have a special order="" attribute, then hold those in
// a separate list, and then insert them into the final list at the
// order specified
if (pluginList != null && pluginList.getLength() > 0) {
List<String> plugList = new ArrayList<String>(pluginList.getLength());
-
- for (int j = 0; j<pluginList.getLength(); j++) {
+
+ for (int j = 0; j < pluginList.getLength(); j++) {
Element plugin = (Element) pluginList.item(j);
String pluginId = plugin.getAttribute("id");
String extId = aliases.get(pluginId);
@@ -163,110 +162,110 @@ class ParsePluginsReader {
plugList.add(extId);
}
}
-
+
// now add the plugin list and map it to this mimeType
pList.setPluginList(mimeTypeStr, plugList);
-
+
} else if (LOG.isWarnEnabled()) {
LOG.warn("ParsePluginsReader:ERROR:no plugins defined for mime type: "
- + mimeTypeStr + ", continuing parse");
+ + mimeTypeStr + ", continuing parse");
}
}
return pList;
}
-
+
/**
* Tests parsing of the parse-plugins.xml file. An alternative name for the
- * file can be specified via the <code>--file</code> option, although the
- * file must be located in the <code>$NUTCH_HOME/conf</code> directory.
- *
+ * file can be specified via the <code>--file</code> option, although the file
+ * must be located in the <code>$NUTCH_HOME/conf</code> directory.
+ *
* @param args
- * Currently only the --file argument to specify an alternative
- * name for the parse-plugins.xml file is supported.
+ * Currently only the --file argument to specify an alternative name
+ * for the parse-plugins.xml file is supported.
*/
public static void main(String[] args) throws Exception {
String parsePluginFile = null;
String usage = "ParsePluginsReader [--file <parse plugin file location>]";
-
- if (( args.length != 0 && args.length != 2 )
+
+ if ((args.length != 0 && args.length != 2)
|| (args.length == 2 && !"--file".equals(args[0]))) {
System.err.println(usage);
System.exit(1);
}
-
+
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--file")) {
parsePluginFile = args[++i];
}
}
-
+
ParsePluginsReader reader = new ParsePluginsReader();
-
+
if (parsePluginFile != null) {
reader.setFParsePluginsFile(parsePluginFile);
}
-
+
ParsePluginList prefs = reader.parse(NutchConfiguration.create());
-
+
for (String mimeType : prefs.getSupportedMimeTypes()) {
-
+
System.out.println("MIMETYPE: " + mimeType);
List<String> plugList = prefs.getPluginList(mimeType);
-
+
System.out.println("EXTENSION IDs:");
-
+
for (String j : plugList) {
System.out.println(j);
}
}
-
+
}
-
+
/**
* @return Returns the fParsePluginsFile.
*/
public String getFParsePluginsFile() {
return fParsePluginsFile;
}
-
+
/**
* @param parsePluginsFile
- * The fParsePluginsFile to set.
+ * The fParsePluginsFile to set.
*/
public void setFParsePluginsFile(String parsePluginsFile) {
fParsePluginsFile = parsePluginsFile;
}
-
+
private Map<String, String> getAliases(Element parsePluginsRoot) {
Map<String, String> aliases = new HashMap<String, String>();
NodeList aliasRoot = parsePluginsRoot.getElementsByTagName("aliases");
-
+
if (aliasRoot == null || (aliasRoot != null && aliasRoot.getLength() == 0)) {
if (LOG.isWarnEnabled()) {
LOG.warn("No aliases defined in parse-plugins.xml!");
}
return aliases;
}
-
+
if (aliasRoot.getLength() > 1) {
// log a warning, but try and continue processing
if (LOG.isWarnEnabled()) {
LOG.warn("There should only be one \"aliases\" tag in parse-plugins.xml");
}
}
-
- Element aliasRootElem = (Element)aliasRoot.item(0);
+
+ Element aliasRootElem = (Element) aliasRoot.item(0);
NodeList aliasElements = aliasRootElem.getElementsByTagName("alias");
-
+
if (aliasElements != null && aliasElements.getLength() > 0) {
- for (int i=0; i<aliasElements.getLength(); i++) {
- Element aliasElem = (Element)aliasElements.item(i);
- String parsePluginId = aliasElem.getAttribute("name");
- String extensionId = aliasElem.getAttribute("extension-id");
+ for (int i = 0; i < aliasElements.getLength(); i++) {
+ Element aliasElem = (Element) aliasElements.item(i);
+ String parsePluginId = aliasElem.getAttribute("name");
+ String extensionId = aliasElem.getAttribute("extension-id");
if (LOG.isTraceEnabled()) {
- LOG.trace("Found alias: plugin-id: " + parsePluginId +
- ", extension-id: " + extensionId);
+ LOG.trace("Found alias: plugin-id: " + parsePluginId
+ + ", extension-id: " + extensionId);
}
if (parsePluginId != null && extensionId != null) {
aliases.put(parsePluginId, extensionId);
@@ -275,5 +274,5 @@ class ParsePluginsReader {
}
return aliases;
}
-
+
}
diff --git a/src/java/org/apache/nutch/parse/ParseResult.java b/src/java/org/apache/nutch/parse/ParseResult.java
index 8d9bdd054..92d8871f1 100644
--- a/src/java/org/apache/nutch/parse/ParseResult.java
+++ b/src/java/org/apache/nutch/parse/ParseResult.java
@@ -27,94 +27,116 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.Text;
/**
- * A utility class that stores result of a parse. Internally
- * a ParseResult stores &lt;{@link Text}, {@link Parse}&gt; pairs.
- * <p>Parsers may return multiple results, which correspond to parts
- * or other associated documents related to the original URL.</p>
- * <p>There will be usually one parse result that corresponds directly
- * to the original URL, and possibly many (or none) results that correspond
- * to derived URLs (or sub-URLs).
+ * A utility class that stores result of a parse. Internally a ParseResult
+ * stores &lt;{@link Text}, {@link Parse}&gt; pairs.
+ * <p>
+ * Parsers may return multiple results, which correspond to parts or other
+ * associated documents related to the original URL.
+ * </p>
+ * <p>
+ * There will be usually one parse result that corresponds directly to the
+ * original URL, and possibly many (or none) results that correspond to derived
+ * URLs (or sub-URLs).
*/
public class ParseResult implements Iterable<Map.Entry<Text, Parse>> {
private Map<Text, Parse> parseMap;
private String originalUrl;
-
+
public static final Logger LOG = LoggerFactory.getLogger(ParseResult.class);
-
+
/**
* Create a container for parse results.
- * @param originalUrl the original url from which all parse results
- * have been obtained.
+ *
+ * @param originalUrl
+ * the original url from which all parse results have been obtained.
*/
public ParseResult(String originalUrl) {
parseMap = new HashMap<Text, Parse>();
this.originalUrl = originalUrl;
}
-
+
/**
* Convenience method for obtaining {@link ParseResult} from a single
* <code>Parse</code> output.
- * @param url canonical url.
- * @param parse single parse output.
+ *
+ * @param url
+ * canonical url.
+ * @param parse
+ * single parse output.
* @return result containing the single parse output.
*/
public static ParseResult createParseResult(String url, Parse parse) {
ParseResult parseResult = new ParseResult(url);
- parseResult.put(new Text(url), new ParseText(parse.getText()), parse.getData());
+ parseResult.put(new Text(url), new ParseText(parse.getText()),
+ parse.getData());
return parseResult;
}
-
+
/**
* Checks whether the result is empty.
+ *
* @return
*/
public boolean isEmpty() {
return parseMap.isEmpty();
}
-
+
/**
* Return the number of parse outputs (both successful and failed)
*/
public int size() {
return parseMap.size();
}
-
+
/**
* Retrieve a single parse output.
- * @param key sub-url under which the parse output is stored.
+ *
+ * @param key
+ * sub-url under which the parse output is stored.
* @return parse output corresponding to this sub-url, or null.
*/
public Parse get(String key) {
return get(new Text(key));
}
-
+
/**
* Retrieve a single parse output.
- * @param key sub-url under which the parse output is stored.
+ *
+ * @param key
+ * sub-url under which the parse output is stored.
* @return parse output corresponding to this sub-url, or null.
*/
public Parse get(Text key) {
return parseMap.get(key);
}
-
+
/**
* Store a result of parsing.
- * @param key URL or sub-url of this parse result
- * @param text plain text result
- * @param data corresponding parse metadata of this result
+ *
+ * @param key
+ * URL or sub-url of this parse result
+ * @param text
+ * plain text result
+ * @param data
+ * corresponding parse metadata of this result
*/
public void put(Text key, ParseText text, ParseData data) {
put(key.toString(), text, data);
}
-
+
/**
* Store a result of parsing.
- * @param key URL or sub-url of this parse result
- * @param text plain text result
- * @param data corresponding parse metadata of this result
+ *
+ * @param key
+ * URL or sub-url of this parse result
+ * @param text
+ * plain text result
+ * @param data
+ * corresponding parse metadata of this result
*/
public void put(String key, ParseText text, ParseData data) {
- parseMap.put(new Text(key), new ParseImpl(text, data, key.equals(originalUrl)));
+ parseMap.put(new Text(key),
+ new ParseImpl(text, data, key.equals(originalUrl)));
}
/**
@@ -123,21 +145,21 @@ public class ParseResult implements Iterable<Map.Entry<Text, Parse>> {
public Iterator<Entry<Text, Parse>> iterator() {
return parseMap.entrySet().iterator();
}
-
+
/**
- * Remove all results where status is not successful (as determined
- * by </code>ParseStatus#isSuccess()</code>). Note that effects of this operation
+ * Remove all results where status is not successful (as determined by
+ * </code>ParseStatus#isSuccess()</code>). Note that effects of this operation
* cannot be reversed.
*/
public void filter() {
- for(Iterator<Entry<Text, Parse>> i = iterator(); i.hasNext();) {
+ for (Iterator<Entry<Text, Parse>> i = iterator(); i.hasNext();) {
Entry<Text, Parse> entry = i.next();
if (!entry.getValue().getData().getStatus().isSuccess()) {
LOG.warn(entry.getKey() + " is not parsed successfully, filtering");
i.remove();
}
}
-
+
}
/**
@@ -145,7 +167,7 @@ public class ParseResult implements Iterable<Map.Entry<Text, Parse>> {
* Parse success is determined by <code>ParseStatus#isSuccess()</code>.
*/
public boolean isSuccess() {
- for(Iterator<Entry<Text, Parse>> i = iterator(); i.hasNext();) {
+ for (Iterator<Entry<Text, Parse>> i = iterator(); i.hasNext();) {
Entry<Text, Parse> entry = i.next();
if (!entry.getValue().getData().getStatus().isSuccess()) {
return false;
diff --git a/src/java/org/apache/nutch/parse/ParseSegment.java b/src/java/org/apache/nutch/parse/ParseSegment.java
index aca6800b2..e1360dff9 100644
--- a/src/java/org/apache/nutch/parse/ParseSegment.java
+++ b/src/java/org/apache/nutch/parse/ParseSegment.java
@@ -46,19 +46,19 @@ public class ParseSegment extends Configured implements Tool,
Reducer<Text, Writable, Text, Writable> {
public static final Logger LOG = LoggerFactory.getLogger(ParseSegment.class);
-
+
public static final String SKIP_TRUNCATED = "parser.skip.truncated";
-
+
private ScoringFilters scfilters;
-
+
private ParseUtil parseUtil;
-
+
private boolean skipTruncated;
-
+
public ParseSegment() {
this(null);
}
-
+
public ParseSegment(Configuration conf) {
super(conf);
}
@@ -66,41 +66,43 @@ public class ParseSegment extends Configured implements Tool,
public void configure(JobConf job) {
setConf(job);
this.scfilters = new ScoringFilters(job);
- skipTruncated=job.getBoolean(SKIP_TRUNCATED, true);
+ skipTruncated = job.getBoolean(SKIP_TRUNCATED, true);
+ }
+
+ public void close() {
}
- public void close() {}
-
private Text newKey = new Text();
public void map(WritableComparable<?> key, Content content,
- OutputCollector<Text, ParseImpl> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, ParseImpl> output, Reporter reporter)
+ throws IOException {
// convert on the fly from old UTF8 keys
if (key instanceof Text) {
newKey.set(key.toString());
key = newKey;
}
-
- int status =
- Integer.parseInt(content.getMetadata().get(Nutch.FETCH_STATUS_KEY));
+
+ int status = Integer.parseInt(content.getMetadata().get(
+ Nutch.FETCH_STATUS_KEY));
if (status != CrawlDatum.STATUS_FETCH_SUCCESS) {
// content not fetched successfully, skip document
LOG.debug("Skipping " + key + " as content is not fetched successfully");
return;
}
-
+
if (skipTruncated && isTruncated(content)) {
return;
}
ParseResult parseResult = null;
try {
- if (parseUtil == null)
+ if (parseUtil == null)
parseUtil = new ParseUtil(getConf());
parseResult = parseUtil.parse(content);
} catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": " + StringUtils.stringifyException(e));
+ LOG.warn("Error parsing: " + key + ": "
+ + StringUtils.stringifyException(e));
return;
}
@@ -111,7 +113,8 @@ public class ParseSegment extends Configured implements Tool,
long start = System.currentTimeMillis();
- reporter.incrCounter("ParserStatus", ParseStatus.majorCodes[parseStatus.getMajorCode()], 1);
+ reporter.incrCounter("ParserStatus",
+ ParseStatus.majorCodes[parseStatus.getMajorCode()], 1);
if (!parseStatus.isSuccess()) {
LOG.warn("Error parsing: " + key + ": " + parseStatus);
@@ -119,45 +122,51 @@ public class ParseSegment extends Configured implements Tool,
}
// pass segment name to parse data
- parse.getData().getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
- getConf().get(Nutch.SEGMENT_NAME_KEY));
+ parse.getData().getContentMeta()
+ .set(Nutch.SEGMENT_NAME_KEY, getConf().get(Nutch.SEGMENT_NAME_KEY));
// compute the new signature
- byte[] signature =
- SignatureFactory.getSignature(getConf()).calculate(content, parse);
- parse.getData().getContentMeta().set(Nutch.SIGNATURE_KEY,
- StringUtil.toHexString(signature));
-
+ byte[] signature = SignatureFactory.getSignature(getConf()).calculate(
+ content, parse);
+ parse.getData().getContentMeta()
+ .set(Nutch.SIGNATURE_KEY, StringUtil.toHexString(signature));
+
try {
scfilters.passScoreAfterParsing(url, content, parse);
} catch (ScoringFilterException e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Error passing score: "+ url +": "+e.getMessage());
+ LOG.warn("Error passing score: " + url + ": " + e.getMessage());
}
}
long end = System.currentTimeMillis();
LOG.info("Parsed (" + Long.toString(end - start) + "ms):" + url);
- output.collect(url, new ParseImpl(new ParseText(parse.getText()),
- parse.getData(), parse.isCanonical()));
+ output.collect(
+ url,
+ new ParseImpl(new ParseText(parse.getText()), parse.getData(), parse
+ .isCanonical()));
}
}
-
+
/**
* Checks if the page's content is truncated.
+ *
* @param content
- * @return If the page is truncated <code>true</code>. When it is not,
- * or when it could be determined, <code>false</code>.
+ * @return If the page is truncated <code>true</code>. When it is not, or when
+ * it could be determined, <code>false</code>.
*/
public static boolean isTruncated(Content content) {
byte[] contentBytes = content.getContent();
- if (contentBytes == null) return false;
+ if (contentBytes == null)
+ return false;
Metadata metadata = content.getMetadata();
- if (metadata == null) return false;
-
+ if (metadata == null)
+ return false;
+
String lengthStr = metadata.get(Response.CONTENT_LENGTH);
- if (lengthStr != null) lengthStr=lengthStr.trim();
+ if (lengthStr != null)
+ lengthStr = lengthStr.trim();
if (StringUtil.isEmpty(lengthStr)) {
return false;
}
@@ -176,14 +185,15 @@ public class ParseSegment extends Configured implements Tool,
return true;
}
if (LOG.isDebugEnabled()) {
- LOG.debug(url + " actualSize=" + actualSize + " inHeaderSize=" + inHeaderSize);
+ LOG.debug(url + " actualSize=" + actualSize + " inHeaderSize="
+ + inHeaderSize);
}
return false;
}
public void reduce(Text key, Iterator<Writable> values,
- OutputCollector<Text, Writable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, Writable> output, Reporter reporter)
+ throws IOException {
output.collect(key, values.next()); // collect first value
}
@@ -204,7 +214,7 @@ public class ParseSegment extends Configured implements Tool,
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(ParseSegment.class);
job.setReducerClass(ParseSegment.class);
-
+
FileOutputFormat.setOutputPath(job, segment);
job.setOutputFormat(ParseOutputFormat.class);
job.setOutputKeyClass(Text.class);
@@ -212,15 +222,16 @@ public class ParseSegment extends Configured implements Tool,
JobClient.runJob(job);
long end = System.currentTimeMillis();
- LOG.info("ParseSegment: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("ParseSegment: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
-
public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new ParseSegment(), args);
- System.exit(res);
+ int res = ToolRunner.run(NutchConfiguration.create(), new ParseSegment(),
+ args);
+ System.exit(res);
}
-
+
public int run(String[] args) throws Exception {
Path segment;
@@ -231,11 +242,11 @@ public class ParseSegment extends Configured implements Tool,
System.exit(-1);
}
- if(args.length > 1) {
- for(int i = 1; i < args.length; i++) {
+ if (args.length > 1) {
+ for (int i = 1; i < args.length; i++) {
String param = args[i];
- if("-nofilter".equalsIgnoreCase(param)) {
+ if ("-nofilter".equalsIgnoreCase(param)) {
getConf().setBoolean("parse.filter.urls", false);
} else if ("-nonormalize".equalsIgnoreCase(param)) {
getConf().setBoolean("parse.normalize.urls", false);
diff --git a/src/java/org/apache/nutch/parse/ParseStatus.java b/src/java/org/apache/nutch/parse/ParseStatus.java
index d86d95846..b9d59598d 100644
--- a/src/java/org/apache/nutch/parse/ParseStatus.java
+++ b/src/java/org/apache/nutch/parse/ParseStatus.java
@@ -1,19 +1,19 @@
/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You 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.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
/*
* Created on Apr 28, 2005
* Author: Andrzej Bialecki &lt;[email protected]&gt;
@@ -32,113 +32,119 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
-
/**
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
public class ParseStatus implements Writable {
-
+
private final static byte VERSION = 2;
-
+
// Primary status codes:
-
+
/** Parsing was not performed. */
- public static final byte NOTPARSED = 0;
+ public static final byte NOTPARSED = 0;
/** Parsing succeeded. */
- public static final byte SUCCESS = 1;
+ public static final byte SUCCESS = 1;
/** General failure. There may be a more specific error message in arguments. */
- public static final byte FAILED = 2;
-
- public static final String[] majorCodes = {
- "notparsed",
- "success",
- "failed"
- };
-
+ public static final byte FAILED = 2;
+
+ public static final String[] majorCodes = { "notparsed", "success", "failed" };
+
// Secondary success codes go here:
-
- /** Parsed content contains a directive to redirect to another URL.
- * The target URL can be retrieved from the arguments.
+
+ /**
+ * Parsed content contains a directive to redirect to another URL. The target
+ * URL can be retrieved from the arguments.
*/
- public static final short SUCCESS_REDIRECT = 100;
-
+ public static final short SUCCESS_REDIRECT = 100;
+
// Secondary failure codes go here:
-
- /** Parsing failed. An Exception occured (which may be retrieved from the arguments). */
- public static final short FAILED_EXCEPTION = 200;
- /** Parsing failed. Content was truncated, but the parser cannot handle incomplete content. */
- public static final short FAILED_TRUNCATED = 202;
- /** Parsing failed. Invalid format - the content may be corrupted or of wrong type. */
- public static final short FAILED_INVALID_FORMAT = 203;
- /** Parsing failed. Other related parts of the content are needed to complete
+
+ /**
+ * Parsing failed. An Exception occured (which may be retrieved from the
+ * arguments).
+ */
+ public static final short FAILED_EXCEPTION = 200;
+ /**
+ * Parsing failed. Content was truncated, but the parser cannot handle
+ * incomplete content.
+ */
+ public static final short FAILED_TRUNCATED = 202;
+ /**
+ * Parsing failed. Invalid format - the content may be corrupted or of wrong
+ * type.
+ */
+ public static final short FAILED_INVALID_FORMAT = 203;
+ /**
+ * Parsing failed. Other related parts of the content are needed to complete
* parsing. The list of URLs to missing parts may be provided in arguments.
* The Fetcher may decide to fetch these parts at once, then put them into
* Content.metadata, and supply them for re-parsing.
*/
- public static final short FAILED_MISSING_PARTS = 204;
- /** Parsing failed. There was no content to be parsed - probably caused
- * by errors at protocol stage.
+ public static final short FAILED_MISSING_PARTS = 204;
+ /**
+ * Parsing failed. There was no content to be parsed - probably caused by
+ * errors at protocol stage.
*/
- public static final short FAILED_MISSING_CONTENT = 205;
-
+ public static final short FAILED_MISSING_CONTENT = 205;
public static final ParseStatus STATUS_NOTPARSED = new ParseStatus(NOTPARSED);
public static final ParseStatus STATUS_SUCCESS = new ParseStatus(SUCCESS);
public static final ParseStatus STATUS_FAILURE = new ParseStatus(FAILED);
-
+
private byte majorCode = 0;
private short minorCode = 0;
private String[] args = null;
-
+
public byte getVersion() {
return VERSION;
}
public ParseStatus() {
-
+
}
-
+
public ParseStatus(int majorCode, int minorCode, String[] args) {
this.args = args;
- this.majorCode = (byte)majorCode;
- this.minorCode = (short)minorCode;
+ this.majorCode = (byte) majorCode;
+ this.minorCode = (short) minorCode;
}
-
+
public ParseStatus(int majorCode) {
- this(majorCode, 0, (String[])null);
+ this(majorCode, 0, (String[]) null);
}
-
+
public ParseStatus(int majorCode, String[] args) {
this(majorCode, 0, args);
}
-
+
public ParseStatus(int majorCode, int minorCode) {
- this(majorCode, minorCode, (String[])null);
+ this(majorCode, minorCode, (String[]) null);
}
-
+
/** Simplified constructor for passing just a text message. */
public ParseStatus(int majorCode, int minorCode, String message) {
- this(majorCode, minorCode, new String[]{message});
+ this(majorCode, minorCode, new String[] { message });
}
-
+
/** Simplified constructor for passing just a text message. */
public ParseStatus(int majorCode, String message) {
- this(majorCode, 0, new String[]{message});
+ this(majorCode, 0, new String[] { message });
}
-
+
public ParseStatus(Throwable t) {
- this(FAILED, FAILED_EXCEPTION, new String[]{t.toString()});
+ this(FAILED, FAILED_EXCEPTION, new String[] { t.toString() });
}
-
+
public static ParseStatus read(DataInput in) throws IOException {
ParseStatus res = new ParseStatus();
res.readFields(in);
return res;
}
-
+
public void readFields(DataInput in) throws IOException {
byte version = in.readByte();
- switch(version) {
+ switch (version) {
case 1:
majorCode = in.readByte();
minorCode = in.readShort();
@@ -152,8 +158,8 @@ public class ParseStatus implements Writable {
default:
throw new VersionMismatchException(VERSION, version);
}
- }
-
+ }
+
public void write(DataOutput out) throws IOException {
out.writeByte(VERSION);
out.writeByte(majorCode);
@@ -164,55 +170,61 @@ public class ParseStatus implements Writable {
WritableUtils.writeStringArray(out, args);
}
}
-
- /** A convenience method. Returns true if majorCode is SUCCESS, false
+
+ /**
+ * A convenience method. Returns true if majorCode is SUCCESS, false
* otherwise.
*/
-
+
public boolean isSuccess() {
return majorCode == SUCCESS;
}
-
- /** A convenience method. Return a String representation of the first
- * argument, or null.
+
+ /**
+ * A convenience method. Return a String representation of the first argument,
+ * or null.
*/
public String getMessage() {
if (args != null && args.length > 0 && args[0] != null)
return args[0];
return null;
}
-
+
public String[] getArgs() {
return args;
}
-
+
public int getMajorCode() {
return majorCode;
}
-
+
public int getMinorCode() {
return minorCode;
}
-
- /** A convenience method. Creates an empty Parse instance,
- * which returns this status.
+
+ /**
+ * A convenience method. Creates an empty Parse instance, which returns this
+ * status.
*/
public Parse getEmptyParse(Configuration conf) {
return new EmptyParseImpl(this, conf);
}
-
- /** A convenience method. Creates an empty ParseResult,
- * which contains this status.
+
+ /**
+ * A convenience method. Creates an empty ParseResult, which contains this
+ * status.
*/
public ParseResult getEmptyParseResult(String url, Configuration conf) {
return ParseResult.createParseResult(url, getEmptyParse(conf));
}
-
+
public String toString() {
StringBuffer res = new StringBuffer();
String name = null;
- if (majorCode >= 0 && majorCode < majorCodes.length) name = majorCodes[majorCode];
- else name = "UNKNOWN!";
+ if (majorCode >= 0 && majorCode < majorCodes.length)
+ name = majorCodes[majorCode];
+ else
+ name = "UNKNOWN!";
res.append(name + "(" + majorCode + "," + minorCode + ")");
if (args != null) {
if (args.length == 1) {
@@ -226,18 +238,18 @@ public class ParseStatus implements Writable {
}
return res.toString();
}
-
+
public void setArgs(String[] args) {
this.args = args;
}
-
+
public void setMessage(String msg) {
if (args == null || args.length == 0) {
args = new String[1];
}
args[0] = msg;
}
-
+
public void setMajorCode(byte majorCode) {
this.majorCode = majorCode;
}
@@ -245,37 +257,45 @@ public class ParseStatus implements Writable {
public void setMinorCode(short minorCode) {
this.minorCode = minorCode;
}
-
+
public boolean equals(Object o) {
- if (o == null) return false;
- if (!(o instanceof ParseStatus)) return false;
+ if (o == null)
+ return false;
+ if (!(o instanceof ParseStatus))
+ return false;
boolean res = true;
- ParseStatus other = (ParseStatus)o;
- res = res && (this.majorCode == other.majorCode) &&
- (this.minorCode == other.minorCode);
- if (!res) return res;
+ ParseStatus other = (ParseStatus) o;
+ res = res && (this.majorCode == other.majorCode)
+ && (this.minorCode == other.minorCode);
+ if (!res)
+ return res;
if (this.args == null) {
- if (other.args == null) return true;
- else return false;
+ if (other.args == null)
+ return true;
+ else
+ return false;
} else {
- if (other.args == null) return false;
- if (other.args.length != this.args.length) return false;
+ if (other.args == null)
+ return false;
+ if (other.args.length != this.args.length)
+ return false;
for (int i = 0; i < this.args.length; i++) {
- if (!this.args[i].equals(other.args[i])) return false;
+ if (!this.args[i].equals(other.args[i]))
+ return false;
}
}
return true;
}
-
+
private static class EmptyParseImpl implements Parse {
-
+
private ParseData data = null;
-
+
public EmptyParseImpl(ParseStatus status, Configuration conf) {
- data = new ParseData(status, "", new Outlink[0],
- new Metadata(), new Metadata());
+ data = new ParseData(status, "", new Outlink[0], new Metadata(),
+ new Metadata());
}
-
+
public ParseData getData() {
return data;
}
@@ -283,10 +303,9 @@ public class ParseStatus implements Writable {
public String getText() {
return "";
}
-
+
public boolean isCanonical() {
return true;
}
}
}
-
diff --git a/src/java/org/apache/nutch/parse/ParseText.java b/src/java/org/apache/nutch/parse/ParseText.java
index 8cc28041f..13416cf04 100644
--- a/src/java/org/apache/nutch/parse/ParseText.java
+++ b/src/java/org/apache/nutch/parse/ParseText.java
@@ -33,10 +33,12 @@ public final class ParseText implements Writable {
private final static byte VERSION = 2;
- public ParseText() {}
+ public ParseText() {
+ }
+
private String text;
-
- public ParseText(String text){
+
+ public ParseText(String text) {
this.text = text;
}
@@ -68,12 +70,14 @@ public final class ParseText implements Writable {
//
// Accessor methods
//
- public String getText() { return text; }
+ public String getText() {
+ return text;
+ }
public boolean equals(Object o) {
if (!(o instanceof ParseText))
return false;
- ParseText other = (ParseText)o;
+ ParseText other = (ParseText) o;
return this.text.equals(other.text);
}
@@ -90,12 +94,11 @@ public final class ParseText implements Writable {
}
Options opts = new Options();
Configuration conf = NutchConfiguration.create();
-
- GenericOptionsParser parser =
- new GenericOptionsParser(conf, opts, argv);
-
+
+ GenericOptionsParser parser = new GenericOptionsParser(conf, opts, argv);
+
String[] remainingArgs = parser.getRemainingArgs();
-
+
FileSystem fs = FileSystem.get(conf);
try {
int recno = Integer.parseInt(remainingArgs[0]);
diff --git a/src/java/org/apache/nutch/parse/ParseUtil.java b/src/java/org/apache/nutch/parse/ParseUtil.java
index 2c4493e57..39024dc7c 100644
--- a/src/java/org/apache/nutch/parse/ParseUtil.java
+++ b/src/java/org/apache/nutch/parse/ParseUtil.java
@@ -30,127 +30,136 @@ import org.apache.nutch.protocol.Content;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-
/**
* A Utility class containing methods to simply perform parsing utilities such
* as iterating through a preferred list of {@link Parser}s to obtain
* {@link Parse} objects.
- *
+ *
* @author mattmann
* @author J&eacute;r&ocirc;me Charron
* @author S&eacute;bastien Le Callonnec
*/
public class ParseUtil {
-
+
/* our log stream */
public static final Logger LOG = LoggerFactory.getLogger(ParseUtil.class);
private ParserFactory parserFactory;
/** Parser timeout set to 30 sec by default. Set -1 to deactivate **/
private int maxParseTime = 30;
private ExecutorService executorService;
-
+
/**
*
* @param conf
*/
public ParseUtil(Configuration conf) {
this.parserFactory = new ParserFactory(conf);
- maxParseTime=conf.getInt("parser.timeout", 30);
+ maxParseTime = conf.getInt("parser.timeout", 30);
executorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder()
- .setNameFormat("parse-%d").setDaemon(true).build());
+ .setNameFormat("parse-%d").setDaemon(true).build());
}
-
+
/**
* Performs a parse by iterating through a List of preferred {@link Parser}s
* until a successful parse is performed and a {@link Parse} object is
* returned. If the parse is unsuccessful, a message is logged to the
* <code>WARNING</code> level, and an empty parse is returned.
- *
- * @param content The content to try and parse.
+ *
+ * @param content
+ * The content to try and parse.
* @return &lt;key, {@link Parse}&gt; pairs.
- * @throws ParseException If no suitable parser is found to perform the parse.
+ * @throws ParseException
+ * If no suitable parser is found to perform the parse.
*/
public ParseResult parse(Content content) throws ParseException {
Parser[] parsers = null;
-
+
try {
- parsers = this.parserFactory.getParsers(content.getContentType(),
- content.getUrl() != null ? content.getUrl():"");
+ parsers = this.parserFactory.getParsers(content.getContentType(),
+ content.getUrl() != null ? content.getUrl() : "");
} catch (ParserNotFound e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("No suitable parser found when trying to parse content " + content.getUrl() +
- " of type " + content.getContentType());
+ LOG.warn("No suitable parser found when trying to parse content "
+ + content.getUrl() + " of type " + content.getContentType());
}
throw new ParseException(e.getMessage());
}
-
+
ParseResult parseResult = null;
- for (int i=0; i<parsers.length; i++) {
+ for (int i = 0; i < parsers.length; i++) {
if (LOG.isDebugEnabled()) {
- LOG.debug("Parsing [" + content.getUrl() + "] with [" + parsers[i] + "]");
+ LOG.debug("Parsing [" + content.getUrl() + "] with [" + parsers[i]
+ + "]");
}
- if (maxParseTime!=-1)
- parseResult = runParser(parsers[i], content);
- else
- parseResult = parsers[i].getParse(content);
+ if (maxParseTime != -1)
+ parseResult = runParser(parsers[i], content);
+ else
+ parseResult = parsers[i].getParse(content);
if (parseResult != null && !parseResult.isEmpty())
return parseResult;
}
-
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to successfully parse content " + content.getUrl() +
- " of type " + content.getContentType());
+
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Unable to successfully parse content " + content.getUrl()
+ + " of type " + content.getContentType());
}
- return new ParseStatus(new ParseException("Unable to successfully parse content")).getEmptyParseResult(content.getUrl(), null);
+ return new ParseStatus(new ParseException(
+ "Unable to successfully parse content")).getEmptyParseResult(
+ content.getUrl(), null);
}
-
+
/**
* Method parses a {@link Content} object using the {@link Parser} specified
- * by the parameter <code>extId</code>, i.e., the Parser's extension ID.
- * If a suitable {@link Parser} is not found, then a <code>WARNING</code>
- * level message is logged, and a ParseException is thrown. If the parse is
- * uncessful for any other reason, then a <code>WARNING</code> level
- * message is logged, and a <code>ParseStatus.getEmptyParse()</code> is
- * returned.
- *
- * @param extId The extension implementation ID of the {@link Parser} to use
- * to parse the specified content.
- * @param content The content to parse.
- *
- * @return &lt;key, {@link Parse}&gt; pairs if the parse is successful, otherwise,
- * a single &lt;key, <code>ParseStatus.getEmptyParse()</code>&gt; pair.
- *
- * @throws ParseException If there is no suitable {@link Parser} found
- * to perform the parse.
+ * by the parameter <code>extId</code>, i.e., the Parser's extension ID. If a
+ * suitable {@link Parser} is not found, then a <code>WARNING</code> level
+ * message is logged, and a ParseException is thrown. If the parse is
+ * uncessful for any other reason, then a <code>WARNING</code> level message
+ * is logged, and a <code>ParseStatus.getEmptyParse()</code> is returned.
+ *
+ * @param extId
+ * The extension implementation ID of the {@link Parser} to use to
+ * parse the specified content.
+ * @param content
+ * The content to parse.
+ *
+ * @return &lt;key, {@link Parse}&gt; pairs if the parse is successful,
+ * otherwise, a single &lt;key,
+ * <code>ParseStatus.getEmptyParse()</code>&gt; pair.
+ *
+ * @throws ParseException
+ * If there is no suitable {@link Parser} found to perform the
+ * parse.
*/
public ParseResult parseByExtensionId(String extId, Content content)
- throws ParseException {
+ throws ParseException {
Parser p = null;
-
+
try {
p = this.parserFactory.getParserById(extId);
} catch (ParserNotFound e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("No suitable parser found when trying to parse content " + content.getUrl() +
- " of type " + content.getContentType());
+ LOG.warn("No suitable parser found when trying to parse content "
+ + content.getUrl() + " of type " + content.getContentType());
}
throw new ParseException(e.getMessage());
}
-
+
ParseResult parseResult = null;
- if (maxParseTime!=-1)
- parseResult = runParser(p, content);
- else
- parseResult = p.getParse(content);
+ if (maxParseTime != -1)
+ parseResult = runParser(p, content);
+ else
+ parseResult = p.getParse(content);
if (parseResult != null && !parseResult.isEmpty()) {
return parseResult;
} else {
if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to successfully parse content " + content.getUrl() +
- " of type " + content.getContentType());
- }
- return new ParseStatus(new ParseException("Unable to successfully parse content")).getEmptyParseResult(content.getUrl(), null);
+ LOG.warn("Unable to successfully parse content " + content.getUrl()
+ + " of type " + content.getContentType());
+ }
+ return new ParseStatus(new ParseException(
+ "Unable to successfully parse content")).getEmptyParseResult(
+ content.getUrl(), null);
}
}
@@ -168,5 +177,5 @@ public class ParseUtil {
}
return res;
}
-
+
}
diff --git a/src/java/org/apache/nutch/parse/Parser.java b/src/java/org/apache/nutch/parse/Parser.java
index 0f8b68084..d101453da 100644
--- a/src/java/org/apache/nutch/parse/Parser.java
+++ b/src/java/org/apache/nutch/parse/Parser.java
@@ -24,33 +24,35 @@ import org.apache.hadoop.conf.Configurable;
import org.apache.nutch.plugin.Pluggable;
import org.apache.nutch.protocol.Content;
-/** 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.
+/**
+ * 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 extends Pluggable, Configurable {
/** The name of the extension point. */
public final static String X_POINT_ID = Parser.class.getName();
- /**
+ /**
* <p>
- * This method parses the given content and returns a map of
- * &lt;key, parse&gt; pairs. {@link Parse} instances will be persisted
- * under the given key.
+ * This method parses the given content and returns a map of &lt;key,
+ * parse&gt; pairs. {@link Parse} instances will be persisted under the given
+ * key.
* </p>
* <p>
- * Note: Meta-redirects should be followed only when they are coming from
- * the original URL. That is: <br>
+ * Note: Meta-redirects should be followed only when they are coming from the
+ * original URL. That is: <br>
* Assume fetcher is in parsing mode and is currently processing
- * foo.bar.com/redirect.html. If this url contains a meta redirect
- * to another url, fetcher should only follow the redirect if the map
- * contains an entry of the form &lt;"foo.bar.com/redirect.html",
- * {@link Parse} with a {@link ParseStatus} indicating the redirect&gt;.
+ * foo.bar.com/redirect.html. If this url contains a meta redirect to another
+ * url, fetcher should only follow the redirect if the map contains an entry
+ * of the form &lt;"foo.bar.com/redirect.html", {@link Parse} with a
+ * {@link ParseStatus} indicating the redirect&gt;.
* </p>
*
- * @param c Content to be parsed
+ * @param c
+ * Content to be parsed
* @return a map containing &lt;key, parse&gt; pairs
* @since NUTCH-443
*/
- ParseResult getParse(Content c);
+ ParseResult getParse(Content c);
}
diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.java
index e9b559bf2..8cd725d7e 100644
--- a/src/java/org/apache/nutch/parse/ParserChecker.java
+++ b/src/java/org/apache/nutch/parse/ParserChecker.java
@@ -40,28 +40,30 @@ import org.apache.nutch.util.URLUtil;
import org.apache.nutch.util.StringUtil;
/**
- * Parser checker, useful for testing parser.
- * It also accurately reports possible fetching and
- * parsing failures and presents protocol status signals to aid
- * debugging. The tool enables us to retrieve the following data from
- * any url:
+ * Parser checker, useful for testing parser. It also accurately reports
+ * possible fetching and parsing failures and presents protocol status signals
+ * to aid debugging. The tool enables us to retrieve the following data from any
+ * url:
* <ol>
- * <li><tt>contentType</tt>: The URL {@link org.apache.nutch.protocol.Content} type.</li>
- * <li><tt>signature</tt>: Digest is used to identify pages (like unique ID) and is used to remove
- * duplicates during the dedup procedure.
- * It is calculated using {@link org.apache.nutch.crawl.MD5Signature} or
+ * <li><tt>contentType</tt>: The URL {@link org.apache.nutch.protocol.Content}
+ * type.</li>
+ * <li><tt>signature</tt>: Digest is used to identify pages (like unique ID) and
+ * is used to remove duplicates during the dedup procedure. It is calculated
+ * using {@link org.apache.nutch.crawl.MD5Signature} or
* {@link org.apache.nutch.crawl.TextProfileSignature}.</li>
* <li><tt>Version</tt>: From {@link org.apache.nutch.parse.ParseData}.</li>
* <li><tt>Status</tt>: From {@link org.apache.nutch.parse.ParseData}.</li>
* <li><tt>Title</tt>: of the URL</li>
* <li><tt>Outlinks</tt>: associated with the URL</li>
* <li><tt>Content Metadata</tt>: such as <i>X-AspNet-Version</i>, <i>Date</i>,
- * <i>Content-length</i>, <i>servedBy</i>, <i>Content-Type</i>, <i>Cache-Control</>, etc.</li>
+ * <i>Content-length</i>, <i>servedBy</i>, <i>Content-Type</i>,
+ * <i>Cache-Control</>, etc.</li>
* <li><tt>Parse Metadata</tt>: such as <i>CharEncodingForConversion</i>,
* <i>OriginalCharEncoding</i>, <i>language</i>, etc.</li>
- * <li><tt>ParseText</tt>: The page parse text which varies in length depdnecing on
- * <code>content.length</code> configuration.</li>
+ * <li><tt>ParseText</tt>: The page parse text which varies in length depdnecing
+ * on <code>content.length</code> configuration.</li>
* </ol>
+ *
* @author John Xing
*/
@@ -132,12 +134,13 @@ public class ParserChecker implements Tool {
Protocol protocol = factory.getProtocol(url);
Text turl = new Text(url);
ProtocolOutput output = protocol.getProtocolOutput(turl, cd);
-
+
if (!output.getStatus().isSuccess()) {
- System.err.println("Fetch failed with protocol status: " + output.getStatus());
+ System.err.println("Fetch failed with protocol status: "
+ + output.getStatus());
return (-1);
}
-
+
Content content = output.getContent();
if (content == null) {
@@ -166,11 +169,12 @@ public class ParserChecker implements Tool {
scfilters.passScoreBeforeParsing(turl, cd, content);
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score before parsing, url " + turl + " (" + e + ")");
+ LOG.warn("Couldn't pass score before parsing, url " + turl + " (" + e
+ + ")");
LOG.warn(StringUtils.stringifyException(e));
}
- }
-
+ }
+
ParseResult parseResult = new ParseUtil(conf).parse(content);
if (parseResult == null) {
@@ -179,8 +183,9 @@ public class ParserChecker implements Tool {
}
// Calculate the signature
- byte[] signature = SignatureFactory.getSignature(getConf()).calculate(content, parseResult.get(new Text(url)));
-
+ byte[] signature = SignatureFactory.getSignature(getConf()).calculate(
+ content, parseResult.get(new Text(url)));
+
if (LOG.isInfoEnabled()) {
LOG.info("parsing: " + url);
LOG.info("contentType: " + contentType);
@@ -204,7 +209,8 @@ public class ParserChecker implements Tool {
scfilters.passScoreAfterParsing(turl, content, parse);
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score after parsing, url " + turl + " (" + e + ")");
+ LOG.warn("Couldn't pass score after parsing, url " + turl + " (" + e
+ + ")");
LOG.warn(StringUtils.stringifyException(e));
}
}
diff --git a/src/java/org/apache/nutch/parse/ParserFactory.java b/src/java/org/apache/nutch/parse/ParserFactory.java
index 963d90156..0982de44c 100644
--- a/src/java/org/apache/nutch/parse/ParserFactory.java
+++ b/src/java/org/apache/nutch/parse/ParserFactory.java
@@ -38,18 +38,18 @@ import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.MimeUtil;
import org.apache.nutch.util.ObjectCache;
-
-/** Creates and caches {@link Parser} plugins.*/
+/** Creates and caches {@link Parser} plugins. */
public final class ParserFactory {
-
+
public static final Logger LOG = LoggerFactory.getLogger(ParserFactory.class);
-
+
/** Wildcard for default plugins. */
public static final String DEFAULT_PLUGIN = "*";
-
+
/** Empty extension list for caching purposes. */
- private final List<Extension> EMPTY_EXTENSION_LIST = Collections.<Extension>emptyList();
-
+ private final List<Extension> EMPTY_EXTENSION_LIST = Collections
+ .<Extension> emptyList();
+
private Configuration conf;
private ExtensionPoint extensionPoint;
private ParsePluginList parsePluginList;
@@ -57,12 +57,15 @@ public final class ParserFactory {
public ParserFactory(Configuration conf) {
this.conf = conf;
ObjectCache objectCache = ObjectCache.get(conf);
- this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(Parser.X_POINT_ID);
- this.parsePluginList = (ParsePluginList)objectCache.getObject(ParsePluginList.class.getName());
-
+ this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(
+ Parser.X_POINT_ID);
+ this.parsePluginList = (ParsePluginList) objectCache
+ .getObject(ParsePluginList.class.getName());
+
if (this.parsePluginList == null) {
this.parsePluginList = new ParsePluginsReader().parse(conf);
- objectCache.setObject(ParsePluginList.class.getName(), this.parsePluginList);
+ objectCache.setObject(ParsePluginList.class.getName(),
+ this.parsePluginList);
}
if (this.extensionPoint == null) {
@@ -72,45 +75,46 @@ public final class ParserFactory {
throw new RuntimeException(
"Parse Plugins preferences could not be loaded.");
}
- }
-
-
+ }
+
/**
* Function returns an array of {@link Parser}s for a given content type.
- *
+ *
* The function consults the internal list of parse plugins for the
- * ParserFactory to determine the list of pluginIds, then gets the
- * appropriate extension points to instantiate as {@link Parser}s.
- *
- * @param contentType The contentType to return the <code>Array</code>
- * of {@link Parser}s for.
- * @param url The url for the content that may allow us to get the type from
- * the file suffix.
+ * ParserFactory to determine the list of pluginIds, then gets the appropriate
+ * extension points to instantiate as {@link Parser}s.
+ *
+ * @param contentType
+ * The contentType to return the <code>Array</code> of {@link Parser}
+ * s for.
+ * @param url
+ * The url for the content that may allow us to get the type from the
+ * file suffix.
* @return An <code>Array</code> of {@link Parser}s for the given contentType.
* If there were plugins mapped to a contentType via the
- * <code>parse-plugins.xml</code> file, but never enabled via
- * the <code>plugin.includes</code> Nutch conf, then those plugins
- * won't be part of this array, i.e., they will be skipped.
- * So, if the ordered list of parsing plugins for
- * <code>text/plain</code> was <code>[parse-text,parse-html,
+ * <code>parse-plugins.xml</code> file, but never enabled via the
+ * <code>plugin.includes</code> Nutch conf, then those plugins won't
+ * be part of this array, i.e., they will be skipped. So, if the
+ * ordered list of parsing plugins for <code>text/plain</code> was
+ * <code>[parse-text,parse-html,
* parse-rtf]</code>, and only <code>parse-html</code> and
* <code>parse-rtf</code> were enabled via
- * <code>plugin.includes</code>, then this ordered Array would
- * consist of two {@link Parser} interfaces,
+ * <code>plugin.includes</code>, then this ordered Array would consist
+ * of two {@link Parser} interfaces,
* <code>[parse-html, parse-rtf]</code>.
*/
public Parser[] getParsers(String contentType, String url)
- throws ParserNotFound {
-
+ throws ParserNotFound {
+
List<Parser> parsers = null;
List<Extension> parserExts = null;
-
+
ObjectCache objectCache = ObjectCache.get(conf);
-
+
// TODO once the MimeTypes is available
// parsers = getExtensions(MimeUtils.map(contentType));
// if (parsers != null) {
- // return parsers;
+ // return parsers;
// }
// Last Chance: Guess content-type from file url...
// parsers = getExtensions(MimeUtils.getMimeType(url));
@@ -121,50 +125,51 @@ public final class ParserFactory {
}
parsers = new Vector<Parser>(parserExts.size());
- for (Iterator<Extension> i = parserExts.iterator(); i.hasNext(); ){
+ for (Iterator<Extension> i = parserExts.iterator(); i.hasNext();) {
Extension ext = i.next();
Parser p = null;
try {
- //check to see if we've cached this parser instance yet
+ // check to see if we've cached this parser instance yet
p = (Parser) objectCache.getObject(ext.getId());
if (p == null) {
// go ahead and instantiate it and then cache it
p = (Parser) ext.getExtensionInstance();
- objectCache.setObject(ext.getId(),p);
+ objectCache.setObject(ext.getId(), p);
}
parsers.add(p);
} catch (PluginRuntimeException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("ParserFactory:PluginRuntimeException when "
- + "initializing parser plugin "
- + ext.getDescriptor().getPluginId()
- + " instance in getParsers "
- + "function: attempting to continue instantiating parsers");
+ + "initializing parser plugin "
+ + ext.getDescriptor().getPluginId() + " instance in getParsers "
+ + "function: attempting to continue instantiating parsers");
}
}
}
- return parsers.toArray(new Parser[]{});
+ return parsers.toArray(new Parser[] {});
}
-
+
/**
* Function returns a {@link Parser} instance with the specified
- * <code>extId</code>, representing its extension ID. 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>.
+ * <code>extId</code>, representing its extension ID. 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 id The string extension ID (e.g.,
- * "org.apache.nutch.parse.rss.RSSParser",
- * "org.apache.nutch.parse.rtf.RTFParseFactory") of the {@link Parser}
- * implementation to return.
+ * @param id
+ * The string extension ID (e.g.,
+ * "org.apache.nutch.parse.rss.RSSParser",
+ * "org.apache.nutch.parse.rtf.RTFParseFactory") of the
+ * {@link Parser} implementation to return.
* @return A {@link Parser} implementation specified by the parameter
* <code>id</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}.
+ * @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 Parser getParserById(String id) throws ParserNotFound {
@@ -172,7 +177,7 @@ public final class ParserFactory {
Extension parserExt = null;
ObjectCache objectCache = ObjectCache.get(conf);
-
+
if (id != null) {
parserExt = getExtension(extensions, id);
}
@@ -183,12 +188,12 @@ public final class ParserFactory {
if (parserExt == null) {
throw new ParserNotFound("No Parser Found for id [" + id + "]");
}
-
- // first check the cache
+
+ // first check the cache
if (objectCache.getObject(parserExt.getId()) != null) {
return (Parser) objectCache.getObject(parserExt.getId());
- // if not found in cache, instantiate the Parser
+ // if not found in cache, instantiate the Parser
} else {
try {
Parser p = (Parser) parserExt.getExtensionInstance();
@@ -196,31 +201,31 @@ public final class ParserFactory {
return p;
} catch (PluginRuntimeException e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Canno initialize parser " +
- parserExt.getDescriptor().getPluginId() +
- " (cause: " + e.toString());
+ LOG.warn("Canno initialize parser "
+ + parserExt.getDescriptor().getPluginId() + " (cause: "
+ + e.toString());
}
throw new ParserNotFound("Cannot init parser for id [" + id + "]");
}
}
}
-
+
/**
* Finds the best-suited parse plugin for a given contentType.
*
- * @param contentType Content-Type for which we seek a parse plugin.
- * @return a list of extensions to be used for this contentType.
- * If none, returns <code>null</code>.
+ * @param contentType
+ * Content-Type for which we seek a parse plugin.
+ * @return a list of extensions to be used for this contentType. If none,
+ * returns <code>null</code>.
*/
@SuppressWarnings("unchecked")
protected List<Extension> getExtensions(String contentType) {
-
+
ObjectCache objectCache = ObjectCache.get(conf);
// First of all, tries to clean the content-type
String type = null;
type = MimeUtil.cleanMimeType(contentType);
-
List<Extension> extensions = (List<Extension>) objectCache.getObject(type);
// Just compare the reference:
@@ -228,100 +233,105 @@ public final class ParserFactory {
if (extensions == EMPTY_EXTENSION_LIST) {
return null;
}
-
+
if (extensions == null) {
extensions = findExtensions(type);
if (extensions != null) {
objectCache.setObject(type, extensions);
} else {
- // Put the empty extension list into cache
- // to remember we don't know any related extension.
+ // Put the empty extension list into cache
+ // to remember we don't know any related extension.
objectCache.setObject(type, EMPTY_EXTENSION_LIST);
}
}
return extensions;
}
-
+
/**
* searches a list of suitable parse plugins for the given contentType.
- * <p>It first looks for a preferred plugin defined in the parse-plugin
- * file. If none is found, it returns a list of default plugins.
+ * <p>
+ * It first looks for a preferred plugin defined in the parse-plugin file. If
+ * none is found, it returns a list of default plugins.
*
- * @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.
*/
private List<Extension> findExtensions(String contentType) {
-
+
Extension[] extensions = this.extensionPoint.getExtensions();
-
+
// Look for a preferred plugin.
- List<String> parsePluginList =
- this.parsePluginList.getPluginList(contentType);
- List<Extension> extensionList =
- matchExtensions(parsePluginList, extensions, contentType);
+ List<String> parsePluginList = this.parsePluginList
+ .getPluginList(contentType);
+ List<Extension> extensionList = matchExtensions(parsePluginList,
+ extensions, contentType);
if (extensionList != null) {
return extensionList;
}
-
+
// If none found, look for a default plugin.
parsePluginList = this.parsePluginList.getPluginList(DEFAULT_PLUGIN);
return matchExtensions(parsePluginList, extensions, DEFAULT_PLUGIN);
}
-
+
/**
* Tries to find a suitable parser for the given contentType.
* <ol>
- * <li>It checks if a parser which accepts the contentType
- * can be found in the <code>plugins</code> list;</li>
- * <li>If this list is empty, it tries to find amongst the loaded
- * extensions whether some of them might suit and warns the user.</li>
+ * <li>It checks if a parser which accepts the contentType can be found in the
+ * <code>plugins</code> list;</li>
+ * <li>If this list is empty, it tries to find amongst the loaded extensions
+ * whether some of them might suit and warns the user.</li>
* </ol>
- * @param plugins List of candidate plugins.
- * @param extensions Array of loaded extensions.
- * @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 plugins
+ * List of candidate plugins.
+ * @param extensions
+ * Array of loaded extensions.
+ * @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.
*/
private List<Extension> matchExtensions(List<String> plugins,
- Extension[] extensions,
- String contentType) {
-
+ Extension[] extensions, String contentType) {
+
List<Extension> extList = new ArrayList<Extension>();
if (plugins != null) {
-
+
for (String parsePluginId : plugins) {
-
+
Extension ext = getExtension(extensions, parsePluginId, contentType);
// the extension returned may be null
// that means that it was not enabled in the plugin.includes
// nutch conf property, but it was mapped in the
// parse-plugins.xml
- // file.
+ // file.
// OR it was enabled in plugin.includes, but the plugin's plugin.xml
// file does not claim that the plugin supports the specified mimeType
// in either case, LOG the appropriate error message to WARN level
-
+
if (ext == null) {
- //try to get it just by its pluginId
+ // try to get it just by its pluginId
ext = getExtension(extensions, parsePluginId);
-
- if (LOG.isWarnEnabled()) {
+
+ if (LOG.isWarnEnabled()) {
if (ext != null) {
// plugin was enabled via plugin.includes
// its plugin.xml just doesn't claim to support that
// particular mimeType
- LOG.warn("ParserFactory:Plugin: " + parsePluginId +
- " mapped to contentType " + contentType +
- " via parse-plugins.xml, but " + "its plugin.xml " +
- "file does not claim to support contentType: " +
- contentType);
+ LOG.warn("ParserFactory:Plugin: " + parsePluginId
+ + " mapped to contentType " + contentType
+ + " via parse-plugins.xml, but " + "its plugin.xml "
+ + "file does not claim to support contentType: "
+ + contentType);
} else {
// plugin wasn't enabled via plugin.includes
- LOG.warn("ParserFactory: Plugin: " + parsePluginId +
- " mapped to contentType " + contentType +
- " via parse-plugins.xml, but not enabled via " +
- "plugin.includes in nutch-default.xml");
+ LOG.warn("ParserFactory: Plugin: " + parsePluginId
+ + " mapped to contentType " + contentType
+ + " via parse-plugins.xml, but not enabled via "
+ + "plugin.includes in nutch-default.xml");
}
}
}
@@ -331,7 +341,7 @@ public final class ParserFactory {
extList.add(ext);
}
}
-
+
} else {
// okay, there were no list of plugins defined for
// this mimeType, however, there may be plugins registered
@@ -340,75 +350,78 @@ public final class ParserFactory {
// so, iterate through the list of extensions and if you find
// any extensions where this is the case, throw a
// NotMappedParserException
-
- for (int i=0; i<extensions.length; i++) {
- if ("*".equals(extensions[i].getAttribute("contentType"))){
+
+ for (int i = 0; i < extensions.length; i++) {
+ if ("*".equals(extensions[i].getAttribute("contentType"))) {
extList.add(0, extensions[i]);
- }
- else if (extensions[i].getAttribute("contentType") != null
- && contentType.matches(escapeContentType(extensions[i].getAttribute("contentType")))) {
+ } else if (extensions[i].getAttribute("contentType") != null
+ && contentType.matches(escapeContentType(extensions[i]
+ .getAttribute("contentType")))) {
extList.add(extensions[i]);
}
}
-
+
if (extList.size() > 0) {
if (LOG.isInfoEnabled()) {
StringBuffer extensionsIDs = new StringBuffer("[");
boolean isFirst = true;
- for (Extension ext : extList){
- if (!isFirst) extensionsIDs.append(" - ");
- else isFirst=false;
- extensionsIDs.append(ext.getId());
+ for (Extension ext : extList) {
+ if (!isFirst)
+ extensionsIDs.append(" - ");
+ else
+ isFirst = false;
+ extensionsIDs.append(ext.getId());
}
- extensionsIDs.append("]");
- LOG.info("The parsing plugins: " + extensionsIDs.toString() +
- " are enabled via the plugin.includes system " +
- "property, and all claim to support the content type " +
- contentType + ", but they are not mapped to it in the " +
- "parse-plugins.xml file");
+ extensionsIDs.append("]");
+ LOG.info("The parsing plugins: " + extensionsIDs.toString()
+ + " are enabled via the plugin.includes system "
+ + "property, and all claim to support the content type "
+ + contentType + ", but they are not mapped to it in the "
+ + "parse-plugins.xml file");
}
} else if (LOG.isDebugEnabled()) {
- LOG.debug("ParserFactory:No parse plugins mapped or enabled for " +
- "contentType " + contentType);
+ LOG.debug("ParserFactory:No parse plugins mapped or enabled for "
+ + "contentType " + contentType);
}
}
-
+
return (extList.size() > 0) ? extList : null;
}
-
+
private String escapeContentType(String contentType) {
- // Escapes contentType in order to use as a regex
- // (and keep backwards compatibility).
- // This enables to accept multiple types for a single parser.
- return contentType.replace("+", "\\+").replace(".", "\\.");
- }
+ // Escapes contentType in order to use as a regex
+ // (and keep backwards compatibility).
+ // This enables to accept multiple types for a single parser.
+ return contentType.replace("+", "\\+").replace(".", "\\.");
+ }
private boolean match(Extension extension, String id, String type) {
- return ((id.equals(extension.getId())) &&
- (extension.getAttribute("contentType").equals("*") ||
- type.matches(escapeContentType(extension.getAttribute("contentType"))) ||
- type.equals(DEFAULT_PLUGIN)));
+ return ((id.equals(extension.getId())) && (extension.getAttribute(
+ "contentType").equals("*")
+ || type
+ .matches(escapeContentType(extension.getAttribute("contentType"))) || type
+ .equals(DEFAULT_PLUGIN)));
}
-
+
/** Get an extension from its id and supported content-type. */
private Extension getExtension(Extension[] list, String id, String type) {
- for (int i=0; i<list.length; i++) {
+ for (int i = 0; i < list.length; i++) {
if (match(list[i], id, type)) {
return list[i];
}
}
return null;
}
-
+
private Extension getExtension(Extension[] list, String id) {
- for (int i=0; i<list.length; i++) {
+ for (int i = 0; i < list.length; i++) {
if (id.equals(list[i].getId())) {
return list[i];
}
}
return null;
}
-
+
private Extension getExtensionFromAlias(Extension[] list, String id) {
return getExtension(list, parsePluginList.getAliases().get(id));
}
diff --git a/src/java/org/apache/nutch/parse/ParserNotFound.java b/src/java/org/apache/nutch/parse/ParserNotFound.java
index df9ff5245..2857efa1c 100644
--- a/src/java/org/apache/nutch/parse/ParserNotFound.java
+++ b/src/java/org/apache/nutch/parse/ParserNotFound.java
@@ -18,17 +18,17 @@ package org.apache.nutch.parse;
public class ParserNotFound extends ParseException {
- private static final long serialVersionUID=23993993939L;
+ private static final long serialVersionUID = 23993993939L;
private String url;
private String contentType;
- public ParserNotFound(String message){
- super(message);
+ public ParserNotFound(String message) {
+ super(message);
}
-
+
public ParserNotFound(String url, String contentType) {
- this(url, contentType,
- "parser not found for contentType="+contentType+" url="+url);
+ this(url, contentType, "parser not found for contentType=" + contentType
+ + " url=" + url);
}
public ParserNotFound(String url, String contentType, String message) {
@@ -37,6 +37,11 @@ public class ParserNotFound extends ParseException {
this.contentType = contentType;
}
- public String getUrl() { return url; }
- public String getContentType() { return contentType; }
+ public String getUrl() {
+ return url;
+ }
+
+ public String getContentType() {
+ return contentType;
+ }
}
diff --git a/src/java/org/apache/nutch/parse/package-info.java b/src/java/org/apache/nutch/parse/package-info.java
index 16196b9fb..40bd3e24b 100644
--- a/src/java/org/apache/nutch/parse/package-info.java
+++ b/src/java/org/apache/nutch/parse/package-info.java
@@ -19,3 +19,4 @@
* The {@link org.apache.nutch.parse.Parse Parse} interface and related classes.
*/
package org.apache.nutch.parse;
+
diff --git a/src/java/org/apache/nutch/plugin/CircularDependencyException.java b/src/java/org/apache/nutch/plugin/CircularDependencyException.java
index 68049ef47..f50c11a83 100644
--- a/src/java/org/apache/nutch/plugin/CircularDependencyException.java
+++ b/src/java/org/apache/nutch/plugin/CircularDependencyException.java
@@ -16,7 +16,6 @@
*/
package org.apache.nutch.plugin;
-
/**
* <code>CircularDependencyException</code> will be thrown if a circular
* dependency is detected.
diff --git a/src/java/org/apache/nutch/plugin/Extension.java b/src/java/org/apache/nutch/plugin/Extension.java
index 0bf5d3815..de96c73d6 100644
--- a/src/java/org/apache/nutch/plugin/Extension.java
+++ b/src/java/org/apache/nutch/plugin/Extension.java
@@ -94,8 +94,10 @@ public class Extension {
* Adds a attribute and is only used until model creation at plugin system
* start up.
*
- * @param pKey a key
- * @param pValue a value
+ * @param pKey
+ * a key
+ * @param pValue
+ * a value
*/
public void addAttribute(String pKey, String pValue) {
fAttributes.put(pKey, pValue);
@@ -105,7 +107,8 @@ public class Extension {
* Sets the Class that implement the concret extension and is only used until
* model creation at system start up.
*
- * @param extensionClazz The extensionClasname to set
+ * @param extensionClazz
+ * The extensionClasname to set
*/
public void setClazz(String extensionClazz) {
fClazz = extensionClazz;
@@ -115,7 +118,8 @@ public class Extension {
* Sets the unique extension Id and is only used until model creation at
* system start up.
*
- * @param extensionID The extensionID to set
+ * @param extensionID
+ * The extensionID to set
*/
public void setId(String extensionID) {
fId = extensionID;
@@ -147,10 +151,10 @@ public class Extension {
// The same is in PluginRepository.getPluginInstance().
// Suggested by Stefan Groschupf <[email protected]>
synchronized (getId()) {
- try {
+ try {
PluginRepository pluginRepository = PluginRepository.get(conf);
- Class extensionClazz =
- pluginRepository.getCachedClass(fDescriptor, getClazz());
+ Class extensionClazz = pluginRepository.getCachedClass(fDescriptor,
+ getClazz());
// lazy loading of Plugin in case there is no instance of the plugin
// already.
pluginRepository.getPluginInstance(getDescriptor());
diff --git a/src/java/org/apache/nutch/plugin/ExtensionPoint.java b/src/java/org/apache/nutch/plugin/ExtensionPoint.java
index a6e8f7987..1200e4f90 100644
--- a/src/java/org/apache/nutch/plugin/ExtensionPoint.java
+++ b/src/java/org/apache/nutch/plugin/ExtensionPoint.java
@@ -15,6 +15,7 @@
* limitations under the License.
*/
package org.apache.nutch.plugin;
+
import java.util.ArrayList;
/**
@@ -76,7 +77,8 @@ public class ExtensionPoint {
/**
* Sets the extensionPointId.
*
- * @param pId extension point id
+ * @param pId
+ * extension point id
*/
private void setId(String pId) {
ftId = pId;
diff --git a/src/java/org/apache/nutch/plugin/MissingDependencyException.java b/src/java/org/apache/nutch/plugin/MissingDependencyException.java
index 928e0df45..b81cc5096 100644
--- a/src/java/org/apache/nutch/plugin/MissingDependencyException.java
+++ b/src/java/org/apache/nutch/plugin/MissingDependencyException.java
@@ -17,8 +17,8 @@
package org.apache.nutch.plugin;
/**
- * <code>MissingDependencyException</code> will be thrown if a plugin
- * dependency cannot be found.
+ * <code>MissingDependencyException</code> will be thrown if a plugin dependency
+ * cannot be found.
*
* @author J&eacute;r&ocirc;me Charron
*/
diff --git a/src/java/org/apache/nutch/plugin/Pluggable.java b/src/java/org/apache/nutch/plugin/Pluggable.java
index 9d99ecb4f..09aba300e 100644
--- a/src/java/org/apache/nutch/plugin/Pluggable.java
+++ b/src/java/org/apache/nutch/plugin/Pluggable.java
@@ -17,16 +17,15 @@
package org.apache.nutch.plugin;
/**
- * Defines the capability of a class to be plugged into Nutch.
- * This is a common interface that must be implemented by all
- * Nutch Extension Points.
- *
+ * Defines the capability of a class to be plugged into Nutch. This is a common
+ * interface that must be implemented by all Nutch Extension Points.
+ *
* @author J&eacute;r&ocirc;me Charron
- *
+ *
* @see <a href="http://wiki.apache.org/nutch/AboutPlugins">About Plugins</a>
- * @see <a href="package-summary.html#package_description">
- * plugin package description</a>
+ * @see <a href="package-summary.html#package_description"> plugin package
+ * description</a>
*/
public interface Pluggable {
-
+
}
diff --git a/src/java/org/apache/nutch/plugin/Plugin.java b/src/java/org/apache/nutch/plugin/Plugin.java
index d62b6ddcb..e78754b8a 100644
--- a/src/java/org/apache/nutch/plugin/Plugin.java
+++ b/src/java/org/apache/nutch/plugin/Plugin.java
@@ -33,8 +33,8 @@ import org.apache.hadoop.conf.Configuration;
* The <code>Plugin</code> will be startuped and shutdown by the nutch plugin
* management system.
*
- * A possible usecase of the <code>Plugin</code> implementation is to create
- * or close a database connection.
+ * A possible usecase of the <code>Plugin</code> implementation is to create or
+ * close a database connection.
*
* @author joa23
*/
@@ -81,7 +81,8 @@ public class Plugin {
}
/**
- * @param descriptor The descriptor to set
+ * @param descriptor
+ * The descriptor to set
*/
private void setDescriptor(PluginDescriptor descriptor) {
fDescriptor = descriptor;
diff --git a/src/java/org/apache/nutch/plugin/PluginClassLoader.java b/src/java/org/apache/nutch/plugin/PluginClassLoader.java
index 35f9a3fab..128bbc63f 100644
--- a/src/java/org/apache/nutch/plugin/PluginClassLoader.java
+++ b/src/java/org/apache/nutch/plugin/PluginClassLoader.java
@@ -45,11 +45,11 @@ public class PluginClassLoader extends URLClassLoader {
*/
public PluginClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
-
+
this.urls = urls;
this.parent = parent;
}
-
+
@Override
public int hashCode() {
final int PRIME = 31;
diff --git a/src/java/org/apache/nutch/plugin/PluginDescriptor.java b/src/java/org/apache/nutch/plugin/PluginDescriptor.java
index 2c6ae2b17..0a43745ff 100644
--- a/src/java/org/apache/nutch/plugin/PluginDescriptor.java
+++ b/src/java/org/apache/nutch/plugin/PluginDescriptor.java
@@ -31,12 +31,11 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
/**
- * The <code>PluginDescriptor</code> provide access to all meta information of
- * a nutch-plugin, as well to the internationalizable resources and the plugin
- * own classloader. There are meta information about <code>Plugin</code>,
- * <code>ExtensionPoint</code> and <code>Extension</code>. To provide
- * access to the meta data of a plugin via a descriptor allow a lazy loading
- * mechanism.
+ * The <code>PluginDescriptor</code> provide access to all meta information of a
+ * nutch-plugin, as well to the internationalizable resources and the plugin own
+ * classloader. There are meta information about <code>Plugin</code>,
+ * <code>ExtensionPoint</code> and <code>Extension</code>. To provide access to
+ * the meta data of a plugin via a descriptor allow a lazy loading mechanism.
*/
public class PluginDescriptor {
private String fPluginPath;
@@ -52,7 +51,8 @@ public class PluginDescriptor {
private ArrayList<URL> fNotExportedLibs = new ArrayList<URL>();
private ArrayList<Extension> fExtensions = new ArrayList<Extension>();
private PluginClassLoader fClassLoader;
- public static final Logger LOG = LoggerFactory.getLogger(PluginDescriptor.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(PluginDescriptor.class);
private Configuration fConf;
/**
@@ -205,18 +205,19 @@ public class PluginDescriptor {
/**
* Adds a dependency
*
- * @param pId id of the dependent plugin
+ * @param pId
+ * id of the dependent plugin
*/
public void addDependency(String pId) {
fDependencies.add(pId);
}
/**
- * Adds a exported library with a relative path to the plugin directory.
- * We automatically escape characters that are illegal in URLs. It is
- * recommended that code converts an abstract pathname into a URL by
- * first converting it into a URI, via the toURI method, and then
- * converting the URI into a URL via the URI.toURL method.
+ * Adds a exported library with a relative path to the plugin directory. We
+ * automatically escape characters that are illegal in URLs. It is recommended
+ * that code converts an abstract pathname into a URL by first converting it
+ * into a URI, via the toURI method, and then converting the URI into a URL
+ * via the URI.toURL method.
*
* @param pLibPath
*/
@@ -246,11 +247,11 @@ public class PluginDescriptor {
}
/**
- * Adds a exported library with a relative path to the plugin directory.
- * We automatically escape characters that are illegal in URLs. It is
- * recommended that code converts an abstract pathname into a URL by
- * first converting it into a URI, via the toURI method, and then
- * converting the URI into a URL via the URI.toURL method.
+ * Adds a exported library with a relative path to the plugin directory. We
+ * automatically escape characters that are illegal in URLs. It is recommended
+ * that code converts an abstract pathname into a URL by first converting it
+ * into a URI, via the toURI method, and then converting the URI into a URL
+ * via the URI.toURL method.
*
* @param pLibPath
*/
@@ -294,8 +295,8 @@ public class PluginDescriptor {
LOG.debug(getPluginId() + " " + e.toString());
}
URL[] urls = arrayList.toArray(new URL[arrayList.size()]);
- fClassLoader = new PluginClassLoader(urls, PluginDescriptor.class
- .getClassLoader());
+ fClassLoader = new PluginClassLoader(urls,
+ PluginDescriptor.class.getClassLoader());
return fClassLoader;
}
@@ -317,7 +318,7 @@ public class PluginDescriptor {
for (String id : pDescriptor.getDependencies()) {
PluginDescriptor descriptor = PluginRepository.get(fConf)
.getPluginDescriptor(id);
- for (URL url: descriptor.getExportedLibUrls()) {
+ for (URL url : descriptor.getExportedLibUrls()) {
pLibs.add(url);
}
collectLibs(pLibs, descriptor);
diff --git a/src/java/org/apache/nutch/plugin/PluginManifestParser.java b/src/java/org/apache/nutch/plugin/PluginManifestParser.java
index 7059cbfc0..3d9fbd061 100644
--- a/src/java/org/apache/nutch/plugin/PluginManifestParser.java
+++ b/src/java/org/apache/nutch/plugin/PluginManifestParser.java
@@ -40,8 +40,8 @@ import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
- * The <code>PluginManifestParser</code> parser just parse the manifest file
- * in all plugin directories.
+ * The <code>PluginManifestParser</code> parser just parse the manifest file in
+ * all plugin directories.
*
* @author joa23
*/
@@ -94,7 +94,8 @@ public class PluginManifestParser {
PluginDescriptor p = parseManifestFile(manifestPath);
map.put(p.getPluginId(), p);
} catch (Exception e) {
- LOG.warn("Error while loading plugin `" + manifestPath + "` " + e.toString());
+ LOG.warn("Error while loading plugin `" + manifestPath + "` "
+ + e.toString());
}
}
}
@@ -183,7 +184,7 @@ public class PluginManifestParser {
PluginDescriptor pluginDescriptor = new PluginDescriptor(id, version, name,
providerName, pluginClazz, pPath, this.conf);
LOG.debug("plugin: id=" + id + " name=" + name + " version=" + version
- + " provider=" + providerName + "class=" + pluginClazz);
+ + " provider=" + providerName + "class=" + pluginClazz);
parseExtension(rootElement, pluginDescriptor);
parseExtensionPoints(rootElement, pluginDescriptor);
parseLibraries(rootElement, pluginDescriptor);
@@ -290,8 +291,8 @@ public class PluginManifestParser {
if (parameters != null) {
for (int k = 0; k < parameters.getLength(); k++) {
Element param = (Element) parameters.item(k);
- extension.addAttribute(param.getAttribute(ATTR_NAME), param
- .getAttribute("value"));
+ extension.addAttribute(param.getAttribute(ATTR_NAME),
+ param.getAttribute("value"));
}
}
pPluginDescriptor.addExtension(extension);
diff --git a/src/java/org/apache/nutch/plugin/PluginRepository.java b/src/java/org/apache/nutch/plugin/PluginRepository.java
index 0c272a59d..3e193454e 100644
--- a/src/java/org/apache/nutch/plugin/PluginRepository.java
+++ b/src/java/org/apache/nutch/plugin/PluginRepository.java
@@ -53,13 +53,13 @@ public class PluginRepository {
private HashMap<String, ExtensionPoint> fExtensionPoints;
private HashMap<String, Plugin> fActivatedPlugins;
-
- private static final Map<String, Map<PluginClassLoader, Class>> CLASS_CACHE =
- new HashMap<String, Map<PluginClassLoader,Class>>();
+
+ private static final Map<String, Map<PluginClassLoader, Class>> CLASS_CACHE = new HashMap<String, Map<PluginClassLoader, Class>>();
private Configuration conf;
- public static final Logger LOG = LoggerFactory.getLogger(PluginRepository.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(PluginRepository.class);
/**
* @throws PluginRuntimeException
@@ -71,7 +71,8 @@ public class PluginRepository {
this.conf = new Configuration(conf);
this.auto = conf.getBoolean("plugin.auto-activation", true);
String[] pluginFolders = conf.getStrings("plugin.folders");
- PluginManifestParser manifestParser = new PluginManifestParser(this.conf, this);
+ PluginManifestParser manifestParser = new PluginManifestParser(this.conf,
+ this);
Map<String, PluginDescriptor> allPlugins = manifestParser
.parsePluginFolder(pluginFolders);
if (allPlugins.isEmpty()) {
@@ -88,7 +89,7 @@ public class PluginRepository {
try {
installExtensions(fRegisteredPlugins);
} catch (PluginRuntimeException e) {
- LOG.error(e.toString());
+ LOG.error(e.toString());
throw new RuntimeException(e.getMessage());
}
displayStatus();
@@ -115,8 +116,8 @@ public class PluginRepository {
return;
}
- for (PluginDescriptor plugin: plugins) {
- for(ExtensionPoint point:plugin.getExtenstionPoints()) {
+ for (PluginDescriptor plugin : plugins) {
+ for (ExtensionPoint point : plugin.getExtenstionPoints()) {
String xpId = point.getId();
LOG.debug("Adding extension point " + xpId);
fExtensionPoints.put(xpId, point);
@@ -131,7 +132,7 @@ public class PluginRepository {
throws PluginRuntimeException {
for (PluginDescriptor descriptor : pRegisteredPlugins) {
- for(Extension extension:descriptor.getExtensions()) {
+ for (Extension extension : descriptor.getExtensions()) {
String xpId = extension.getTargetPoint();
ExtensionPoint point = getExtensionPoint(xpId);
if (point == null) {
@@ -159,7 +160,7 @@ public class PluginRepository {
branch.put(plugin.getPluginId(), plugin);
// Otherwise, checks each dependency
- for(String id:plugin.getDependencies()) {
+ for (String id : plugin.getDependencies()) {
PluginDescriptor dependency = plugins.get(id);
if (dependency == null) {
throw new MissingDependencyException("Missing dependency " + id
@@ -274,7 +275,8 @@ public class PluginRepository {
// The same is in Extension.getExtensionInstance().
// Suggested by Stefan Groschupf <[email protected]>
synchronized (pDescriptor) {
- Class<?> pluginClass = getCachedClass(pDescriptor, pDescriptor.getPluginClass());
+ Class<?> pluginClass = getCachedClass(pDescriptor,
+ pDescriptor.getPluginClass());
Constructor<?> constructor = pluginClass.getConstructor(new Class<?>[] {
PluginDescriptor.class, Configuration.class });
Plugin plugin = (Plugin) constructor.newInstance(new Object[] {
@@ -315,9 +317,9 @@ public class PluginRepository {
plugin.shutDown();
}
}
-
+
public Class getCachedClass(PluginDescriptor pDescriptor, String className)
- throws ClassNotFoundException {
+ throws ClassNotFoundException {
Map<PluginClassLoader, Class> descMap = CLASS_CACHE.get(className);
if (descMap == null) {
descMap = new HashMap<PluginClassLoader, Class>();
@@ -396,7 +398,7 @@ public class PluginRepository {
}
return map;
}
-
+
/**
* Get ordered list of plugins. Filter and normalization plugins are applied
* in a configurable "pipeline" order, e.g., if one plugin depends on the
@@ -412,8 +414,8 @@ public class PluginRepository {
* property name defining plugin order
* @return array of plugin instances
*/
- public synchronized Object[] getOrderedPlugins(Class<?> clazz, String xPointId,
- String orderProperty) {
+ public synchronized Object[] getOrderedPlugins(Class<?> clazz,
+ String xPointId, String orderProperty) {
Object[] filters;
ObjectCache objectCache = ObjectCache.get(conf);
filters = (Object[]) objectCache.getObject(clazz.getName());
diff --git a/src/java/org/apache/nutch/plugin/PluginRuntimeException.java b/src/java/org/apache/nutch/plugin/PluginRuntimeException.java
index 22194e47a..acccda25f 100644
--- a/src/java/org/apache/nutch/plugin/PluginRuntimeException.java
+++ b/src/java/org/apache/nutch/plugin/PluginRuntimeException.java
@@ -16,6 +16,7 @@
* limitations under the License.
*/
package org.apache.nutch.plugin;
+
/**
* <code>PluginRuntimeException</code> will be thrown until a exception in the
* plugin managemnt occurs.
diff --git a/src/java/org/apache/nutch/protocol/Content.java b/src/java/org/apache/nutch/protocol/Content.java
index 11ac4c6d8..4dc8277b0 100755
--- a/src/java/org/apache/nutch/protocol/Content.java
+++ b/src/java/org/apache/nutch/protocol/Content.java
@@ -42,7 +42,7 @@ import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.util.MimeUtil;
import org.apache.nutch.util.NutchConfiguration;
-public final class Content implements Writable{
+public final class Content implements Writable {
public static final String DIR_NAME = "content";
@@ -121,11 +121,11 @@ public final class Content implements Writable{
metadata.readFields(in); // read meta data
break;
default:
- throw new VersionMismatchException((byte)2, oldVersion);
+ throw new VersionMismatchException((byte) 2, oldVersion);
}
}
-
+
public final void readFields(DataInput in) throws IOException {
metadata.clear();
int sizeOrVersion = in.readInt();
@@ -143,14 +143,14 @@ public final class Content implements Writable{
metadata.readFields(in);
break;
default:
- throw new VersionMismatchException((byte)VERSION, (byte)version);
+ throw new VersionMismatchException((byte) VERSION, (byte) version);
}
} else { // size
byte[] compressed = new byte[sizeOrVersion];
in.readFully(compressed, 0, compressed.length);
ByteArrayInputStream deflated = new ByteArrayInputStream(compressed);
- DataInput inflater =
- new DataInputStream(new InflaterInputStream(deflated));
+ DataInput inflater = new DataInputStream(
+ new InflaterInputStream(deflated));
readFieldsCompressed(inflater);
}
}
@@ -184,8 +184,9 @@ public final class Content implements Writable{
return url;
}
- /** The base url for relative links contained in the content.
- * Maybe be different from url if the request redirected.
+ /**
+ * The base url for relative links contained in the content. Maybe be
+ * different from url if the request redirected.
*/
public String getBaseUrl() {
return base;
@@ -200,7 +201,9 @@ public final class Content implements Writable{
this.content = content;
}
- /** The media type of the retrieved content.
+ /**
+ * The media type of the retrieved content.
+ *
* @see <a href="http://www.iana.org/assignments/media-types/">
* http://www.iana.org/assignments/media-types/</a>
*/
@@ -258,13 +261,12 @@ public final class Content implements Writable{
}
Options opts = new Options();
Configuration conf = NutchConfiguration.create();
-
- GenericOptionsParser parser =
- new GenericOptionsParser(conf, opts, argv);
-
+
+ GenericOptionsParser parser = new GenericOptionsParser(conf, opts, argv);
+
String[] remainingArgs = parser.getRemainingArgs();
FileSystem fs = FileSystem.get(conf);
-
+
try {
int recno = Integer.parseInt(remainingArgs[0]);
String segment = remainingArgs[1];
diff --git a/src/java/org/apache/nutch/protocol/Protocol.java b/src/java/org/apache/nutch/protocol/Protocol.java
index eb5bb3895..0aa5d297f 100755
--- a/src/java/org/apache/nutch/protocol/Protocol.java
+++ b/src/java/org/apache/nutch/protocol/Protocol.java
@@ -27,12 +27,11 @@ import org.apache.nutch.plugin.Pluggable;
import crawlercommons.robots.BaseRobotRules;
-
/** A retriever of url content. Implemented by protocol extensions. */
public interface Protocol extends Pluggable, Configurable {
/** The name of the extension point. */
public final static String X_POINT_ID = Protocol.class.getName();
-
+
/**
* Property name. If in the current configuration this property is set to
* true, protocol implementations should handle "politeness" limits
@@ -51,16 +50,19 @@ public interface Protocol extends Pluggable, Configurable {
*/
public final static String CHECK_ROBOTS = "protocol.plugin.check.robots";
- /** Returns the {@link Content} for a fetchlist entry.
+ /**
+ * Returns the {@link Content} for a fetchlist entry.
*/
ProtocolOutput getProtocolOutput(Text url, CrawlDatum datum);
/**
* Retrieve robot rules applicable for this url.
- * @param url url to check
- * @param datum page datum
+ *
+ * @param url
+ * url to check
+ * @param datum
+ * page datum
* @return robot rules (specific for this url or default), never null
*/
BaseRobotRules getRobotRules(Text url, CrawlDatum datum);
}
-
diff --git a/src/java/org/apache/nutch/protocol/ProtocolFactory.java b/src/java/org/apache/nutch/protocol/ProtocolFactory.java
index 578f626a7..8a92d60b5 100644
--- a/src/java/org/apache/nutch/protocol/ProtocolFactory.java
+++ b/src/java/org/apache/nutch/protocol/ProtocolFactory.java
@@ -37,7 +37,8 @@ import org.apache.hadoop.conf.Configuration;
*/
public class ProtocolFactory {
- public static final Logger LOG = LoggerFactory.getLogger(ProtocolFactory.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(ProtocolFactory.class);
private ExtensionPoint extensionPoint;
diff --git a/src/java/org/apache/nutch/protocol/ProtocolNotFound.java b/src/java/org/apache/nutch/protocol/ProtocolNotFound.java
index f9f7d49e4..8cadc238e 100644
--- a/src/java/org/apache/nutch/protocol/ProtocolNotFound.java
+++ b/src/java/org/apache/nutch/protocol/ProtocolNotFound.java
@@ -22,7 +22,7 @@ public class ProtocolNotFound extends ProtocolException {
private String url;
public ProtocolNotFound(String url) {
- this(url, "protocol not found for url="+url);
+ this(url, "protocol not found for url=" + url);
}
public ProtocolNotFound(String url, String message) {
@@ -30,5 +30,7 @@ public class ProtocolNotFound extends ProtocolException {
this.url = url;
}
- public String getUrl() { return url; }
+ public String getUrl() {
+ return url;
+ }
}
diff --git a/src/java/org/apache/nutch/protocol/ProtocolOutput.java b/src/java/org/apache/nutch/protocol/ProtocolOutput.java
index 21ca1012d..c7f0c2c48 100644
--- a/src/java/org/apache/nutch/protocol/ProtocolOutput.java
+++ b/src/java/org/apache/nutch/protocol/ProtocolOutput.java
@@ -18,8 +18,9 @@
package org.apache.nutch.protocol;
/**
- * Simple aggregate to pass from protocol plugins both content and
- * protocol status.
+ * Simple aggregate to pass from protocol plugins both content and protocol
+ * status.
+ *
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
public class ProtocolOutput {
@@ -30,12 +31,12 @@ public class ProtocolOutput {
this.content = content;
this.status = status;
}
-
+
public ProtocolOutput(Content content) {
this.content = content;
this.status = ProtocolStatus.STATUS_SUCCESS;
}
-
+
public Content getContent() {
return content;
}
diff --git a/src/java/org/apache/nutch/protocol/ProtocolStatus.java b/src/java/org/apache/nutch/protocol/ProtocolStatus.java
index 156c7fed6..476039325 100644
--- a/src/java/org/apache/nutch/protocol/ProtocolStatus.java
+++ b/src/java/org/apache/nutch/protocol/ProtocolStatus.java
@@ -30,65 +30,76 @@ import org.apache.hadoop.io.WritableUtils;
* @author Andrzej Bialecki
*/
public class ProtocolStatus implements Writable {
-
+
private final static byte VERSION = 2;
-
+
/** Content was retrieved without errors. */
- public static final int SUCCESS = 1;
+ public static final int SUCCESS = 1;
/** Content was not retrieved. Any further errors may be indicated in args. */
- public static final int FAILED = 2;
-
- /** This protocol was not found. Application may attempt to retry later. */
- public static final int PROTO_NOT_FOUND = 10;
+ public static final int FAILED = 2;
+
+ /** This protocol was not found. Application may attempt to retry later. */
+ public static final int PROTO_NOT_FOUND = 10;
/** Resource is gone. */
- public static final int GONE = 11;
+ public static final int GONE = 11;
/** Resource has moved permanently. New url should be found in args. */
- public static final int MOVED = 12;
+ public static final int MOVED = 12;
/** Resource has moved temporarily. New url should be found in args. */
- public static final int TEMP_MOVED = 13;
+ public static final int TEMP_MOVED = 13;
/** Resource was not found. */
- public static final int NOTFOUND = 14;
+ public static final int NOTFOUND = 14;
/** Temporary failure. Application may retry immediately. */
- public static final int RETRY = 15;
- /** Unspecified exception occured. Further information may be provided in args. */
- public static final int EXCEPTION = 16;
+ public static final int RETRY = 15;
+ /**
+ * Unspecified exception occured. Further information may be provided in args.
+ */
+ public static final int EXCEPTION = 16;
/** Access denied - authorization required, but missing/incorrect. */
- public static final int ACCESS_DENIED = 17;
+ public static final int ACCESS_DENIED = 17;
/** Access denied by robots.txt rules. */
- public static final int ROBOTS_DENIED = 18;
+ public static final int ROBOTS_DENIED = 18;
/** Too many redirects. */
- public static final int REDIR_EXCEEDED = 19;
+ public static final int REDIR_EXCEEDED = 19;
/** Not fetching. */
- public static final int NOTFETCHING = 20;
+ public static final int NOTFETCHING = 20;
/** Unchanged since the last fetch. */
- public static final int NOTMODIFIED = 21;
- /** Request was refused by protocol plugins, because it would block.
- * The expected number of milliseconds to wait before retry may be provided
- * in args. */
- public static final int WOULDBLOCK = 22;
+ public static final int NOTMODIFIED = 21;
+ /**
+ * Request was refused by protocol plugins, because it would block. The
+ * expected number of milliseconds to wait before retry may be provided in
+ * args.
+ */
+ public static final int WOULDBLOCK = 22;
/** Thread was blocked http.max.delays times during fetching. */
- public static final int BLOCKED = 23;
-
+ public static final int BLOCKED = 23;
+
// Useful static instances for status codes that don't usually require any
// additional arguments.
- public static final ProtocolStatus STATUS_SUCCESS = new ProtocolStatus(SUCCESS);
+ public static final ProtocolStatus STATUS_SUCCESS = new ProtocolStatus(
+ SUCCESS);
public static final ProtocolStatus STATUS_FAILED = new ProtocolStatus(FAILED);
public static final ProtocolStatus STATUS_GONE = new ProtocolStatus(GONE);
- public static final ProtocolStatus STATUS_NOTFOUND = new ProtocolStatus(NOTFOUND);
+ public static final ProtocolStatus STATUS_NOTFOUND = new ProtocolStatus(
+ NOTFOUND);
public static final ProtocolStatus STATUS_RETRY = new ProtocolStatus(RETRY);
- public static final ProtocolStatus STATUS_ROBOTS_DENIED = new ProtocolStatus(ROBOTS_DENIED);
- public static final ProtocolStatus STATUS_REDIR_EXCEEDED = new ProtocolStatus(REDIR_EXCEEDED);
- public static final ProtocolStatus STATUS_NOTFETCHING = new ProtocolStatus(NOTFETCHING);
- public static final ProtocolStatus STATUS_NOTMODIFIED = new ProtocolStatus(NOTMODIFIED);
- public static final ProtocolStatus STATUS_WOULDBLOCK = new ProtocolStatus(WOULDBLOCK);
- public static final ProtocolStatus STATUS_BLOCKED = new ProtocolStatus(BLOCKED);
-
+ public static final ProtocolStatus STATUS_ROBOTS_DENIED = new ProtocolStatus(
+ ROBOTS_DENIED);
+ public static final ProtocolStatus STATUS_REDIR_EXCEEDED = new ProtocolStatus(
+ REDIR_EXCEEDED);
+ public static final ProtocolStatus STATUS_NOTFETCHING = new ProtocolStatus(
+ NOTFETCHING);
+ public static final ProtocolStatus STATUS_NOTMODIFIED = new ProtocolStatus(
+ NOTMODIFIED);
+ public static final ProtocolStatus STATUS_WOULDBLOCK = new ProtocolStatus(
+ WOULDBLOCK);
+ public static final ProtocolStatus STATUS_BLOCKED = new ProtocolStatus(
+ BLOCKED);
+
private int code;
private long lastModified;
private String[] args;
-
- private static final HashMap<Integer, String> codeToName =
- new HashMap<Integer, String>();
+
+ private static final HashMap<Integer, String> codeToName = new HashMap<Integer, String>();
static {
codeToName.put(new Integer(SUCCESS), "success");
codeToName.put(new Integer(FAILED), "failed");
@@ -107,40 +118,41 @@ public class ProtocolStatus implements Writable {
codeToName.put(new Integer(WOULDBLOCK), "wouldblock");
codeToName.put(new Integer(BLOCKED), "blocked");
}
-
+
public ProtocolStatus() {
-
+
}
public ProtocolStatus(int code, String[] args) {
this.code = code;
this.args = args;
}
-
+
public ProtocolStatus(int code, String[] args, long lastModified) {
this.code = code;
this.args = args;
this.lastModified = lastModified;
}
-
+
public ProtocolStatus(int code) {
this(code, null);
}
-
+
public ProtocolStatus(int code, long lastModified) {
this(code, null, lastModified);
}
-
+
public ProtocolStatus(int code, Object message) {
this(code, message, 0L);
}
-
+
public ProtocolStatus(int code, Object message, long lastModified) {
this.code = code;
this.lastModified = lastModified;
- if (message != null) this.args = new String[]{String.valueOf(message)};
+ if (message != null)
+ this.args = new String[] { String.valueOf(message) };
}
-
+
public ProtocolStatus(Throwable t) {
this(EXCEPTION, t);
}
@@ -150,10 +162,10 @@ public class ProtocolStatus implements Writable {
res.readFields(in);
return res;
}
-
+
public void readFields(DataInput in) throws IOException {
byte version = in.readByte();
- switch(version) {
+ switch (version) {
case 1:
code = in.readByte();
lastModified = in.readLong();
@@ -168,10 +180,10 @@ public class ProtocolStatus implements Writable {
throw new VersionMismatchException(VERSION, version);
}
}
-
+
public void write(DataOutput out) throws IOException {
out.writeByte(VERSION);
- out.writeByte((byte)code);
+ out.writeByte((byte) code);
out.writeLong(lastModified);
if (args == null) {
out.writeInt(-1);
@@ -183,7 +195,7 @@ public class ProtocolStatus implements Writable {
public void setArgs(String[] args) {
this.args = args;
}
-
+
public String[] getArgs() {
return args;
}
@@ -195,74 +207,77 @@ public class ProtocolStatus implements Writable {
public String getName() {
return codeToName.get(this.code);
}
-
+
public void setCode(int code) {
this.code = code;
}
-
+
public boolean isSuccess() {
- return code == SUCCESS;
+ return code == SUCCESS;
}
-
+
public boolean isTransientFailure() {
- return
- code == ACCESS_DENIED ||
- code == EXCEPTION ||
- code == REDIR_EXCEEDED ||
- code == RETRY ||
- code == TEMP_MOVED ||
- code == WOULDBLOCK ||
- code == PROTO_NOT_FOUND;
+ return code == ACCESS_DENIED || code == EXCEPTION || code == REDIR_EXCEEDED
+ || code == RETRY || code == TEMP_MOVED || code == WOULDBLOCK
+ || code == PROTO_NOT_FOUND;
}
-
+
public boolean isPermanentFailure() {
- return
- code == FAILED ||
- code == GONE ||
- code == MOVED ||
- code == NOTFOUND ||
- code == ROBOTS_DENIED;
+ return code == FAILED || code == GONE || code == MOVED || code == NOTFOUND
+ || code == ROBOTS_DENIED;
}
-
+
public String getMessage() {
- if (args != null && args.length > 0) return args[0];
+ if (args != null && args.length > 0)
+ return args[0];
return null;
}
-
+
public void setMessage(String msg) {
- if (args != null && args.length > 0) args[0] = msg;
- else args = new String[] {msg};
+ if (args != null && args.length > 0)
+ args[0] = msg;
+ else
+ args = new String[] { msg };
}
-
+
public long getLastModified() {
return lastModified;
}
-
+
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
-
+
public boolean equals(Object o) {
- if (o == null) return false;
- if (!(o instanceof ProtocolStatus)) return false;
- ProtocolStatus other = (ProtocolStatus)o;
- if (this.code != other.code || this.lastModified != other.lastModified) return false;
+ if (o == null)
+ return false;
+ if (!(o instanceof ProtocolStatus))
+ return false;
+ ProtocolStatus other = (ProtocolStatus) o;
+ if (this.code != other.code || this.lastModified != other.lastModified)
+ return false;
if (this.args == null) {
- if (other.args == null) return true;
- else return false;
+ if (other.args == null)
+ return true;
+ else
+ return false;
} else {
- if (other.args == null) return false;
- if (other.args.length != this.args.length) return false;
+ if (other.args == null)
+ return false;
+ if (other.args.length != this.args.length)
+ return false;
for (int i = 0; i < this.args.length; i++) {
- if (!this.args[i].equals(other.args[i])) return false;
+ if (!this.args[i].equals(other.args[i]))
+ return false;
}
}
return true;
}
-
+
public String toString() {
StringBuffer res = new StringBuffer();
- res.append(codeToName.get(new Integer(code)) + "(" + code + "), lastModified=" + lastModified);
+ res.append(codeToName.get(new Integer(code)) + "(" + code
+ + "), lastModified=" + lastModified);
if (args != null) {
if (args.length == 1) {
res.append(": " + String.valueOf(args[0]));
diff --git a/src/java/org/apache/nutch/protocol/RobotRules.java b/src/java/org/apache/nutch/protocol/RobotRules.java
index 8695c6d56..dbf72bafe 100644
--- a/src/java/org/apache/nutch/protocol/RobotRules.java
+++ b/src/java/org/apache/nutch/protocol/RobotRules.java
@@ -35,9 +35,8 @@ public interface RobotRules {
public long getCrawlDelay();
/**
- * Returns <code>false</code> if the <code>robots.txt</code> file
- * prohibits us from accessing the given <code>url</code>, or
- * <code>true</code> otherwise.
+ * Returns <code>false</code> if the <code>robots.txt</code> file prohibits us
+ * from accessing the given <code>url</code>, or <code>true</code> otherwise.
*/
public boolean isAllowed(URL url);
diff --git a/src/java/org/apache/nutch/protocol/RobotRulesParser.java b/src/java/org/apache/nutch/protocol/RobotRulesParser.java
index bf29661a3..d6b2364db 100644
--- a/src/java/org/apache/nutch/protocol/RobotRulesParser.java
+++ b/src/java/org/apache/nutch/protocol/RobotRulesParser.java
@@ -43,35 +43,38 @@ import crawlercommons.robots.SimpleRobotRules.RobotRulesMode;
import crawlercommons.robots.SimpleRobotRulesParser;
/**
- * This class uses crawler-commons for handling the parsing of {@code robots.txt} files.
- * It emits SimpleRobotRules objects, which describe the download permissions
- * as described in SimpleRobotRulesParser.
+ * This class uses crawler-commons for handling the parsing of
+ * {@code robots.txt} files. It emits SimpleRobotRules objects, which describe
+ * the download permissions as described in SimpleRobotRulesParser.
*/
public abstract class RobotRulesParser implements Configurable {
- public static final Logger LOG = LoggerFactory.getLogger(RobotRulesParser.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(RobotRulesParser.class);
- protected static final Hashtable<String, BaseRobotRules> CACHE = new Hashtable<String, BaseRobotRules> ();
+ protected static final Hashtable<String, BaseRobotRules> CACHE = new Hashtable<String, BaseRobotRules>();
/**
- * A {@link BaseRobotRules} object appropriate for use
- * when the {@code robots.txt} file is empty or missing;
- * all requests are allowed.
+ * A {@link BaseRobotRules} object appropriate for use when the
+ * {@code robots.txt} file is empty or missing; all requests are allowed.
*/
- public static final BaseRobotRules EMPTY_RULES = new SimpleRobotRules(RobotRulesMode.ALLOW_ALL);
+ public static final BaseRobotRules EMPTY_RULES = new SimpleRobotRules(
+ RobotRulesMode.ALLOW_ALL);
/**
- * A {@link BaseRobotRules} object appropriate for use when the
- * {@code robots.txt} file is not fetched due to a {@code 403/Forbidden}
- * response; all requests are disallowed.
+ * A {@link BaseRobotRules} object appropriate for use when the
+ * {@code robots.txt} file is not fetched due to a {@code 403/Forbidden}
+ * response; all requests are disallowed.
*/
- public static BaseRobotRules FORBID_ALL_RULES = new SimpleRobotRules(RobotRulesMode.ALLOW_NONE);
+ public static BaseRobotRules FORBID_ALL_RULES = new SimpleRobotRules(
+ RobotRulesMode.ALLOW_NONE);
private static SimpleRobotRulesParser robotParser = new SimpleRobotRulesParser();
private Configuration conf;
protected String agentNames;
- public RobotRulesParser() { }
+ public RobotRulesParser() {
+ }
public RobotRulesParser(Configuration conf) {
setConf(conf);
@@ -90,16 +93,18 @@ public abstract class RobotRulesParser implements Configurable {
}
agentNames = agentName;
- // If there are any other agents specified, append those to the list of agents
+ // If there are any other agents specified, append those to the list of
+ // agents
String otherAgents = conf.get("http.robots.agents");
- if(otherAgents != null && !otherAgents.trim().isEmpty()) {
+ if (otherAgents != null && !otherAgents.trim().isEmpty()) {
StringTokenizer tok = new StringTokenizer(otherAgents, ",");
StringBuilder sb = new StringBuilder(agentNames);
while (tok.hasMoreTokens()) {
String str = tok.nextToken().trim();
if (str.equals("*") || str.equals(agentName)) {
// skip wildcard "*" or agent name itself
- // (required for backward compatibility, cf. NUTCH-1715 and NUTCH-1718)
+ // (required for backward compatibility, cf. NUTCH-1715 and
+ // NUTCH-1718)
} else {
sb.append(",").append(str);
}
@@ -117,16 +122,23 @@ public abstract class RobotRulesParser implements Configurable {
}
/**
- * Parses the robots content using the {@link SimpleRobotRulesParser} from crawler commons
- *
- * @param url A string containing url
- * @param content Contents of the robots file in a byte array
- * @param contentType The content type of the robots file
- * @param robotName A string containing all the robots agent names used by parser for matching
- * @return BaseRobotRules object
+ * Parses the robots content using the {@link SimpleRobotRulesParser} from
+ * crawler commons
+ *
+ * @param url
+ * A string containing url
+ * @param content
+ * Contents of the robots file in a byte array
+ * @param contentType
+ * The content type of the robots file
+ * @param robotName
+ * A string containing all the robots agent names used by parser for
+ * matching
+ * @return BaseRobotRules object
*/
- public BaseRobotRules parseRules (String url, byte[] content, String contentType, String robotName) {
- return robotParser.parseContent(url, content, contentType, robotName);
+ public BaseRobotRules parseRules(String url, byte[] content,
+ String contentType, String robotName) {
+ return robotParser.parseContent(url, content, contentType, robotName);
}
public BaseRobotRules getRobotRulesSet(Protocol protocol, Text url) {
@@ -145,23 +157,30 @@ public abstract class RobotRulesParser implements Configurable {
public static void main(String[] argv) {
if (argv.length != 3) {
- System.err.println("Usage: RobotRulesParser <robots-file> <url-file> <agent-names>\n");
- System.err.println("\tThe <robots-file> will be parsed as a robots.txt file,");
- System.err.println("\tusing the given <agent-name> to select rules. URLs ");
- System.err.println("\twill be read (one per line) from <url-file>, and tested");
- System.err.println("\tagainst the rules. Multiple agent names can be provided using");
+ System.err
+ .println("Usage: RobotRulesParser <robots-file> <url-file> <agent-names>\n");
+ System.err
+ .println("\tThe <robots-file> will be parsed as a robots.txt file,");
+ System.err
+ .println("\tusing the given <agent-name> to select rules. URLs ");
+ System.err
+ .println("\twill be read (one per line) from <url-file>, and tested");
+ System.err
+ .println("\tagainst the rules. Multiple agent names can be provided using");
System.err.println("\tcomma as a delimiter without any spaces.");
System.exit(-1);
}
try {
byte[] robotsBytes = Files.toByteArray(new File(argv[0]));
- BaseRobotRules rules = robotParser.parseContent(argv[0], robotsBytes, "text/plain", argv[2]);
+ BaseRobotRules rules = robotParser.parseContent(argv[0], robotsBytes,
+ "text/plain", argv[2]);
LineNumberReader testsIn = new LineNumberReader(new FileReader(argv[1]));
String testPath = testsIn.readLine().trim();
while (testPath != null) {
- System.out.println( (rules.isAllowed(testPath) ? "allowed" : "not allowed") + ":\t" + testPath);
+ System.out.println((rules.isAllowed(testPath) ? "allowed"
+ : "not allowed") + ":\t" + testPath);
testPath = testsIn.readLine();
}
testsIn.close();
diff --git a/src/java/org/apache/nutch/protocol/package-info.java b/src/java/org/apache/nutch/protocol/package-info.java
index 8804cb77b..66852498f 100644
--- a/src/java/org/apache/nutch/protocol/package-info.java
+++ b/src/java/org/apache/nutch/protocol/package-info.java
@@ -20,3 +20,4 @@
* see also {@link org.apache.nutch.net.protocols}.
*/
package org.apache.nutch.protocol;
+
diff --git a/src/java/org/apache/nutch/scoring/AbstractScoringFilter.java b/src/java/org/apache/nutch/scoring/AbstractScoringFilter.java
index 8c02482d8..d74c7fbe1 100644
--- a/src/java/org/apache/nutch/scoring/AbstractScoringFilter.java
+++ b/src/java/org/apache/nutch/scoring/AbstractScoringFilter.java
@@ -17,52 +17,52 @@ import org.apache.nutch.scoring.ScoringFilterException;
public abstract class AbstractScoringFilter implements ScoringFilter {
- private Configuration conf;
+ private Configuration conf;
- public Configuration getConf() {
- return conf;
- }
+ public Configuration getConf() {
+ return conf;
+ }
- public void setConf(Configuration conf) {
- this.conf = conf;
- }
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
- public void injectedScore(Text url, CrawlDatum datum)
- throws ScoringFilterException {
- }
+ public void injectedScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
+ }
- public void initialScore(Text url, CrawlDatum datum)
- throws ScoringFilterException {
- }
+ public void initialScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
+ }
- public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
- throws ScoringFilterException {
- return initSort;
- }
+ public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
+ throws ScoringFilterException {
+ return initSort;
+ }
- public void passScoreBeforeParsing(Text url, CrawlDatum datum,
- Content content) throws ScoringFilterException {
- }
+ public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content)
+ throws ScoringFilterException {
+ }
- public void passScoreAfterParsing(Text url, Content content, Parse parse)
- throws ScoringFilterException {
- }
+ public void passScoreAfterParsing(Text url, Content content, Parse parse)
+ throws ScoringFilterException {
+ }
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
- ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
- CrawlDatum adjust, int allCount) throws ScoringFilterException {
- return adjust;
- }
+ public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
+ ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
+ CrawlDatum adjust, int allCount) throws ScoringFilterException {
+ return adjust;
+ }
- public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
- List<CrawlDatum> inlinked) throws ScoringFilterException {
- }
+ public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
+ List<CrawlDatum> inlinked) throws ScoringFilterException {
+ }
- @Override
- public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
- CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
- throws ScoringFilterException {
- return initScore;
- }
+ @Override
+ public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
+ CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
+ throws ScoringFilterException {
+ return initScore;
+ }
}
diff --git a/src/java/org/apache/nutch/scoring/ScoringFilter.java b/src/java/org/apache/nutch/scoring/ScoringFilter.java
index 410521d51..4061a750b 100644
--- a/src/java/org/apache/nutch/scoring/ScoringFilter.java
+++ b/src/java/org/apache/nutch/scoring/ScoringFilter.java
@@ -33,129 +33,181 @@ import org.apache.nutch.protocol.Content;
/**
* A contract defining behavior of scoring plugins.
*
- * A scoring filter will manipulate scoring variables in CrawlDatum and
- * in resulting search indexes. Filters can be chained in a specific order,
- * to provide multi-stage scoring adjustments.
+ * A scoring filter will manipulate scoring variables in CrawlDatum and in
+ * resulting search indexes. Filters can be chained in a specific order, to
+ * provide multi-stage scoring adjustments.
*
* @author Andrzej Bialecki
*/
public interface ScoringFilter extends Configurable, Pluggable {
/** The name of the extension point. */
public final static String X_POINT_ID = ScoringFilter.class.getName();
-
+
/**
* Set an initial score for newly injected pages. Note: newly injected pages
- * may have no inlinks, so filter implementations may wish to set this
- * score to a non-zero value, to give newly injected pages some initial
- * credit.
- * @param url url of the page
- * @param datum new datum. Filters will modify it in-place.
+ * may have no inlinks, so filter implementations may wish to set this score
+ * to a non-zero value, to give newly injected pages some initial credit.
+ *
+ * @param url
+ * url of the page
+ * @param datum
+ * new datum. Filters will modify it in-place.
* @throws ScoringFilterException
*/
- public void injectedScore(Text url, CrawlDatum datum) throws ScoringFilterException;
-
+ public void injectedScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException;
+
/**
- * Set an initial score for newly discovered pages. Note: newly discovered pages
- * have at least one inlink with its score contribution, so filter implementations
- * may choose to set initial score to zero (unknown value), and then the inlink
- * score contribution will set the "real" value of the new page.
- * @param url url of the page
- * @param datum new datum. Filters will modify it in-place.
+ * Set an initial score for newly discovered pages. Note: newly discovered
+ * pages have at least one inlink with its score contribution, so filter
+ * implementations may choose to set initial score to zero (unknown value),
+ * and then the inlink score contribution will set the "real" value of the new
+ * page.
+ *
+ * @param url
+ * url of the page
+ * @param datum
+ * new datum. Filters will modify it in-place.
* @throws ScoringFilterException
*/
- public void initialScore(Text url, CrawlDatum datum) throws ScoringFilterException;
-
+ public void initialScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException;
+
/**
- * This method prepares a sort value for the purpose of sorting and
- * selecting top N scoring pages during fetchlist generation.
- * @param url url of the page
- * @param datum page's datum, should not be modified
- * @param initSort initial sort value, or a value from previous filters in chain
+ * This method prepares a sort value for the purpose of sorting and selecting
+ * top N scoring pages during fetchlist generation.
+ *
+ * @param url
+ * url of the page
+ * @param datum
+ * page's datum, should not be modified
+ * @param initSort
+ * initial sort value, or a value from previous filters in chain
*/
- public float generatorSortValue(Text url, CrawlDatum datum, float initSort) throws ScoringFilterException;
-
+ public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
+ throws ScoringFilterException;
+
/**
* This method takes all relevant score information from the current datum
* (coming from a generated fetchlist) and stores it into
- * {@link org.apache.nutch.protocol.Content} metadata.
- * This is needed in order to pass this value(s) to the mechanism that distributes it
- * to outlinked pages.
- * @param url url of the page
- * @param datum source datum. NOTE: modifications to this value are not persisted.
- * @param content instance of content. Implementations may modify this
- * in-place, primarily by setting some metadata properties.
+ * {@link org.apache.nutch.protocol.Content} metadata. This is needed in order
+ * to pass this value(s) to the mechanism that distributes it to outlinked
+ * pages.
+ *
+ * @param url
+ * url of the page
+ * @param datum
+ * source datum. NOTE: modifications to this value are not persisted.
+ * @param content
+ * instance of content. Implementations may modify this in-place,
+ * primarily by setting some metadata properties.
*/
- public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content) throws ScoringFilterException;
-
+ public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content)
+ throws ScoringFilterException;
+
/**
* Currently a part of score distribution is performed using only data coming
* from the parsing process. We need this method in order to ensure the
* presence of score data in these steps.
- * @param url page url
- * @param content original content. NOTE: modifications to this value are not persisted.
- * @param parse target instance to copy the score information to. Implementations
- * may modify this in-place, primarily by setting some metadata properties.
+ *
+ * @param url
+ * page url
+ * @param content
+ * original content. NOTE: modifications to this value are not
+ * persisted.
+ * @param parse
+ * target instance to copy the score information to. Implementations
+ * may modify this in-place, primarily by setting some metadata
+ * properties.
*/
- public void passScoreAfterParsing(Text url, Content content, Parse parse) throws ScoringFilterException;
-
+ public void passScoreAfterParsing(Text url, Content content, Parse parse)
+ throws ScoringFilterException;
+
/**
* Distribute score value from the current page to all its outlinked pages.
- * @param fromUrl url of the source page
- * @param parseData ParseData instance, which stores relevant score value(s)
- * in its metadata. NOTE: filters may modify this in-place, all changes will
- * be persisted.
- * @param targets &lt;url, CrawlDatum&gt; pairs. NOTE: filters can modify this in-place,
- * all changes will be persisted.
- * @param adjust a CrawlDatum instance, initially null, which implementations
- * may use to pass adjustment values to the original CrawlDatum. When creating
- * this instance, set its status to {@link CrawlDatum#STATUS_LINKED}.
- * @param allCount number of all collected outlinks from the source page
+ *
+ * @param fromUrl
+ * url of the source page
+ * @param parseData
+ * ParseData instance, which stores relevant score value(s) in its
+ * metadata. NOTE: filters may modify this in-place, all changes will
+ * be persisted.
+ * @param targets
+ * &lt;url, CrawlDatum&gt; pairs. NOTE: filters can modify this
+ * in-place, all changes will be persisted.
+ * @param adjust
+ * a CrawlDatum instance, initially null, which implementations may
+ * use to pass adjustment values to the original CrawlDatum. When
+ * creating this instance, set its status to
+ * {@link CrawlDatum#STATUS_LINKED}.
+ * @param allCount
+ * number of all collected outlinks from the source page
* @return if needed, implementations may return an instance of CrawlDatum,
- * with status {@link CrawlDatum#STATUS_LINKED}, which contains adjustments
- * to be applied to the original CrawlDatum score(s) and metadata. This can
- * be null if not needed.
+ * with status {@link CrawlDatum#STATUS_LINKED}, which contains
+ * adjustments to be applied to the original CrawlDatum score(s) and
+ * metadata. This can be null if not needed.
* @throws ScoringFilterException
*/
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl, ParseData parseData,
- Collection<Entry<Text, CrawlDatum>> targets, CrawlDatum adjust,
- int allCount) throws ScoringFilterException;
+ public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
+ ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
+ CrawlDatum adjust, int allCount) throws ScoringFilterException;
/**
- * This method calculates a new score of CrawlDatum during CrawlDb update, based on the
- * initial value of the original CrawlDatum, and also score values contributed by
- * inlinked pages.
- * @param url url of the page
- * @param old original datum, with original score. May be null if this is a newly
- * discovered page. If not null, filters should use score values from this parameter
- * as the starting values - the <code>datum</code> parameter may contain values that are
- * no longer valid, if other updates occured between generation and this update.
- * @param datum the new datum, with the original score saved at the time when
- * fetchlist was generated. Filters should update this in-place, and it will be saved in
- * the crawldb.
- * @param inlinked (partial) list of CrawlDatum-s (with their scores) from
- * links pointing to this page, found in the current update batch.
+ * This method calculates a new score of CrawlDatum during CrawlDb update,
+ * based on the initial value of the original CrawlDatum, and also score
+ * values contributed by inlinked pages.
+ *
+ * @param url
+ * url of the page
+ * @param old
+ * original datum, with original score. May be null if this is a
+ * newly discovered page. If not null, filters should use score
+ * values from this parameter as the starting values - the
+ * <code>datum</code> parameter may contain values that are no longer
+ * valid, if other updates occured between generation and this
+ * update.
+ * @param datum
+ * the new datum, with the original score saved at the time when
+ * fetchlist was generated. Filters should update this in-place, and
+ * it will be saved in the crawldb.
+ * @param inlinked
+ * (partial) list of CrawlDatum-s (with their scores) from links
+ * pointing to this page, found in the current update batch.
* @throws ScoringFilterException
*/
- public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum, List<CrawlDatum> inlinked) throws ScoringFilterException;
-
+ public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
+ List<CrawlDatum> inlinked) throws ScoringFilterException;
+
/**
* This method calculates a Lucene document boost.
- * @param url url of the page
- * @param doc Lucene document. NOTE: this already contains all information collected
- * by indexing filters. Implementations may modify this instance, in order to store/remove
- * some information.
- * @param dbDatum current page from CrawlDb. NOTE: changes made to this instance
- * are not persisted.
- * @param fetchDatum datum from FetcherOutput (containing among others the fetching status)
- * @param parse parsing result. NOTE: changes made to this instance are not persisted.
- * @param inlinks current inlinks from LinkDb. NOTE: changes made to this instance are
- * not persisted.
- * @param initScore initial boost value for the Lucene document.
- * @return boost value for the Lucene document. This value is passed as an argument
- * to the next scoring filter in chain. NOTE: implementations may also express
- * other scoring strategies by modifying Lucene document directly.
+ *
+ * @param url
+ * url of the page
+ * @param doc
+ * Lucene document. NOTE: this already contains all information
+ * collected by indexing filters. Implementations may modify this
+ * instance, in order to store/remove some information.
+ * @param dbDatum
+ * current page from CrawlDb. NOTE: changes made to this instance are
+ * not persisted.
+ * @param fetchDatum
+ * datum from FetcherOutput (containing among others the fetching
+ * status)
+ * @param parse
+ * parsing result. NOTE: changes made to this instance are not
+ * persisted.
+ * @param inlinks
+ * current inlinks from LinkDb. NOTE: changes made to this instance
+ * are not persisted.
+ * @param initScore
+ * initial boost value for the Lucene document.
+ * @return boost value for the Lucene document. This value is passed as an
+ * argument to the next scoring filter in chain. NOTE: implementations
+ * may also express other scoring strategies by modifying Lucene
+ * document directly.
* @throws ScoringFilterException
*/
public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
- CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore) throws ScoringFilterException;
+ CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
+ throws ScoringFilterException;
}
diff --git a/src/java/org/apache/nutch/scoring/ScoringFilterException.java b/src/java/org/apache/nutch/scoring/ScoringFilterException.java
index 69cd94fa0..f363c4bba 100644
--- a/src/java/org/apache/nutch/scoring/ScoringFilterException.java
+++ b/src/java/org/apache/nutch/scoring/ScoringFilterException.java
@@ -1,19 +1,19 @@
/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You 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.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.scoring;
/**
diff --git a/src/java/org/apache/nutch/scoring/ScoringFilters.java b/src/java/org/apache/nutch/scoring/ScoringFilters.java
index 9499eae07..5bad78f60 100644
--- a/src/java/org/apache/nutch/scoring/ScoringFilters.java
+++ b/src/java/org/apache/nutch/scoring/ScoringFilters.java
@@ -49,7 +49,8 @@ public class ScoringFilters extends Configured implements ScoringFilter {
}
/** Calculate a sort value for Generate. */
- public float generatorSortValue(Text url, CrawlDatum datum, float initSort) throws ScoringFilterException {
+ public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
+ throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
initSort = this.filters[i].generatorSortValue(url, datum, initSort);
}
@@ -57,48 +58,59 @@ public class ScoringFilters extends Configured implements ScoringFilter {
}
/** Calculate a new initial score, used when adding newly discovered pages. */
- public void initialScore(Text url, CrawlDatum datum) throws ScoringFilterException {
+ public void initialScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].initialScore(url, datum);
}
}
/** Calculate a new initial score, used when injecting new pages. */
- public void injectedScore(Text url, CrawlDatum datum) throws ScoringFilterException {
+ public void injectedScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].injectedScore(url, datum);
}
}
/** Calculate updated page score during CrawlDb.update(). */
- public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum, List<CrawlDatum> inlinked) throws ScoringFilterException {
+ public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
+ List<CrawlDatum> inlinked) throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].updateDbScore(url, old, datum, inlinked);
}
}
- public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content) throws ScoringFilterException {
+ public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content)
+ throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].passScoreBeforeParsing(url, datum, content);
}
}
-
- public void passScoreAfterParsing(Text url, Content content, Parse parse) throws ScoringFilterException {
+
+ public void passScoreAfterParsing(Text url, Content content, Parse parse)
+ throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].passScoreAfterParsing(url, content, parse);
}
}
-
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl, ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets, CrawlDatum adjust, int allCount) throws ScoringFilterException {
+
+ public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
+ ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
+ CrawlDatum adjust, int allCount) throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
- adjust = this.filters[i].distributeScoreToOutlinks(fromUrl, parseData, targets, adjust, allCount);
+ adjust = this.filters[i].distributeScoreToOutlinks(fromUrl, parseData,
+ targets, adjust, allCount);
}
return adjust;
}
- public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum, CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore) throws ScoringFilterException {
+ public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
+ CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
+ throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
- initScore = this.filters[i].indexerScore(url, doc, dbDatum, fetchDatum, parse, inlinks, initScore);
+ initScore = this.filters[i].indexerScore(url, doc, dbDatum, fetchDatum,
+ parse, inlinks, initScore);
}
return initScore;
}
diff --git a/src/java/org/apache/nutch/scoring/package-info.java b/src/java/org/apache/nutch/scoring/package-info.java
index a7d74d916..b6a578b57 100644
--- a/src/java/org/apache/nutch/scoring/package-info.java
+++ b/src/java/org/apache/nutch/scoring/package-info.java
@@ -19,3 +19,4 @@
* The {@link org.apache.nutch.scoring.ScoringFilter ScoringFilter} interface.
*/
package org.apache.nutch.scoring;
+
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkDatum.java b/src/java/org/apache/nutch/scoring/webgraph/LinkDatum.java
index 769d20f37..67c936612 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkDatum.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkDatum.java
@@ -27,8 +27,7 @@ import org.apache.hadoop.io.Writable;
* A class for holding link information including the url, anchor text, a score,
* the timestamp of the link and a link type.
*/
-public class LinkDatum
- implements Writable {
+public class LinkDatum implements Writable {
public final static byte INLINK = 1;
public final static byte OUTLINK = 2;
@@ -49,7 +48,8 @@ public class LinkDatum
/**
* Creates a LinkDatum with a given url. Timestamp is set to current time.
*
- * @param url The link url.
+ * @param url
+ * The link url.
*/
public LinkDatum(String url) {
this(url, "", System.currentTimeMillis());
@@ -59,8 +59,10 @@ public class LinkDatum
* Creates a LinkDatum with a url and an anchor text. Timestamp is set to
* current time.
*
- * @param url The link url.
- * @param anchor The link anchor text.
+ * @param url
+ * The link url.
+ * @param anchor
+ * The link anchor text.
*/
public LinkDatum(String url, String anchor) {
this(url, anchor, System.currentTimeMillis());
@@ -112,8 +114,7 @@ public class LinkDatum
this.linkType = linkType;
}
- public void readFields(DataInput in)
- throws IOException {
+ public void readFields(DataInput in) throws IOException {
url = Text.readString(in);
anchor = Text.readString(in);
score = in.readFloat();
@@ -121,8 +122,7 @@ public class LinkDatum
linkType = in.readByte();
}
- public void write(DataOutput out)
- throws IOException {
+ public void write(DataOutput out) throws IOException {
Text.writeString(out, url);
Text.writeString(out, anchor != null ? anchor : "");
out.writeFloat(score);
@@ -132,9 +132,9 @@ public class LinkDatum
public String toString() {
- String type = (linkType == INLINK ? "inlink" : (linkType == OUTLINK)
- ? "outlink" : "unknown");
+ String type = (linkType == INLINK ? "inlink"
+ : (linkType == OUTLINK) ? "outlink" : "unknown");
return "url: " + url + ", anchor: " + anchor + ", score: " + score
- + ", timestamp: " + timestamp + ", link type: " + type;
+ + ", timestamp: " + timestamp + ", link type: " + type;
}
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java b/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
index 0a641fea5..a79342f6d 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
@@ -67,27 +67,24 @@ import org.apache.nutch.util.TimingUtil;
/**
* The LinkDumper tool creates a database of node to inlink information that can
- * be read using the nested Reader class. This allows the inlink and scoring
- * state of a single url to be reviewed quickly to determine why a given url is
- * ranking a certain way. This tool is to be used with the LinkRank analysis.
+ * be read using the nested Reader class. This allows the inlink and scoring
+ * state of a single url to be reviewed quickly to determine why a given url is
+ * ranking a certain way. This tool is to be used with the LinkRank analysis.
*/
-public class LinkDumper
- extends Configured
- implements Tool {
+public class LinkDumper extends Configured implements Tool {
public static final Logger LOG = LoggerFactory.getLogger(LinkDumper.class);
public static final String DUMP_DIR = "linkdump";
/**
- * Reader class which will print out the url and all of its inlinks to system
- * out. Each inlinkwill be displayed with its node information including
- * score and number of in and outlinks.
+ * Reader class which will print out the url and all of its inlinks to system
+ * out. Each inlinkwill be displayed with its node information including score
+ * and number of in and outlinks.
*/
public static class Reader {
- public static void main(String[] args)
- throws Exception {
-
+ public static void main(String[] args) throws Exception {
+
if (args == null || args.length < 2) {
System.out.println("LinkDumper$Reader usage: <webgraphdb> <url>");
return;
@@ -99,20 +96,20 @@ public class LinkDumper
Path webGraphDb = new Path(args[0]);
String url = args[1];
MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(
- webGraphDb, DUMP_DIR), conf);
+ webGraphDb, DUMP_DIR), conf);
// get the link nodes for the url
Text key = new Text(url);
LinkNodes nodes = new LinkNodes();
MapFileOutputFormat.getEntry(readers,
- new HashPartitioner<Text, LinkNodes>(), key, nodes);
+ new HashPartitioner<Text, LinkNodes>(), key, nodes);
// print out the link nodes
LinkNode[] linkNodesAr = nodes.getLinks();
System.out.println(url + ":");
for (LinkNode node : linkNodesAr) {
System.out.println(" " + node.getUrl() + " - "
- + node.getNode().toString());
+ + node.getNode().toString());
}
// close the readers
@@ -123,8 +120,7 @@ public class LinkDumper
/**
* Bean class which holds url to node information.
*/
- public static class LinkNode
- implements Writable {
+ public static class LinkNode implements Writable {
private String url = null;
private Node node = null;
@@ -154,15 +150,13 @@ public class LinkDumper
this.node = node;
}
- public void readFields(DataInput in)
- throws IOException {
+ public void readFields(DataInput in) throws IOException {
url = in.readUTF();
node = new Node();
node.readFields(in);
}
- public void write(DataOutput out)
- throws IOException {
+ public void write(DataOutput out) throws IOException {
out.writeUTF(url);
node.write(out);
}
@@ -172,8 +166,7 @@ public class LinkDumper
/**
* Writable class which holds an array of LinkNode objects.
*/
- public static class LinkNodes
- implements Writable {
+ public static class LinkNodes implements Writable {
private LinkNode[] links;
@@ -193,8 +186,7 @@ public class LinkDumper
this.links = links;
}
- public void readFields(DataInput in)
- throws IOException {
+ public void readFields(DataInput in) throws IOException {
int numLinks = in.readInt();
if (numLinks > 0) {
links = new LinkNode[numLinks];
@@ -206,8 +198,7 @@ public class LinkDumper
}
}
- public void write(DataOutput out)
- throws IOException {
+ public void write(DataOutput out) throws IOException {
if (links != null && links.length > 0) {
int numLinks = links.length;
out.writeInt(numLinks);
@@ -222,9 +213,9 @@ public class LinkDumper
* Inverts outlinks from the WebGraph to inlinks and attaches node
* information.
*/
- public static class Inverter
- implements Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, LinkNode> {
+ public static class Inverter implements
+ Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, LinkNode> {
private JobConf conf;
@@ -236,8 +227,8 @@ public class LinkDumper
* Wraps all values in ObjectWritables.
*/
public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
ObjectWritable objWrite = new ObjectWritable();
objWrite.set(value);
@@ -245,12 +236,12 @@ public class LinkDumper
}
/**
- * Inverts outlinks to inlinks while attaching node information to the
+ * Inverts outlinks to inlinks while attaching node information to the
* outlink.
*/
public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, LinkNode> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, LinkNode> output, Reporter reporter)
+ throws IOException {
String fromUrl = key.toString();
List<LinkDatum> outlinks = new ArrayList<LinkDatum>();
@@ -262,13 +253,11 @@ public class LinkDumper
ObjectWritable write = values.next();
Object obj = write.get();
if (obj instanceof Node) {
- node = (Node)obj;
- }
- else if (obj instanceof LinkDatum) {
- outlinks.add(WritableUtils.clone((LinkDatum)obj, conf));
- }
- else if (obj instanceof LoopSet) {
- loops = (LoopSet)obj;
+ node = (Node) obj;
+ } else if (obj instanceof LinkDatum) {
+ outlinks.add(WritableUtils.clone((LinkDatum) obj, conf));
+ } else if (obj instanceof LoopSet) {
+ loops = (LoopSet) obj;
}
}
@@ -280,13 +269,13 @@ public class LinkDumper
for (int i = 0; i < outlinks.size(); i++) {
LinkDatum outlink = outlinks.get(i);
String toUrl = outlink.getUrl();
-
+
// remove any url that is in the loopset, same as LinkRank
if (loopSet != null && loopSet.contains(toUrl)) {
continue;
}
-
- // collect the outlink as an inlink with the node
+
+ // collect the outlink as an inlink with the node
output.collect(new Text(toUrl), new LinkNode(fromUrl, node));
}
}
@@ -297,11 +286,11 @@ public class LinkDumper
}
/**
- * Merges LinkNode objects into a single array value per url. This allows
- * all values to be quickly retrieved and printed via the Reader tool.
+ * Merges LinkNode objects into a single array value per url. This allows all
+ * values to be quickly retrieved and printed via the Reader tool.
*/
- public static class Merger
- implements Reducer<Text, LinkNode, Text, LinkNodes> {
+ public static class Merger implements
+ Reducer<Text, LinkNode, Text, LinkNodes> {
private JobConf conf;
private int maxInlinks = 50000;
@@ -314,8 +303,8 @@ public class LinkDumper
* Aggregate all LinkNode objects for a given url.
*/
public void reduce(Text key, Iterator<LinkNode> values,
- OutputCollector<Text, LinkNodes> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, LinkNodes> output, Reporter reporter)
+ throws IOException {
List<LinkNode> nodeList = new ArrayList<LinkNode>();
int numNodes = 0;
@@ -325,8 +314,7 @@ public class LinkDumper
if (numNodes < maxInlinks) {
nodeList.add(WritableUtils.clone(cur, conf));
numNodes++;
- }
- else {
+ } else {
break;
}
}
@@ -342,11 +330,10 @@ public class LinkDumper
}
/**
- * Runs the inverter and merger jobs of the LinkDumper tool to create the
- * url to inlink node database.
+ * Runs the inverter and merger jobs of the LinkDumper tool to create the url
+ * to inlink node database.
*/
- public void dumpLinks(Path webGraphDb)
- throws IOException {
+ public void dumpLinks(Path webGraphDb) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -362,7 +349,7 @@ public class LinkDumper
// run the inverter job
Path tempInverted = new Path(webGraphDb, "inverted-"
- + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
JobConf inverter = new NutchJob(conf);
inverter.setJobName("LinkDumper: inverter");
FileInputFormat.addInputPath(inverter, nodeDb);
@@ -384,8 +371,7 @@ public class LinkDumper
LOG.info("LinkDumper: running inverter");
JobClient.runJob(inverter);
LOG.info("LinkDumper: finished inverter");
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -407,43 +393,41 @@ public class LinkDumper
LOG.info("LinkDumper: running merger");
JobClient.runJob(merger);
LOG.info("LinkDumper: finished merger");
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
fs.delete(tempInverted, true);
long end = System.currentTimeMillis();
- LOG.info("LinkDumper: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("LinkDumper: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- public static void main(String[] args)
- throws Exception {
+ public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new LinkDumper(),
- args);
+ args);
System.exit(res);
}
/**
- * Runs the LinkDumper tool. This simply creates the database, to read the
+ * Runs the LinkDumper tool. This simply creates the database, to read the
* values the nested Reader tool must be used.
*/
- public int run(String[] args)
- throws Exception {
+ public int run(String[] args) throws Exception {
Options options = new Options();
OptionBuilder.withArgName("help");
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("webgraphdb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the web graph database to use");
Option webGraphDbOpts = OptionBuilder.create("webgraphdb");
options.addOption(webGraphDbOpts);
-
+
CommandLineParser parser = new GnuParser();
try {
@@ -457,8 +441,7 @@ public class LinkDumper
String webGraphDb = line.getOptionValue("webgraphdb");
dumpLinks(new Path(webGraphDb));
return 0;
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("LinkDumper: " + StringUtils.stringifyException(e));
return -2;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
index bee1cb548..142137cd0 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
@@ -68,9 +68,7 @@ import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.TimingUtil;
import org.apache.nutch.util.URLUtil;
-public class LinkRank
- extends Configured
- implements Tool {
+public class LinkRank extends Configured implements Tool {
public static final Logger LOG = LoggerFactory.getLogger(LinkRank.class);
private static final String NUM_NODES = "_num_nodes_";
@@ -79,14 +77,16 @@ public class LinkRank
* Runs the counter job. The counter job determines the number of links in the
* webgraph. This is used during analysis.
*
- * @param fs The job file system.
- * @param webGraphDb The web graph database to use.
+ * @param fs
+ * The job file system.
+ * @param webGraphDb
+ * The web graph database to use.
*
* @return The number of nodes in the web graph.
- * @throws IOException If an error occurs while running the counter job.
+ * @throws IOException
+ * If an error occurs while running the counter job.
*/
- private int runCounter(FileSystem fs, Path webGraphDb)
- throws IOException {
+ private int runCounter(FileSystem fs, Path webGraphDb) throws IOException {
// configure the counter job
Path numLinksPath = new Path(webGraphDb, NUM_NODES);
@@ -105,14 +105,14 @@ public class LinkRank
counter.setOutputValueClass(LongWritable.class);
counter.setNumReduceTasks(1);
counter.setOutputFormat(TextOutputFormat.class);
- counter.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ counter.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ false);
// run the counter job, outputs to a single reduce task and file
LOG.info("Starting link counter job");
try {
JobClient.runJob(counter);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -125,13 +125,13 @@ public class LinkRank
BufferedReader buffer = new BufferedReader(new InputStreamReader(readLinks));
String numLinksLine = buffer.readLine();
readLinks.close();
-
+
// check if there are links to process, if none, webgraph might be empty
if (numLinksLine == null || numLinksLine.length() == 0) {
fs.delete(numLinksPath, true);
throw new IOException("No links to process, is the webgraph empty?");
}
-
+
// delete temp file and convert and return the number of links as an int
LOG.info("Deleting numlinks temp file");
fs.delete(numLinksPath, true);
@@ -143,13 +143,15 @@ public class LinkRank
* Runs the initializer job. The initializer job sets up the nodes with a
* default starting score for link analysis.
*
- * @param nodeDb The node database to use.
- * @param output The job output directory.
+ * @param nodeDb
+ * The node database to use.
+ * @param output
+ * The job output directory.
*
- * @throws IOException If an error occurs while running the initializer job.
+ * @throws IOException
+ * If an error occurs while running the initializer job.
*/
- private void runInitializer(Path nodeDb, Path output)
- throws IOException {
+ private void runInitializer(Path nodeDb, Path output) throws IOException {
// configure the initializer
JobConf initializer = new NutchJob(getConf());
@@ -163,14 +165,14 @@ public class LinkRank
initializer.setOutputKeyClass(Text.class);
initializer.setOutputValueClass(Node.class);
initializer.setOutputFormat(MapFileOutputFormat.class);
- initializer.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ initializer.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ false);
// run the initializer
LOG.info("Starting initialization job");
try {
JobClient.runJob(initializer);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -186,15 +188,20 @@ public class LinkRank
* space requirements but it can be very useful is weeding out and eliminating
* link farms and other spam pages.
*
- * @param nodeDb The node database to use.
- * @param outlinkDb The outlink database to use.
- * @param loopDb The loop database to use if it exists.
- * @param output The output directory.
+ * @param nodeDb
+ * The node database to use.
+ * @param outlinkDb
+ * The outlink database to use.
+ * @param loopDb
+ * The loop database to use if it exists.
+ * @param output
+ * The output directory.
*
- * @throws IOException If an error occurs while running the inverter job.
+ * @throws IOException
+ * If an error occurs while running the inverter job.
*/
private void runInverter(Path nodeDb, Path outlinkDb, Path loopDb, Path output)
- throws IOException {
+ throws IOException {
// configure the inverter
JobConf inverter = new NutchJob(getConf());
@@ -215,14 +222,14 @@ public class LinkRank
inverter.setOutputKeyClass(Text.class);
inverter.setOutputValueClass(LinkDatum.class);
inverter.setOutputFormat(SequenceFileOutputFormat.class);
- inverter.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ inverter.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ false);
// run the inverter job
LOG.info("Starting inverter job");
try {
JobClient.runJob(inverter);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -236,23 +243,28 @@ public class LinkRank
* Typically the link analysis job is run a number of times to allow the link
* rank scores to converge.
*
- * @param nodeDb The node database from which we are getting previous link
- * rank scores.
- * @param inverted The inverted inlinks
- * @param output The link analysis output.
- * @param iteration The current iteration number.
- * @param numIterations The total number of link analysis iterations
+ * @param nodeDb
+ * The node database from which we are getting previous link rank
+ * scores.
+ * @param inverted
+ * The inverted inlinks
+ * @param output
+ * The link analysis output.
+ * @param iteration
+ * The current iteration number.
+ * @param numIterations
+ * The total number of link analysis iterations
*
- * @throws IOException If an error occurs during link analysis.
+ * @throws IOException
+ * If an error occurs during link analysis.
*/
private void runAnalysis(Path nodeDb, Path inverted, Path output,
- int iteration, int numIterations, float rankOne)
- throws IOException {
+ int iteration, int numIterations, float rankOne) throws IOException {
JobConf analyzer = new NutchJob(getConf());
analyzer.set("link.analyze.iteration", String.valueOf(iteration + 1));
analyzer.setJobName("LinkAnalysis Analyzer, iteration " + (iteration + 1)
- + " of " + numIterations);
+ + " of " + numIterations);
FileInputFormat.addInputPath(analyzer, nodeDb);
FileInputFormat.addInputPath(analyzer, inverted);
FileOutputFormat.setOutputPath(analyzer, output);
@@ -265,13 +277,13 @@ public class LinkRank
analyzer.setOutputKeyClass(Text.class);
analyzer.setOutputValueClass(Node.class);
analyzer.setOutputFormat(MapFileOutputFormat.class);
- analyzer.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ analyzer.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ false);
LOG.info("Starting analysis job");
try {
JobClient.runJob(analyzer);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -283,9 +295,9 @@ public class LinkRank
* This is used to determine a rank one score for pages with zero inlinks but
* that contain outlinks.
*/
- private static class Counter
- implements Mapper<Text, Node, Text, LongWritable>,
- Reducer<Text, LongWritable, Text, LongWritable> {
+ private static class Counter implements
+ Mapper<Text, Node, Text, LongWritable>,
+ Reducer<Text, LongWritable, Text, LongWritable> {
private static Text numNodes = new Text(NUM_NODES);
private static LongWritable one = new LongWritable(1L);
@@ -297,8 +309,8 @@ public class LinkRank
* Outputs one for every node.
*/
public void map(Text key, Node value,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, LongWritable> output, Reporter reporter)
+ throws IOException {
output.collect(numNodes, one);
}
@@ -306,8 +318,8 @@ public class LinkRank
* Totals the node number and outputs a single total value.
*/
public void reduce(Text key, Iterator<LongWritable> values,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, LongWritable> output, Reporter reporter)
+ throws IOException {
long total = 0;
while (values.hasNext()) {
@@ -320,8 +332,7 @@ public class LinkRank
}
}
- private static class Initializer
- implements Mapper<Text, Node, Text, Node> {
+ private static class Initializer implements Mapper<Text, Node, Text, Node> {
private JobConf conf;
private float initialScore = 1.0f;
@@ -332,8 +343,7 @@ public class LinkRank
}
public void map(Text key, Node node, OutputCollector<Text, Node> output,
- Reporter reporter)
- throws IOException {
+ Reporter reporter) throws IOException {
String url = key.toString();
Node outNode = WritableUtils.clone(node, conf);
@@ -351,9 +361,9 @@ public class LinkRank
* WebGraph. The link analysis process consists of inverting, analyzing and
* scoring, in a loop for a given number of iterations.
*/
- private static class Inverter
- implements Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, LinkDatum> {
+ private static class Inverter implements
+ Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, LinkDatum> {
private JobConf conf;
@@ -365,8 +375,8 @@ public class LinkRank
* Convert values to ObjectWritable
*/
public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
ObjectWritable objWrite = new ObjectWritable();
objWrite.set(value);
@@ -379,8 +389,8 @@ public class LinkRank
* within the loopset.
*/
public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, LinkDatum> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, LinkDatum> output, Reporter reporter)
+ throws IOException {
String fromUrl = key.toString();
List<LinkDatum> outlinks = new ArrayList<LinkDatum>();
@@ -392,23 +402,25 @@ public class LinkRank
ObjectWritable write = values.next();
Object obj = write.get();
if (obj instanceof Node) {
- node = (Node)obj;
- }
- else if (obj instanceof LinkDatum) {
- outlinks.add(WritableUtils.clone((LinkDatum)obj, conf));
- }
- else if (obj instanceof LoopSet) {
- loops = (LoopSet)obj;
+ node = (Node) obj;
+ } else if (obj instanceof LinkDatum) {
+ outlinks.add(WritableUtils.clone((LinkDatum) obj, conf));
+ } else if (obj instanceof LoopSet) {
+ loops = (LoopSet) obj;
}
}
- // Check for the possibility of a LoopSet object without Node and LinkDatum objects. This can happen
- // with webgraphs that receive deletes (e.g. link.delete.gone and/or URL filters or normalizers) but
+ // Check for the possibility of a LoopSet object without Node and
+ // LinkDatum objects. This can happen
+ // with webgraphs that receive deletes (e.g. link.delete.gone and/or URL
+ // filters or normalizers) but
// without an updated Loops database.
// See: https://issues.apache.org/jira/browse/NUTCH-1299
if (node == null && loops != null) {
// Nothing to do
- LOG.warn("LoopSet without Node object received for " + key.toString() + " . You should either not use Loops as input of the LinkRank program or rerun the Loops program over the WebGraph.");
+ LOG.warn("LoopSet without Node object received for "
+ + key.toString()
+ + " . You should either not use Loops as input of the LinkRank program or rerun the Loops program over the WebGraph.");
return;
}
@@ -430,7 +442,7 @@ public class LinkRank
// remove any url that is contained in the loopset
if (loopSet != null && loopSet.contains(toUrl)) {
LOG.debug(fromUrl + ": Skipping inverting inlink from loop "
- + toUrl);
+ + toUrl);
continue;
}
outlink.setUrl(fromUrl);
@@ -439,8 +451,8 @@ public class LinkRank
// collect the inverted outlink
output.collect(new Text(toUrl), outlink);
LOG.debug(toUrl + ": inverting inlink from " + fromUrl
- + " origscore: " + inlinkScore + " numOutlinks: " + numOutlinks
- + " inlinkscore: " + outlinkScore);
+ + " origscore: " + inlinkScore + " numOutlinks: " + numOutlinks
+ + " inlinkscore: " + outlinkScore);
}
}
}
@@ -452,9 +464,9 @@ public class LinkRank
/**
* Runs a single link analysis iteration.
*/
- private static class Analyzer
- implements Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, Node> {
+ private static class Analyzer implements
+ Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, Node> {
private JobConf conf;
private float dampingFactor = 0.85f;
@@ -471,13 +483,13 @@ public class LinkRank
try {
this.conf = conf;
- this.dampingFactor = conf.getFloat("link.analyze.damping.factor", 0.85f);
+ this.dampingFactor = conf
+ .getFloat("link.analyze.damping.factor", 0.85f);
this.rankOne = conf.getFloat("link.analyze.rank.one", 0.0f);
this.itNum = conf.getInt("link.analyze.iteration", 0);
limitPages = conf.getBoolean("link.ignore.limit.page", true);
limitDomains = conf.getBoolean("link.ignore.limit.domain", true);
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error(StringUtils.stringifyException(e));
throw new IllegalArgumentException(e);
}
@@ -487,8 +499,8 @@ public class LinkRank
* Convert values to ObjectWritable
*/
public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
ObjectWritable objWrite = new ObjectWritable();
objWrite.set(WritableUtils.clone(value, conf));
@@ -500,8 +512,8 @@ public class LinkRank
* stored in a temporary NodeDb which replaces the NodeDb of the WebGraph.
*/
public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, Node> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, Node> output, Reporter reporter)
+ throws IOException {
String url = key.toString();
Set<String> domains = new HashSet<String>();
@@ -517,11 +529,10 @@ public class LinkRank
ObjectWritable next = values.next();
Object value = next.get();
if (value instanceof Node) {
- node = (Node)value;
- }
- else if (value instanceof LinkDatum) {
+ node = (Node) value;
+ } else if (value instanceof LinkDatum) {
- LinkDatum linkDatum = (LinkDatum)value;
+ LinkDatum linkDatum = (LinkDatum) value;
float scoreFromInlink = linkDatum.getScore();
String inlinkUrl = linkDatum.getUrl();
String inLinkDomain = URLUtil.getDomainName(inlinkUrl);
@@ -529,9 +540,9 @@ public class LinkRank
// limit counting duplicate inlinks by pages or domains
if ((limitPages && pages.contains(inLinkPage))
- || (limitDomains && domains.contains(inLinkDomain))) {
+ || (limitDomains && domains.contains(inLinkDomain))) {
LOG.debug(url + ": ignoring " + scoreFromInlink + " from "
- + inlinkUrl + ", duplicate page or domain");
+ + inlinkUrl + ", duplicate page or domain");
continue;
}
@@ -541,16 +552,16 @@ public class LinkRank
domains.add(inLinkDomain);
pages.add(inLinkPage);
LOG.debug(url + ": adding " + scoreFromInlink + " from " + inlinkUrl
- + ", total: " + totalInlinkScore);
+ + ", total: " + totalInlinkScore);
}
}
// calculate linkRank score formula
float linkRankScore = (1 - this.dampingFactor)
- + (this.dampingFactor * totalInlinkScore);
+ + (this.dampingFactor * totalInlinkScore);
LOG.debug(url + ": score: " + linkRankScore + " num inlinks: "
- + numInlinks + " iteration: " + itNum);
+ + numInlinks + " iteration: " + itNum);
// store the score in a temporary NodeDb
Node outNode = WritableUtils.clone(node, conf);
@@ -558,8 +569,7 @@ public class LinkRank
output.collect(key, outNode);
}
- public void close()
- throws IOException {
+ public void close() throws IOException {
}
}
@@ -586,12 +596,13 @@ public class LinkRank
* by default 10. And finally replaces the NodeDb in the WebGraph with the
* link rank output.
*
- * @param webGraphDb The WebGraph to run link analysis on.
+ * @param webGraphDb
+ * The WebGraph to run link analysis on.
*
- * @throws IOException If an error occurs during link analysis.
+ * @throws IOException
+ * If an error occurs during link analysis.
*/
- public void analyze(Path webGraphDb)
- throws IOException {
+ public void analyze(Path webGraphDb) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -621,7 +632,7 @@ public class LinkRank
// initialze all urls with a default score
int numLinks = runCounter(fs, webGraphDb);
runInitializer(wgNodeDb, nodeDb);
- float rankOneScore = (1f / (float)numLinks);
+ float rankOneScore = (1f / (float) numLinks);
if (LOG.isInfoEnabled()) {
LOG.info("Analysis: Number of links: " + numLinks);
@@ -634,9 +645,10 @@ public class LinkRank
for (int i = 0; i < numIterations; i++) {
// the input to inverting is always the previous output from analysis
- LOG.info("Analysis: Starting iteration " + (i + 1) + " of " + numIterations);
+ LOG.info("Analysis: Starting iteration " + (i + 1) + " of "
+ + numIterations);
Path tempRank = new Path(linkRank + "-"
- + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
fs.mkdirs(tempRank);
Path tempInverted = new Path(tempRank, "inverted");
Path tempNodeDb = new Path(tempRank, WebGraph.NODE_DIR);
@@ -644,13 +656,13 @@ public class LinkRank
// run invert and analysis
runInverter(nodeDb, wgOutlinkDb, loopDb, tempInverted);
runAnalysis(nodeDb, tempInverted, tempNodeDb, i, numIterations,
- rankOneScore);
+ rankOneScore);
// replace the temporary NodeDb with the output from analysis
LOG.info("Analysis: Installing new link scores");
FSUtils.replace(fs, linkRank, tempRank, true);
LOG.info("Analysis: finished iteration " + (i + 1) + " of "
- + numIterations);
+ + numIterations);
}
// replace the NodeDb in the WebGraph with the final output of analysis
@@ -660,11 +672,11 @@ public class LinkRank
// remove the temporary link rank folder
fs.delete(linkRank, true);
long end = System.currentTimeMillis();
- LOG.info("Analysis: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("Analysis: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- public static void main(String[] args)
- throws Exception {
+ public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new LinkRank(), args);
System.exit(res);
}
@@ -672,15 +684,14 @@ public class LinkRank
/**
* Runs the LinkRank tool.
*/
- public int run(String[] args)
- throws Exception {
+ public int run(String[] args) throws Exception {
Options options = new Options();
OptionBuilder.withArgName("help");
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("webgraphdb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the web graph db to use");
@@ -701,8 +712,7 @@ public class LinkRank
analyze(new Path(webGraphDb));
return 0;
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("LinkAnalysis: " + StringUtils.stringifyException(e));
return -2;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LoopReader.java b/src/java/org/apache/nutch/scoring/webgraph/LoopReader.java
index c2ca35643..24051288d 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LoopReader.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LoopReader.java
@@ -44,35 +44,38 @@ public class LoopReader extends Configured {
private FileSystem fs;
private MapFile.Reader[] loopReaders;
-
- public LoopReader() { }
-
+
+ public LoopReader() {
+ }
+
public LoopReader(Configuration conf) {
super(conf);
}
/**
- * Prints loopset for a single url. The loopset information will show any
+ * Prints loopset for a single url. The loopset information will show any
* outlink url the eventually forms a link cycle.
*
- * @param webGraphDb The WebGraph to check for loops
- * @param url The url to check.
+ * @param webGraphDb
+ * The WebGraph to check for loops
+ * @param url
+ * The url to check.
*
- * @throws IOException If an error occurs while printing loopset information.
+ * @throws IOException
+ * If an error occurs while printing loopset information.
*/
- public void dumpUrl(Path webGraphDb, String url)
- throws IOException {
+ public void dumpUrl(Path webGraphDb, String url) throws IOException {
// open the readers
fs = FileSystem.get(getConf());
loopReaders = MapFileOutputFormat.getReaders(fs, new Path(webGraphDb,
- Loops.LOOPS_DIR), getConf());
+ Loops.LOOPS_DIR), getConf());
// get the loopset for a given url, if any
Text key = new Text(url);
LoopSet loop = new LoopSet();
MapFileOutputFormat.getEntry(loopReaders,
- new HashPartitioner<Text, LoopSet>(), key, loop);
+ new HashPartitioner<Text, LoopSet>(), key, loop);
// print out each loop url in the set
System.out.println(url + ":");
@@ -85,24 +88,23 @@ public class LoopReader extends Configured {
}
/**
- * Runs the LoopReader tool. For this tool to work the loops job must have
+ * Runs the LoopReader tool. For this tool to work the loops job must have
* already been run on the corresponding WebGraph.
*/
- public static void main(String[] args)
- throws Exception {
+ public static void main(String[] args) throws Exception {
Options options = new Options();
OptionBuilder.withArgName("help");
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("webgraphdb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the webgraphdb to use");
Option webGraphOpts = OptionBuilder.create("webgraphdb");
options.addOption(webGraphOpts);
-
+
OptionBuilder.withArgName("url");
OptionBuilder.hasOptionalArg();
OptionBuilder.withDescription("the url to dump");
@@ -114,7 +116,7 @@ public class LoopReader extends Configured {
CommandLine line = parser.parse(options, args);
if (line.hasOption("help") || !line.hasOption("webgraphdb")
- || !line.hasOption("url")) {
+ || !line.hasOption("url")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("WebGraphReader", options);
return;
@@ -125,8 +127,7 @@ public class LoopReader extends Configured {
LoopReader reader = new LoopReader(NutchConfiguration.create());
reader.dumpUrl(new Path(webGraphDb), url);
return;
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
return;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/Loops.java b/src/java/org/apache/nutch/scoring/webgraph/Loops.java
index 009ee836d..708742e95 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/Loops.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/Loops.java
@@ -76,9 +76,7 @@ import org.apache.nutch.util.TimingUtil;
* rather small. Because of this the Loops job is optional and if it doesn't
* exist then it won't be factored into the LinkRank program.
*/
-public class Loops
- extends Configured
- implements Tool {
+public class Loops extends Configured implements Tool {
public static final Logger LOG = LoggerFactory.getLogger(Loops.class);
public static final String LOOPS_DIR = "loops";
@@ -87,8 +85,7 @@ public class Loops
/**
* A link path or route looking to identify a link cycle.
*/
- public static class Route
- implements Writable {
+ public static class Route implements Writable {
private String outlinkUrl = null;
private String lookingFor = null;
@@ -122,16 +119,14 @@ public class Loops
this.found = found;
}
- public void readFields(DataInput in)
- throws IOException {
+ public void readFields(DataInput in) throws IOException {
outlinkUrl = Text.readString(in);
lookingFor = Text.readString(in);
found = in.readBoolean();
}
- public void write(DataOutput out)
- throws IOException {
+ public void write(DataOutput out) throws IOException {
Text.writeString(out, outlinkUrl);
Text.writeString(out, lookingFor);
out.writeBoolean(found);
@@ -141,8 +136,7 @@ public class Loops
/**
* A set of loops.
*/
- public static class LoopSet
- implements Writable {
+ public static class LoopSet implements Writable {
private Set<String> loopSet = new HashSet<String>();
@@ -158,8 +152,7 @@ public class Loops
this.loopSet = loopSet;
}
- public void readFields(DataInput in)
- throws IOException {
+ public void readFields(DataInput in) throws IOException {
int numNodes = in.readInt();
loopSet = new HashSet<String>();
@@ -169,8 +162,7 @@ public class Loops
}
}
- public void write(DataOutput out)
- throws IOException {
+ public void write(DataOutput out) throws IOException {
int numNodes = (loopSet != null ? loopSet.size() : 0);
out.writeInt(numNodes);
@@ -191,10 +183,9 @@ public class Loops
/**
* Initializes the Loop routes.
*/
- public static class Initializer
- extends Configured
- implements Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, Route> {
+ public static class Initializer extends Configured implements
+ Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, Route> {
private JobConf conf;
@@ -222,8 +213,8 @@ public class Loops
* Wraps values in ObjectWritable.
*/
public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
ObjectWritable objWrite = new ObjectWritable();
objWrite.set(value);
@@ -236,8 +227,8 @@ public class Loops
* the Looper job.
*/
public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, Route> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, Route> output, Reporter reporter)
+ throws IOException {
String url = key.toString();
Node node = null;
@@ -248,10 +239,9 @@ public class Loops
ObjectWritable objWrite = values.next();
Object obj = objWrite.get();
if (obj instanceof LinkDatum) {
- outlinkList.add((LinkDatum)obj);
- }
- else if (obj instanceof Node) {
- node = (Node)obj;
+ outlinkList.add((LinkDatum) obj);
+ } else if (obj instanceof Node) {
+ node = (Node) obj;
}
}
@@ -282,10 +272,9 @@ public class Loops
* Follows a route path looking for the start url of the route. If the start
* url is found then the route is a cyclical path.
*/
- public static class Looper
- extends Configured
- implements Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, Route> {
+ public static class Looper extends Configured implements
+ Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, Route> {
private JobConf conf;
private boolean last = false;
@@ -315,15 +304,14 @@ public class Loops
* Wrap values in ObjectWritable.
*/
public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
ObjectWritable objWrite = new ObjectWritable();
Writable cloned = null;
if (value instanceof LinkDatum) {
- cloned = new Text(((LinkDatum)value).getUrl());
- }
- else {
+ cloned = new Text(((LinkDatum) value).getUrl());
+ } else {
cloned = WritableUtils.clone(value, conf);
}
objWrite.set(cloned);
@@ -336,8 +324,8 @@ public class Loops
* passes.
*/
public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, Route> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, Route> output, Reporter reporter)
+ throws IOException {
List<Route> routeList = new ArrayList<Route>();
Set<String> outlinkUrls = new LinkedHashSet<String>();
@@ -348,10 +336,9 @@ public class Loops
ObjectWritable next = values.next();
Object value = next.get();
if (value instanceof Route) {
- routeList.add(WritableUtils.clone((Route)value, conf));
- }
- else if (value instanceof Text) {
- String outlinkUrl = ((Text)value).toString();
+ routeList.add(WritableUtils.clone((Route) value, conf));
+ } else if (value instanceof Text) {
+ String outlinkUrl = ((Text) value).toString();
if (!outlinkUrls.contains(outlinkUrl)) {
outlinkUrls.add(outlinkUrl);
}
@@ -375,16 +362,14 @@ public class Loops
routeIt.remove();
if (route.isFound()) {
output.collect(key, route);
- }
- else {
+ } else {
// if the route start url is found, set route to found and collect
String lookingFor = route.getLookingFor();
if (outlinkUrls.contains(lookingFor)) {
route.setFound(true);
output.collect(key, route);
- }
- else if (!last) {
+ } else if (!last) {
// setup for next pass through the loop
for (String outlink : outlinkUrls) {
@@ -402,10 +387,8 @@ public class Loops
/**
* Finishes the Loops job by aggregating and collecting and found routes.
*/
- public static class Finalizer
- extends Configured
- implements Mapper<Text, Route, Text, Route>,
- Reducer<Text, Route, Text, LoopSet> {
+ public static class Finalizer extends Configured implements
+ Mapper<Text, Route, Text, Route>, Reducer<Text, Route, Text, LoopSet> {
private JobConf conf;
@@ -433,8 +416,7 @@ public class Loops
* Maps out and found routes, those will be the link cycles.
*/
public void map(Text key, Route value, OutputCollector<Text, Route> output,
- Reporter reporter)
- throws IOException {
+ Reporter reporter) throws IOException {
if (value.isFound()) {
String lookingFor = value.getLookingFor();
@@ -443,12 +425,12 @@ public class Loops
}
/**
- * Aggregates all found routes for a given start url into a loopset and
+ * Aggregates all found routes for a given start url into a loopset and
* collects the loopset.
*/
public void reduce(Text key, Iterator<Route> values,
- OutputCollector<Text, LoopSet> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, LoopSet> output, Reporter reporter)
+ throws IOException {
LoopSet loops = new LoopSet();
while (values.hasNext()) {
@@ -465,8 +447,7 @@ public class Loops
/**
* Runs the various loop jobs.
*/
- public void findLoops(Path webGraphDb)
- throws IOException {
+ public void findLoops(Path webGraphDb) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -481,7 +462,7 @@ public class Loops
Path nodeDb = new Path(webGraphDb, WebGraph.NODE_DIR);
Path routes = new Path(webGraphDb, ROUTES_DIR);
Path tempRoute = new Path(webGraphDb, ROUTES_DIR + "-"
- + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
// run the initializer
JobConf init = new NutchJob(conf);
@@ -504,8 +485,7 @@ public class Loops
LOG.info("Loops: installing initializer " + routes);
FSUtils.replace(fs, routes, tempRoute, true);
LOG.info("Loops: finished initializer");
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -536,8 +516,7 @@ public class Loops
LOG.info("Loops: installing looper " + routes);
FSUtils.replace(fs, routes, tempRoute, true);
LOG.info("Loops: finished looper");
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -561,17 +540,16 @@ public class Loops
LOG.info("Loops: starting finalizer");
JobClient.runJob(finalizer);
LOG.info("Loops: finished finalizer");
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
long end = System.currentTimeMillis();
- LOG.info("Loops: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("Loops: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- public static void main(String[] args)
- throws Exception {
+ public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new Loops(), args);
System.exit(res);
}
@@ -579,15 +557,14 @@ public class Loops
/**
* Runs the Loops tool.
*/
- public int run(String[] args)
- throws Exception {
+ public int run(String[] args) throws Exception {
Options options = new Options();
OptionBuilder.withArgName("help");
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("webgraphdb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the web graph database to use");
@@ -607,8 +584,7 @@ public class Loops
String webGraphDb = line.getOptionValue("webgraphdb");
findLoops(new Path(webGraphDb));
return 0;
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("Loops: " + StringUtils.stringifyException(e));
return -2;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/Node.java b/src/java/org/apache/nutch/scoring/webgraph/Node.java
index 9ade35663..a35e84288 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/Node.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/Node.java
@@ -25,12 +25,11 @@ import org.apache.nutch.metadata.Metadata;
/**
* A class which holds the number of inlinks and outlinks for a given url along
- * with an inlink score from a link analysis program and any metadata.
+ * with an inlink score from a link analysis program and any metadata.
*
* The Node is the core unit of the NodeDb in the WebGraph.
*/
-public class Node
- implements Writable {
+public class Node implements Writable {
private int numInlinks = 0;
private int numOutlinks = 0;
@@ -77,8 +76,7 @@ public class Node
this.metadata = metadata;
}
- public void readFields(DataInput in)
- throws IOException {
+ public void readFields(DataInput in) throws IOException {
numInlinks = in.readInt();
numOutlinks = in.readInt();
@@ -87,8 +85,7 @@ public class Node
metadata.readFields(in);
}
- public void write(DataOutput out)
- throws IOException {
+ public void write(DataOutput out) throws IOException {
out.writeInt(numInlinks);
out.writeInt(numOutlinks);
@@ -98,8 +95,8 @@ public class Node
public String toString() {
return "num inlinks: " + numInlinks + ", num outlinks: " + numOutlinks
- + ", inlink score: " + inlinkScore + ", outlink score: "
- + getOutlinkScore() + ", metadata: " + metadata.toString();
+ + ", inlink score: " + inlinkScore + ", outlink score: "
+ + getOutlinkScore() + ", metadata: " + metadata.toString();
}
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java b/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
index c06b9dc11..4a57c29d1 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
@@ -63,26 +63,20 @@ import org.apache.nutch.util.URLUtil;
* have been run. For link analysis score a program such as LinkRank will need
* to have been run which updates the NodeDb of the WebGraph.
*/
-public class NodeDumper
- extends Configured
- implements Tool {
+public class NodeDumper extends Configured implements Tool {
public static final Logger LOG = LoggerFactory.getLogger(NodeDumper.class);
private static enum DumpType {
- INLINKS,
- OUTLINKS,
- SCORES
+ INLINKS, OUTLINKS, SCORES
}
private static enum AggrType {
- SUM,
- MAX
+ SUM, MAX
}
private static enum NameType {
- HOST,
- DOMAIN
+ HOST, DOMAIN
}
/**
@@ -90,10 +84,9 @@ public class NodeDumper
* on the command line, the top urls could be for number of inlinks, for
* number of outlinks, or for link analysis score.
*/
- public static class Sorter
- extends Configured
- implements Mapper<Text, Node, FloatWritable, Text>,
- Reducer<FloatWritable, Text, Text, FloatWritable> {
+ public static class Sorter extends Configured implements
+ Mapper<Text, Node, FloatWritable, Text>,
+ Reducer<FloatWritable, Text, Text, FloatWritable> {
private JobConf conf;
private boolean inlinks = false;
@@ -121,17 +114,15 @@ public class NodeDumper
* score.
*/
public void map(Text key, Node node,
- OutputCollector<FloatWritable, Text> output, Reporter reporter)
- throws IOException {
+ OutputCollector<FloatWritable, Text> output, Reporter reporter)
+ throws IOException {
float number = 0;
if (inlinks) {
number = node.getNumInlinks();
- }
- else if (outlinks) {
+ } else if (outlinks) {
number = node.getNumOutlinks();
- }
- else {
+ } else {
number = node.getInlinkScore();
}
@@ -143,8 +134,8 @@ public class NodeDumper
* Flips and collects the url and numeric sort value.
*/
public void reduce(FloatWritable key, Iterator<Text> values,
- OutputCollector<Text, FloatWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, FloatWritable> output, Reporter reporter)
+ throws IOException {
// take the negative of the negative to get original value, sometimes 0
// value are a little weird
@@ -162,14 +153,13 @@ public class NodeDumper
}
/**
- * Outputs the hosts or domains with an associated value. This value consists of either
- * the number of inlinks, the number of outlinks or the score. The computed value is then
- * either the sum of all parts or the top value.
+ * Outputs the hosts or domains with an associated value. This value consists
+ * of either the number of inlinks, the number of outlinks or the score. The
+ * computed value is then either the sum of all parts or the top value.
*/
- public static class Dumper
- extends Configured
- implements Mapper<Text, Node, Text, FloatWritable>,
- Reducer<Text, FloatWritable, Text, FloatWritable> {
+ public static class Dumper extends Configured implements
+ Mapper<Text, Node, Text, FloatWritable>,
+ Reducer<Text, FloatWritable, Text, FloatWritable> {
private JobConf conf;
private boolean inlinks = false;
@@ -197,21 +187,19 @@ public class NodeDumper
}
/**
- * Outputs the host or domain as key for this record and numInlinks, numOutlinks
- * or score as the value.
+ * Outputs the host or domain as key for this record and numInlinks,
+ * numOutlinks or score as the value.
*/
public void map(Text key, Node node,
- OutputCollector<Text, FloatWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, FloatWritable> output, Reporter reporter)
+ throws IOException {
float number = 0;
if (inlinks) {
number = node.getNumInlinks();
- }
- else if (outlinks) {
+ } else if (outlinks) {
number = node.getNumOutlinks();
- }
- else {
+ } else {
number = node.getInlinkScore();
}
@@ -228,8 +216,8 @@ public class NodeDumper
* Outputs either the sum or the top value for this record.
*/
public void reduce(Text key, Iterator<FloatWritable> values,
- OutputCollector<Text, FloatWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, FloatWritable> output, Reporter reporter)
+ throws IOException {
long numCollected = 0;
float sumOrMax = 0;
@@ -256,16 +244,19 @@ public class NodeDumper
/**
* Runs the process to dump the top urls out to a text file.
- *
- * @param webGraphDb The WebGraph from which to pull values.
- *
+ *
+ * @param webGraphDb
+ * The WebGraph from which to pull values.
+ *
* @param topN
* @param output
- *
- * @throws IOException If an error occurs while dumping the top values.
+ *
+ * @throws IOException
+ * If an error occurs while dumping the top values.
*/
- public void dumpNodes(Path webGraphDb, DumpType type, long topN, Path output, boolean asEff, NameType nameType, AggrType aggrType, boolean asSequenceFile)
- throws Exception {
+ public void dumpNodes(Path webGraphDb, DumpType type, long topN, Path output,
+ boolean asEff, NameType nameType, AggrType aggrType,
+ boolean asSequenceFile) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -320,77 +311,76 @@ public class NodeDumper
try {
LOG.info("NodeDumper: running");
JobClient.runJob(dumper);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
long end = System.currentTimeMillis();
- LOG.info("NodeDumper: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("NodeDumper: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- public static void main(String[] args)
- throws Exception {
+ public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new NodeDumper(),
- args);
+ args);
System.exit(res);
}
/**
* Runs the node dumper tool.
*/
- public int run(String[] args)
- throws Exception {
+ public int run(String[] args) throws Exception {
Options options = new Options();
OptionBuilder.withArgName("help");
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("webgraphdb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the web graph database to use");
Option webGraphDbOpts = OptionBuilder.create("webgraphdb");
options.addOption(webGraphDbOpts);
-
+
OptionBuilder.withArgName("inlinks");
OptionBuilder.withDescription("show highest inlinks");
Option inlinkOpts = OptionBuilder.create("inlinks");
options.addOption(inlinkOpts);
-
+
OptionBuilder.withArgName("outlinks");
OptionBuilder.withDescription("show highest outlinks");
Option outlinkOpts = OptionBuilder.create("outlinks");
options.addOption(outlinkOpts);
-
+
OptionBuilder.withArgName("scores");
OptionBuilder.withDescription("show highest scores");
Option scoreOpts = OptionBuilder.create("scores");
options.addOption(scoreOpts);
-
+
OptionBuilder.withArgName("topn");
OptionBuilder.hasOptionalArg();
OptionBuilder.withDescription("show topN scores");
Option topNOpts = OptionBuilder.create("topn");
options.addOption(topNOpts);
-
+
OptionBuilder.withArgName("output");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the output directory to use");
Option outputOpts = OptionBuilder.create("output");
options.addOption(outputOpts);
-
+
OptionBuilder.withArgName("asEff");
- OptionBuilder.withDescription("Solr ExternalFileField compatible output format");
+ OptionBuilder
+ .withDescription("Solr ExternalFileField compatible output format");
Option effOpts = OptionBuilder.create("asEff");
options.addOption(effOpts);
-
+
OptionBuilder.hasArgs(2);
OptionBuilder.withDescription("group <host|domain> <sum|max>");
Option groupOpts = OptionBuilder.create("group");
options.addOption(groupOpts);
-
+
OptionBuilder.withArgName("asSequenceFile");
OptionBuilder.withDescription("whether to output as a sequencefile");
Option sequenceFileOpts = OptionBuilder.create("asSequenceFile");
@@ -410,32 +400,32 @@ public class NodeDumper
boolean inlinks = line.hasOption("inlinks");
boolean outlinks = line.hasOption("outlinks");
- long topN = (line.hasOption("topn")
- ? Long.parseLong(line.getOptionValue("topn")) : Long.MAX_VALUE);
+ long topN = (line.hasOption("topn") ? Long.parseLong(line
+ .getOptionValue("topn")) : Long.MAX_VALUE);
// get the correct dump type
String output = line.getOptionValue("output");
- DumpType type = (inlinks ? DumpType.INLINKS : outlinks
- ? DumpType.OUTLINKS : DumpType.SCORES);
+ DumpType type = (inlinks ? DumpType.INLINKS
+ : outlinks ? DumpType.OUTLINKS : DumpType.SCORES);
NameType nameType = null;
AggrType aggrType = null;
String[] group = line.getOptionValues("group");
if (group != null && group.length == 2) {
- nameType = (group[0].equals("host") ? NameType.HOST : group[0].equals("domain")
- ? NameType.DOMAIN : null);
- aggrType = (group[1].equals("sum") ? AggrType.SUM : group[1].equals("sum")
- ? AggrType.MAX : null);
+ nameType = (group[0].equals("host") ? NameType.HOST : group[0]
+ .equals("domain") ? NameType.DOMAIN : null);
+ aggrType = (group[1].equals("sum") ? AggrType.SUM : group[1]
+ .equals("sum") ? AggrType.MAX : null);
}
// Use ExternalFileField?
boolean asEff = line.hasOption("asEff");
boolean asSequenceFile = line.hasOption("asSequenceFile");
- dumpNodes(new Path(webGraphDb), type, topN, new Path(output), asEff, nameType, aggrType, asSequenceFile);
+ dumpNodes(new Path(webGraphDb), type, topN, new Path(output), asEff,
+ nameType, aggrType, asSequenceFile);
return 0;
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("NodeDumper: " + StringUtils.stringifyException(e));
return -2;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java b/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java
index 72c7a9b28..e6b681558 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java
@@ -37,7 +37,7 @@ import org.apache.nutch.util.FSUtils;
import org.apache.nutch.util.NutchConfiguration;
/**
- * Reads and prints to system out information for a single node from the NodeDb
+ * Reads and prints to system out information for a single node from the NodeDb
* in the WebGraph.
*/
public class NodeReader extends Configured {
@@ -46,33 +46,35 @@ public class NodeReader extends Configured {
private MapFile.Reader[] nodeReaders;
public NodeReader() {
-
+
}
-
+
public NodeReader(Configuration conf) {
super(conf);
}
-
+
/**
* Prints the content of the Node represented by the url to system out.
*
- * @param webGraphDb The webgraph from which to get the node.
- * @param url The url of the node.
+ * @param webGraphDb
+ * The webgraph from which to get the node.
+ * @param url
+ * The url of the node.
*
- * @throws IOException If an error occurs while getting the node.
+ * @throws IOException
+ * If an error occurs while getting the node.
*/
- public void dumpUrl(Path webGraphDb, String url)
- throws IOException {
+ public void dumpUrl(Path webGraphDb, String url) throws IOException {
fs = FileSystem.get(getConf());
nodeReaders = MapFileOutputFormat.getReaders(fs, new Path(webGraphDb,
- WebGraph.NODE_DIR), getConf());
+ WebGraph.NODE_DIR), getConf());
// open the readers, get the node, print out the info, and close the readers
Text key = new Text(url);
Node node = new Node();
MapFileOutputFormat.getEntry(nodeReaders,
- new HashPartitioner<Text, Node>(), key, node);
+ new HashPartitioner<Text, Node>(), key, node);
System.out.println(url + ":");
System.out.println(" inlink score: " + node.getInlinkScore());
System.out.println(" outlink score: " + node.getOutlinkScore());
@@ -82,25 +84,24 @@ public class NodeReader extends Configured {
}
/**
- * Runs the NodeReader tool. The command line arguments must contain a
- * webgraphdb path and a url. The url must match the normalized url that is
+ * Runs the NodeReader tool. The command line arguments must contain a
+ * webgraphdb path and a url. The url must match the normalized url that is
* contained in the NodeDb of the WebGraph.
*/
- public static void main(String[] args)
- throws Exception {
+ public static void main(String[] args) throws Exception {
Options options = new Options();
OptionBuilder.withArgName("help");
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("webgraphdb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the webgraphdb to use");
Option webGraphOpts = OptionBuilder.create("webgraphdb");
options.addOption(webGraphOpts);
-
+
OptionBuilder.withArgName("url");
OptionBuilder.hasOptionalArg();
OptionBuilder.withDescription("the url to dump");
@@ -113,7 +114,7 @@ public class NodeReader extends Configured {
// command line must take a webgraphdb and a url
CommandLine line = parser.parse(options, args);
if (line.hasOption("help") || !line.hasOption("webgraphdb")
- || !line.hasOption("url")) {
+ || !line.hasOption("url")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("WebGraphReader", options);
return;
@@ -124,10 +125,9 @@ public class NodeReader extends Configured {
String url = line.getOptionValue("url");
NodeReader reader = new NodeReader(NutchConfiguration.create());
reader.dumpUrl(new Path(webGraphDb), url);
-
+
return;
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
return;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java b/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
index 7a13739e2..19704ebce 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
@@ -58,13 +58,12 @@ import org.apache.nutch.util.TimingUtil;
/**
* Updates the score from the WebGraph node database into the crawl database.
- * Any score that is not in the node database is set to the clear score in the
+ * Any score that is not in the node database is set to the clear score in the
* crawl database.
*/
-public class ScoreUpdater
- extends Configured
- implements Tool, Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, CrawlDatum> {
+public class ScoreUpdater extends Configured implements Tool,
+ Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, CrawlDatum> {
public static final Logger LOG = LoggerFactory.getLogger(ScoreUpdater.class);
@@ -80,8 +79,8 @@ public class ScoreUpdater
* Changes input into ObjectWritables.
*/
public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
ObjectWritable objWrite = new ObjectWritable();
objWrite.set(value);
@@ -93,8 +92,8 @@ public class ScoreUpdater
* with a cleared score.
*/
public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
String url = key.toString();
Node node = null;
@@ -106,34 +105,31 @@ public class ScoreUpdater
ObjectWritable next = values.next();
Object value = next.get();
if (value instanceof Node) {
- node = (Node)value;
- }
- else if (value instanceof CrawlDatum) {
- datum = (CrawlDatum)value;
+ node = (Node) value;
+ } else if (value instanceof CrawlDatum) {
+ datum = (CrawlDatum) value;
}
}
- // datum should never be null, could happen if somehow the url was
+ // datum should never be null, could happen if somehow the url was
// normalized or changed after being pulled from the crawldb
if (datum != null) {
if (node != null) {
-
+
// set the inlink score in the nodedb
float inlinkScore = node.getInlinkScore();
datum.setScore(inlinkScore);
LOG.debug(url + ": setting to score " + inlinkScore);
- }
- else {
-
+ } else {
+
// clear out the score in the crawldb
datum.setScore(clearScore);
LOG.debug(url + ": setting to clear score of " + clearScore);
}
output.collect(key, datum);
- }
- else {
+ } else {
LOG.debug(url + ": no datum");
}
}
@@ -142,16 +138,18 @@ public class ScoreUpdater
}
/**
- * Updates the inlink score in the web graph node databsae into the crawl
+ * Updates the inlink score in the web graph node databsae into the crawl
* database.
*
- * @param crawlDb The crawl database to update
- * @param webGraphDb The webgraph database to use.
+ * @param crawlDb
+ * The crawl database to update
+ * @param webGraphDb
+ * The webgraph database to use.
*
- * @throws IOException If an error occurs while updating the scores.
+ * @throws IOException
+ * If an error occurs while updating the scores.
*/
- public void update(Path crawlDb, Path webGraphDb)
- throws IOException {
+ public void update(Path crawlDb, Path webGraphDb) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -164,8 +162,8 @@ public class ScoreUpdater
LOG.info("Running crawldb update " + crawlDb);
Path nodeDb = new Path(webGraphDb, WebGraph.NODE_DIR);
Path crawlDbCurrent = new Path(crawlDb, CrawlDb.CURRENT_NAME);
- Path newCrawlDb = new Path(crawlDb,
- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ Path newCrawlDb = new Path(crawlDb, Integer.toString(new Random()
+ .nextInt(Integer.MAX_VALUE)));
// run the updater job outputting to the temp crawl database
JobConf updater = new NutchJob(conf);
@@ -184,10 +182,9 @@ public class ScoreUpdater
try {
JobClient.runJob(updater);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
-
+
// remove the temp crawldb on error
if (fs.exists(newCrawlDb)) {
fs.delete(newCrawlDb, true);
@@ -200,34 +197,33 @@ public class ScoreUpdater
CrawlDb.install(updater, crawlDb);
long end = System.currentTimeMillis();
- LOG.info("ScoreUpdater: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("ScoreUpdater: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
- public static void main(String[] args)
- throws Exception {
+ public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new ScoreUpdater(),
- args);
+ args);
System.exit(res);
}
/**
* Runs the ScoreUpdater tool.
*/
- public int run(String[] args)
- throws Exception {
+ public int run(String[] args) throws Exception {
Options options = new Options();
OptionBuilder.withArgName("help");
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("crawldb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the crawldb to use");
Option crawlDbOpts = OptionBuilder.create("crawldb");
options.addOption(crawlDbOpts);
-
+
OptionBuilder.withArgName("webgraphdb");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the webgraphdb to use");
@@ -239,7 +235,7 @@ public class ScoreUpdater
CommandLine line = parser.parse(options, args);
if (line.hasOption("help") || !line.hasOption("webgraphdb")
- || !line.hasOption("crawldb")) {
+ || !line.hasOption("crawldb")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ScoreUpdater", options);
return -1;
@@ -249,8 +245,7 @@ public class ScoreUpdater
String webGraphDb = line.getOptionValue("webgraphdb");
update(new Path(crawlDb), new Path(webGraphDb));
return 0;
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("ScoreUpdater: " + StringUtils.stringifyException(e));
return -1;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java b/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
index 5079ba608..e2c3d8b46 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
@@ -107,8 +107,9 @@ public class WebGraph extends Configured implements Tool {
* by domain and host can be ignored. The number of Outlinks out to a given
* page or domain can also be limited.
*/
- public static class OutlinkDb extends Configured implements
- Mapper<Text, Writable, Text, NutchWritable>, Reducer<Text, NutchWritable, Text, LinkDatum> {
+ public static class OutlinkDb extends Configured implements
+ Mapper<Text, Writable, Text, NutchWritable>,
+ Reducer<Text, NutchWritable, Text, LinkDatum> {
public static final String URL_NORMALIZING = "webgraph.url.normalizers";
public static final String URL_FILTERING = "webgraph.url.filters";
@@ -133,7 +134,8 @@ public class WebGraph extends Configured implements Tool {
/**
* Normalizes and trims extra whitespace from the given url.
*
- * @param url The url to normalize.
+ * @param url
+ * The url to normalize.
*
* @return The normalized url.
*/
@@ -151,8 +153,7 @@ public class WebGraph extends Configured implements Tool {
normalized = urlNormalizers.normalize(url,
URLNormalizers.SCOPE_DEFAULT);
normalized = normalized.trim();
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.warn("Skipping " + url + ":" + e);
normalized = null;
}
@@ -162,9 +163,10 @@ public class WebGraph extends Configured implements Tool {
/**
* Filters the given url.
- *
- * @param url The url to filter.
- *
+ *
+ * @param url
+ * The url to filter.
+ *
* @return The filtered url or null.
*/
private String filterUrl(String url) {
@@ -186,7 +188,8 @@ public class WebGraph extends Configured implements Tool {
* Returns the fetch time from the parse data or the current system time if
* the fetch time doesn't exist.
*
- * @param data The parse data.
+ * @param data
+ * The parse data.
*
* @return The fetch time as a long.
*/
@@ -198,8 +201,7 @@ public class WebGraph extends Configured implements Tool {
try {
// get the fetch time from the parse data
fetchTime = Long.parseLong(fetchTimeStr);
- }
- catch (Exception e) {
+ } catch (Exception e) {
fetchTime = System.currentTimeMillis();
}
return fetchTime;
@@ -244,8 +246,9 @@ public class WebGraph extends Configured implements Tool {
* Passes through existing LinkDatum objects from an existing OutlinkDb and
* maps out new LinkDatum objects from new crawls ParseData.
*/
- public void map(Text key, Writable value, OutputCollector<Text, NutchWritable>
- output, Reporter reporter) throws IOException {
+ public void map(Text key, Writable value,
+ OutputCollector<Text, NutchWritable> output, Reporter reporter)
+ throws IOException {
// normalize url, stop processing if null
String url = normalizeUrl(key.toString());
@@ -262,20 +265,19 @@ public class WebGraph extends Configured implements Tool {
key.set(url);
if (value instanceof CrawlDatum) {
- CrawlDatum datum = (CrawlDatum)value;
+ CrawlDatum datum = (CrawlDatum) value;
- if (datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP ||
- datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM ||
- datum.getStatus() == CrawlDatum.STATUS_FETCH_GONE) {
+ if (datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP
+ || datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM
+ || datum.getStatus() == CrawlDatum.STATUS_FETCH_GONE) {
// Tell the reducer to get rid of all instances of this key
output.collect(key, new NutchWritable(new BooleanWritable(true)));
}
- }
- else if (value instanceof ParseData) {
+ } else if (value instanceof ParseData) {
// get the parse data and the outlinks from the parse data, along with
// the fetch time for those links
- ParseData data = (ParseData)value;
+ ParseData data = (ParseData) value;
long fetchTime = getFetchTime(data);
Outlink[] outlinkAr = data.getOutlinks();
Map<String, String> outlinkMap = new LinkedHashMap<String, String>();
@@ -307,9 +309,8 @@ public class WebGraph extends Configured implements Tool {
LinkDatum datum = new LinkDatum(outlinkUrl, anchor, fetchTime);
output.collect(key, new NutchWritable(datum));
}
- }
- else if (value instanceof LinkDatum) {
- LinkDatum datum = (LinkDatum)value;
+ } else if (value instanceof LinkDatum) {
+ LinkDatum datum = (LinkDatum) value;
String linkDatumUrl = normalizeUrl(datum.getUrl());
if (filterUrl(linkDatumUrl) != null) {
@@ -323,7 +324,7 @@ public class WebGraph extends Configured implements Tool {
public void reduce(Text key, Iterator<NutchWritable> values,
OutputCollector<Text, LinkDatum> output, Reporter reporter)
- throws IOException {
+ throws IOException {
// aggregate all outlinks, get the most recent timestamp for a fetch
// which should be the timestamp for all of the most recent outlinks
@@ -334,17 +335,17 @@ public class WebGraph extends Configured implements Tool {
if (value instanceof LinkDatum) {
// loop through, change out most recent timestamp if needed
- LinkDatum next = (LinkDatum)value;
+ LinkDatum next = (LinkDatum) value;
long timestamp = next.getTimestamp();
if (mostRecent == 0L || mostRecent < timestamp) {
mostRecent = timestamp;
}
outlinkList.add(WritableUtils.clone(next, conf));
reporter.incrCounter("WebGraph.outlinks", "added links", 1);
- }
- else if (value instanceof BooleanWritable) {
- BooleanWritable delete = (BooleanWritable)value;
- // Actually, delete is always true, otherwise we don't emit it in the mapper in the first place
+ } else if (value instanceof BooleanWritable) {
+ BooleanWritable delete = (BooleanWritable) value;
+ // Actually, delete is always true, otherwise we don't emit it in the
+ // mapper in the first place
if (delete.get() == true) {
// This page is gone, do not emit it's outlinks
reporter.incrCounter("WebGraph.outlinks", "removed links", 1);
@@ -378,7 +379,8 @@ public class WebGraph extends Configured implements Tool {
&& (!limitPages || (limitPages && !pages.contains(toPage)))
&& (!limitDomains || (limitDomains && !domains.contains(toDomain)))
&& (!ignoreHost || (ignoreHost && !toHost.equalsIgnoreCase(host)))
- && (!ignoreDomain || (ignoreDomain && !toDomain.equalsIgnoreCase(domain)))) {
+ && (!ignoreDomain || (ignoreDomain && !toDomain
+ .equalsIgnoreCase(domain)))) {
output.collect(key, datum);
pages.add(toPage);
domains.add(toDomain);
@@ -395,7 +397,8 @@ public class WebGraph extends Configured implements Tool {
* OutlinkDb LinkDatum objects and are regenerated each time the WebGraph is
* updated.
*/
- private static class InlinkDb extends Configured implements Mapper<Text, LinkDatum, Text, LinkDatum> {
+ private static class InlinkDb extends Configured implements
+ Mapper<Text, LinkDatum, Text, LinkDatum> {
private long timestamp;
@@ -414,8 +417,9 @@ public class WebGraph extends Configured implements Tool {
* Inverts the Outlink LinkDatum objects into new LinkDatum objects with a
* new system timestamp, type and to and from url switched.
*/
- public void map(Text key, LinkDatum datum, OutputCollector<Text, LinkDatum>
- output, Reporter reporter) throws IOException {
+ public void map(Text key, LinkDatum datum,
+ OutputCollector<Text, LinkDatum> output, Reporter reporter)
+ throws IOException {
// get the to and from url and the anchor
String fromUrl = key.toString();
@@ -433,21 +437,25 @@ public class WebGraph extends Configured implements Tool {
* Creates the Node database which consists of the number of in and outlinks
* for each url and a score slot for analysis programs such as LinkRank.
*/
- private static class NodeDb extends Configured implements Reducer<Text, LinkDatum, Text, Node> {
+ private static class NodeDb extends Configured implements
+ Reducer<Text, LinkDatum, Text, Node> {
/**
* Configures job.
*/
- public void configure(JobConf conf) { }
+ public void configure(JobConf conf) {
+ }
- public void close() { }
+ public void close() {
+ }
/**
* Counts the number of inlinks and outlinks for each url and sets a default
* score of 0.0 for each url (node) in the webgraph.
*/
- public void reduce(Text key, Iterator<LinkDatum> values, OutputCollector<Text, Node>
- output, Reporter reporter) throws IOException {
+ public void reduce(Text key, Iterator<LinkDatum> values,
+ OutputCollector<Text, Node> output, Reporter reporter)
+ throws IOException {
Node node = new Node();
int numInlinks = 0;
@@ -458,8 +466,7 @@ public class WebGraph extends Configured implements Tool {
LinkDatum next = values.next();
if (next.getLinkType() == LinkDatum.INLINK) {
numInlinks++;
- }
- else if (next.getLinkType() == LinkDatum.OUTLINK) {
+ } else if (next.getLinkType() == LinkDatum.OUTLINK) {
numOutlinks++;
}
}
@@ -477,16 +484,21 @@ public class WebGraph extends Configured implements Tool {
* Node. If a current WebGraph exists then it is updated, if it doesn't exist
* then a new WebGraph database is created.
*
- * @param webGraphDb The WebGraph to create or update.
- * @param segments The array of segments used to update the WebGraph. Newer
- * segments and fetch times will overwrite older segments.
- * @param normalize whether to use URLNormalizers on URL's in the segment
- * @param filter whether to use URLFilters on URL's in the segment
+ * @param webGraphDb
+ * The WebGraph to create or update.
+ * @param segments
+ * The array of segments used to update the WebGraph. Newer segments
+ * and fetch times will overwrite older segments.
+ * @param normalize
+ * whether to use URLNormalizers on URL's in the segment
+ * @param filter
+ * whether to use URLFilters on URL's in the segment
*
- * @throws IOException If an error occurs while processing the WebGraph.
+ * @throws IOException
+ * If an error occurs while processing the WebGraph.
*/
- public void createWebGraph(Path webGraphDb, Path[] segments, boolean normalize, boolean filter)
- throws IOException {
+ public void createWebGraph(Path webGraphDb, Path[] segments,
+ boolean normalize, boolean filter) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -563,7 +575,8 @@ public class WebGraph extends Configured implements Tool {
outlinkJob.setOutputValueClass(LinkDatum.class);
FileOutputFormat.setOutputPath(outlinkJob, tempOutlinkDb);
outlinkJob.setOutputFormat(MapFileOutputFormat.class);
- outlinkJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ outlinkJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ false);
// run the outlinkdb job and replace any old outlinkdb with the new one
try {
@@ -572,10 +585,10 @@ public class WebGraph extends Configured implements Tool {
LOG.info("OutlinkDb: installing " + outlinkDb);
FSUtils.replace(fs, oldOutlinkDb, outlinkDb, true);
FSUtils.replace(fs, outlinkDb, tempOutlinkDb, true);
- if (!preserveBackup && fs.exists(oldOutlinkDb)) fs.delete(oldOutlinkDb, true);
+ if (!preserveBackup && fs.exists(oldOutlinkDb))
+ fs.delete(oldOutlinkDb, true);
LOG.info("OutlinkDb: finished");
- }
- catch (IOException e) {
+ } catch (IOException e) {
// remove lock file and and temporary directory if an error occurs
LockUtil.removeLockFile(fs, lock);
@@ -603,7 +616,8 @@ public class WebGraph extends Configured implements Tool {
inlinkJob.setOutputValueClass(LinkDatum.class);
FileOutputFormat.setOutputPath(inlinkJob, tempInlinkDb);
inlinkJob.setOutputFormat(MapFileOutputFormat.class);
- inlinkJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ inlinkJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ false);
try {
@@ -613,14 +627,13 @@ public class WebGraph extends Configured implements Tool {
LOG.info("InlinkDb: installing " + inlinkDb);
FSUtils.replace(fs, inlinkDb, tempInlinkDb, true);
LOG.info("InlinkDb: finished");
- }
- catch (IOException e) {
+ } catch (IOException e) {
// remove lock file and and temporary directory if an error occurs
LockUtil.removeLockFile(fs, lock);
if (fs.exists(tempInlinkDb)) {
fs.delete(tempInlinkDb, true);
- }
+ }
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -644,7 +657,8 @@ public class WebGraph extends Configured implements Tool {
nodeJob.setOutputValueClass(Node.class);
FileOutputFormat.setOutputPath(nodeJob, tempNodeDb);
nodeJob.setOutputFormat(MapFileOutputFormat.class);
- nodeJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ nodeJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ false);
try {
@@ -654,14 +668,13 @@ public class WebGraph extends Configured implements Tool {
LOG.info("NodeDb: installing " + nodeDb);
FSUtils.replace(fs, nodeDb, tempNodeDb, true);
LOG.info("NodeDb: finished");
- }
- catch (IOException e) {
+ } catch (IOException e) {
// remove lock file and and temporary directory if an error occurs
LockUtil.removeLockFile(fs, lock);
if (fs.exists(tempNodeDb)) {
fs.delete(tempNodeDb, true);
- }
+ }
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -670,7 +683,8 @@ public class WebGraph extends Configured implements Tool {
LockUtil.removeLockFile(fs, lock);
long end = System.currentTimeMillis();
- LOG.info("WebGraphDb: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("WebGraphDb: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
}
public static void main(String[] args) throws Exception {
@@ -683,26 +697,29 @@ public class WebGraph extends Configured implements Tool {
*/
public int run(String[] args) throws Exception {
- //boolean options
+ // boolean options
Option helpOpt = new Option("h", "help", false, "show this help message");
- Option normOpt = new Option("n", "normalize", false, "whether to use URLNormalizers on the URL's in the segment");
- Option filtOpt = new Option("f", "filter", false, "whether to use URLFilters on the URL's in the segment");
+ Option normOpt = new Option("n", "normalize", false,
+ "whether to use URLNormalizers on the URL's in the segment");
+ Option filtOpt = new Option("f", "filter", false,
+ "whether to use URLFilters on the URL's in the segment");
- //argument options
+ // argument options
@SuppressWarnings("static-access")
- Option graphOpt = OptionBuilder.withArgName("webgraphdb")
- .hasArg().withDescription("the web graph database to create (if none exists) or use if one does")
+ Option graphOpt = OptionBuilder
+ .withArgName("webgraphdb")
+ .hasArg()
+ .withDescription(
+ "the web graph database to create (if none exists) or use if one does")
.create("webgraphdb");
@SuppressWarnings("static-access")
- Option segOpt = OptionBuilder.withArgName("segment")
- .hasArgs().withDescription("the segment(s) to use")
- .create("segment");
+ Option segOpt = OptionBuilder.withArgName("segment").hasArgs()
+ .withDescription("the segment(s) to use").create("segment");
@SuppressWarnings("static-access")
- Option segDirOpt = OptionBuilder.withArgName("segmentDir")
- .hasArgs().withDescription("the segment directory to use")
- .create("segmentDir");
-
- //create the options
+ Option segDirOpt = OptionBuilder.withArgName("segmentDir").hasArgs()
+ .withDescription("the segment directory to use").create("segmentDir");
+
+ // create the options
Options options = new Options();
options.addOption(helpOpt);
options.addOption(normOpt);
@@ -738,7 +755,8 @@ public class WebGraph extends Configured implements Tool {
if (line.hasOption("segmentDir")) {
Path dir = new Path(line.getOptionValue("segmentDir"));
FileSystem fs = dir.getFileSystem(getConf());
- FileStatus[] fstats = fs.listStatus(dir, HadoopFSUtil.getPassDirectoriesFilter(fs));
+ FileStatus[] fstats = fs.listStatus(dir,
+ HadoopFSUtil.getPassDirectoriesFilter(fs));
segPaths = HadoopFSUtil.getPaths(fstats);
}
@@ -756,8 +774,7 @@ public class WebGraph extends Configured implements Tool {
createWebGraph(new Path(webGraphDb), segPaths, normalize, filter);
return 0;
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("WebGraph: " + StringUtils.stringifyException(e));
return -2;
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/package-info.java b/src/java/org/apache/nutch/scoring/webgraph/package-info.java
index 5fd9b175e..a568b4682 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/package-info.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/package-info.java
@@ -21,3 +21,4 @@
* see {@link org.apache.nutch.scoring.webgraph.WebGraph}.
*/
package org.apache.nutch.scoring.webgraph;
+
diff --git a/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java b/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
index 3da45d731..6a682ce53 100644
--- a/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
+++ b/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
@@ -31,14 +31,14 @@ import org.apache.nutch.protocol.Content;
/**
* An input format that takes Nutch Content objects and converts them to text
- * while converting newline endings to spaces. This format is useful for working
+ * while converting newline endings to spaces. This format is useful for working
* with Nutch content objects in Hadoop Streaming with other languages.
*/
-public class ContentAsTextInputFormat
- extends SequenceFileInputFormat<Text, Text> {
+public class ContentAsTextInputFormat extends
+ SequenceFileInputFormat<Text, Text> {
- private static class ContentAsTextRecordReader
- implements RecordReader<Text, Text> {
+ private static class ContentAsTextRecordReader implements
+ RecordReader<Text, Text> {
private final SequenceFileRecordReader<Text, Content> sequenceFileRecordReader;
@@ -46,9 +46,9 @@ public class ContentAsTextInputFormat
private Content innerValue;
public ContentAsTextRecordReader(Configuration conf, FileSplit split)
- throws IOException {
+ throws IOException {
sequenceFileRecordReader = new SequenceFileRecordReader<Text, Content>(
- conf, split);
+ conf, split);
innerKey = sequenceFileRecordReader.createKey();
innerValue = sequenceFileRecordReader.createValue();
}
@@ -61,9 +61,8 @@ public class ContentAsTextInputFormat
return new Text();
}
- public synchronized boolean next(Text key, Text value)
- throws IOException {
-
+ public synchronized boolean next(Text key, Text value) throws IOException {
+
// convert the content object to text
Text tKey = key;
Text tValue = value;
@@ -72,26 +71,23 @@ public class ContentAsTextInputFormat
}
tKey.set(innerKey.toString());
String contentAsStr = new String(innerValue.getContent());
-
+
// replace new line endings with spaces
contentAsStr = contentAsStr.replaceAll("\n", " ");
value.set(contentAsStr);
-
+
return true;
}
- public float getProgress()
- throws IOException {
+ public float getProgress() throws IOException {
return sequenceFileRecordReader.getProgress();
}
- public synchronized long getPos()
- throws IOException {
+ public synchronized long getPos() throws IOException {
return sequenceFileRecordReader.getPos();
}
- public synchronized void close()
- throws IOException {
+ public synchronized void close() throws IOException {
sequenceFileRecordReader.close();
}
}
@@ -101,10 +97,9 @@ public class ContentAsTextInputFormat
}
public RecordReader<Text, Text> getRecordReader(InputSplit split,
- JobConf job, Reporter reporter)
- throws IOException {
+ JobConf job, Reporter reporter) throws IOException {
reporter.setStatus(split.toString());
- return new ContentAsTextRecordReader(job, (FileSplit)split);
+ return new ContentAsTextRecordReader(job, (FileSplit) split);
}
}
diff --git a/src/java/org/apache/nutch/segment/SegmentMergeFilters.java b/src/java/org/apache/nutch/segment/SegmentMergeFilters.java
index c1c98a548..7aa2de3c7 100644
--- a/src/java/org/apache/nutch/segment/SegmentMergeFilters.java
+++ b/src/java/org/apache/nutch/segment/SegmentMergeFilters.java
@@ -39,7 +39,8 @@ import org.apache.nutch.protocol.Content;
*
*/
public class SegmentMergeFilters {
- private static final Logger LOG = LoggerFactory.getLogger(SegmentMergeFilters.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(SegmentMergeFilters.class);
private SegmentMergeFilter[] filters;
public SegmentMergeFilters(Configuration conf) {
diff --git a/src/java/org/apache/nutch/segment/SegmentMerger.java b/src/java/org/apache/nutch/segment/SegmentMerger.java
index 22bb6c4de..c03b4576f 100644
--- a/src/java/org/apache/nutch/segment/SegmentMerger.java
+++ b/src/java/org/apache/nutch/segment/SegmentMerger.java
@@ -73,40 +73,47 @@ import org.apache.nutch.util.NutchJob;
* <p>
* Also, it's possible to slice the resulting segment into chunks of fixed size.
* </p>
- * <h3>Important Notes</h3>
- * <h4>Which parts are merged?</h4>
- * <p>It doesn't make sense to merge data from segments, which are at different stages
- * of processing (e.g. one unfetched segment, one fetched but not parsed, and
- * one fetched and parsed). Therefore, prior to merging, the tool will determine
- * the lowest common set of input data, and only this data will be merged.
- * This may have some unintended consequences:
- * e.g. if majority of input segments are fetched and parsed, but one of them is unfetched,
- * the tool will fall back to just merging fetchlists, and it will skip all other data
- * from all segments.</p>
+ * <h3>Important Notes</h3> <h4>Which parts are merged?</h4>
+ * <p>
+ * It doesn't make sense to merge data from segments, which are at different
+ * stages of processing (e.g. one unfetched segment, one fetched but not parsed,
+ * and one fetched and parsed). Therefore, prior to merging, the tool will
+ * determine the lowest common set of input data, and only this data will be
+ * merged. This may have some unintended consequences: e.g. if majority of input
+ * segments are fetched and parsed, but one of them is unfetched, the tool will
+ * fall back to just merging fetchlists, and it will skip all other data from
+ * all segments.
+ * </p>
* <h4>Merging fetchlists</h4>
- * <p>Merging segments, which contain just fetchlists (i.e. prior to fetching)
- * is not recommended, because this tool (unlike the {@link org.apache.nutch.crawl.Generator}
- * doesn't ensure that fetchlist parts for each map task are disjoint.</p>
+ * <p>
+ * Merging segments, which contain just fetchlists (i.e. prior to fetching) is
+ * not recommended, because this tool (unlike the
+ * {@link org.apache.nutch.crawl.Generator} doesn't ensure that fetchlist parts
+ * for each map task are disjoint.
+ * </p>
* <p>
* <h4>Duplicate content</h4>
- * Merging segments removes older content whenever possible (see below). However,
- * this is NOT the same as de-duplication, which in addition removes identical
- * content found at different URL-s. In other words, running DeleteDuplicates is
- * still necessary.
+ * Merging segments removes older content whenever possible (see below).
+ * However, this is NOT the same as de-duplication, which in addition removes
+ * identical content found at different URL-s. In other words, running
+ * DeleteDuplicates is still necessary.
+ * </p>
+ * <p>
+ * For some types of data (especially ParseText) it's not possible to determine
+ * which version is really older. Therefore the tool always uses segment names
+ * as timestamps, for all types of input data. Segment names are compared in
+ * forward lexicographic order (0-9a-zA-Z), and data from segments with "higher"
+ * names will prevail. It follows then that it is extremely important that
+ * segments be named in an increasing lexicographic order as their creation time
+ * increases.
* </p>
- * <p>For some types of data (especially ParseText) it's not possible to determine
- * which version is really older. Therefore the tool always uses segment names as
- * timestamps, for all types of input data. Segment names are compared in forward lexicographic
- * order (0-9a-zA-Z), and data from segments with "higher" names will prevail.
- * It follows then that it is extremely important that segments be named in an
- * increasing lexicographic order as their creation time increases.</p>
* <p>
* <h4>Merging and indexes</h4>
* Merged segment gets a different name. Since Indexer embeds segment names in
- * indexes, any indexes originally created for the input segments will NOT work with the
- * merged segment. Newly created merged segment(s) need to be indexed afresh.
- * This tool doesn't use existing indexes in any way, so if
- * you plan to merge segments you don't have to index them prior to merging.
+ * indexes, any indexes originally created for the input segments will NOT work
+ * with the merged segment. Newly created merged segment(s) need to be indexed
+ * afresh. This tool doesn't use existing indexes in any way, so if you plan to
+ * merge segments you don't have to index them prior to merging.
*
*
* @author Andrzej Bialecki
@@ -114,7 +121,8 @@ import org.apache.nutch.util.NutchJob;
public class SegmentMerger extends Configured implements
Mapper<Text, MetaWrapper, Text, MetaWrapper>,
Reducer<Text, MetaWrapper, Text, MetaWrapper> {
- private static final Logger LOG = LoggerFactory.getLogger(SegmentMerger.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(SegmentMerger.class);
private static final String SEGMENT_PART_KEY = "part";
private static final String SEGMENT_SLICE_KEY = "slice";
@@ -124,20 +132,21 @@ public class SegmentMerger extends Configured implements
private SegmentMergeFilters mergeFilters = null;
private long sliceSize = -1;
private long curCount = 0;
-
+
/**
- * Wraps inputs in an {@link MetaWrapper}, to permit merging different
- * types in reduce and use additional metadata.
+ * Wraps inputs in an {@link MetaWrapper}, to permit merging different types
+ * in reduce and use additional metadata.
*/
public static class ObjectInputFormat extends
- SequenceFileInputFormat<Text, MetaWrapper> {
-
+ SequenceFileInputFormat<Text, MetaWrapper> {
+
@Override
- public RecordReader<Text, MetaWrapper> getRecordReader(final InputSplit split,
- final JobConf job, Reporter reporter) throws IOException {
+ public RecordReader<Text, MetaWrapper> getRecordReader(
+ final InputSplit split, final JobConf job, Reporter reporter)
+ throws IOException {
reporter.setStatus(split.toString());
-
+
// find part name
SegmentPart segmentPart;
final String spString;
@@ -148,10 +157,10 @@ public class SegmentMerger extends Configured implements
} catch (IOException e) {
throw new RuntimeException("Cannot identify segment:", e);
}
-
- SequenceFile.Reader reader =
- new SequenceFile.Reader(FileSystem.get(job), fSplit.getPath(), job);
-
+
+ SequenceFile.Reader reader = new SequenceFile.Reader(FileSystem.get(job),
+ fSplit.getPath(), job);
+
final Writable w;
try {
w = (Writable) reader.getValueClass().newInstance();
@@ -164,13 +173,14 @@ public class SegmentMerger extends Configured implements
// ignore
}
}
- final SequenceFileRecordReader<Text,Writable> splitReader =
- new SequenceFileRecordReader<Text,Writable>(job, (FileSplit)split);
+ final SequenceFileRecordReader<Text, Writable> splitReader = new SequenceFileRecordReader<Text, Writable>(
+ job, (FileSplit) split);
try {
return new SequenceFileRecordReader<Text, MetaWrapper>(job, fSplit) {
-
- public synchronized boolean next(Text key, MetaWrapper wrapper) throws IOException {
+
+ public synchronized boolean next(Text key, MetaWrapper wrapper)
+ throws IOException {
LOG.debug("Running OIF.next()");
boolean res = splitReader.next(key, w);
@@ -178,17 +188,17 @@ public class SegmentMerger extends Configured implements
wrapper.setMeta(SEGMENT_PART_KEY, spString);
return res;
}
-
+
@Override
public synchronized void close() throws IOException {
splitReader.close();
}
-
+
@Override
public MetaWrapper createValue() {
return new MetaWrapper();
}
-
+
};
} catch (IOException e) {
throw new RuntimeException("Cannot create RecordReader: ", e);
@@ -196,11 +206,14 @@ public class SegmentMerger extends Configured implements
}
}
- public static class SegmentOutputFormat extends FileOutputFormat<Text, MetaWrapper> {
+ public static class SegmentOutputFormat extends
+ FileOutputFormat<Text, MetaWrapper> {
private static final String DEFAULT_SLICE = "default";
-
+
@Override
- public RecordWriter<Text, MetaWrapper> getRecordWriter(final FileSystem fs, final JobConf job, final String name, final Progressable progress) throws IOException {
+ public RecordWriter<Text, MetaWrapper> getRecordWriter(final FileSystem fs,
+ final JobConf job, final String name, final Progressable progress)
+ throws IOException {
return new RecordWriter<Text, MetaWrapper>() {
MapFile.Writer c_out = null;
MapFile.Writer f_out = null;
@@ -210,7 +223,7 @@ public class SegmentMerger extends Configured implements
SequenceFile.Writer p_out = null;
HashMap<String, Closeable> sliceWriters = new HashMap<String, Closeable>();
String segmentName = job.get("segment.merger.segmentName");
-
+
public void write(Text key, MetaWrapper wrapper) throws IOException {
// unwrap
SegmentPart sp = SegmentPart.parse(wrapper.getMeta(SEGMENT_PART_KEY));
@@ -221,13 +234,15 @@ public class SegmentMerger extends Configured implements
g_out = ensureSequenceFile(slice, CrawlDatum.GENERATE_DIR_NAME);
g_out.append(key, o);
} else if (sp.partName.equals(CrawlDatum.FETCH_DIR_NAME)) {
- f_out = ensureMapFile(slice, CrawlDatum.FETCH_DIR_NAME, CrawlDatum.class);
+ f_out = ensureMapFile(slice, CrawlDatum.FETCH_DIR_NAME,
+ CrawlDatum.class);
f_out.append(key, o);
} else if (sp.partName.equals(CrawlDatum.PARSE_DIR_NAME)) {
p_out = ensureSequenceFile(slice, CrawlDatum.PARSE_DIR_NAME);
p_out.append(key, o);
} else {
- throw new IOException("Cannot determine segment part: " + sp.partName);
+ throw new IOException("Cannot determine segment part: "
+ + sp.partName);
}
} else if (o instanceof Content) {
c_out = ensureMapFile(slice, Content.DIR_NAME, Content.class);
@@ -235,9 +250,11 @@ public class SegmentMerger extends Configured implements
} else if (o instanceof ParseData) {
// update the segment name inside contentMeta - required by Indexer
if (slice == null) {
- ((ParseData)o).getContentMeta().set(Nutch.SEGMENT_NAME_KEY, segmentName);
+ ((ParseData) o).getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
+ segmentName);
} else {
- ((ParseData)o).getContentMeta().set(Nutch.SEGMENT_NAME_KEY, segmentName + "-" + slice);
+ ((ParseData) o).getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
+ segmentName + "-" + slice);
}
pd_out = ensureMapFile(slice, ParseData.DIR_NAME, ParseData.class);
pd_out.append(key, o);
@@ -246,20 +263,26 @@ public class SegmentMerger extends Configured implements
pt_out.append(key, o);
}
}
-
+
// lazily create SequenceFile-s.
- private SequenceFile.Writer ensureSequenceFile(String slice, String dirName) throws IOException {
- if (slice == null) slice = DEFAULT_SLICE;
- SequenceFile.Writer res = (SequenceFile.Writer)sliceWriters.get(slice + dirName);
- if (res != null) return res;
+ private SequenceFile.Writer ensureSequenceFile(String slice,
+ String dirName) throws IOException {
+ if (slice == null)
+ slice = DEFAULT_SLICE;
+ SequenceFile.Writer res = (SequenceFile.Writer) sliceWriters
+ .get(slice + dirName);
+ if (res != null)
+ return res;
Path wname;
Path out = FileOutputFormat.getOutputPath(job);
if (slice == DEFAULT_SLICE) {
- wname = new Path(new Path(new Path(out, segmentName), dirName), name);
+ wname = new Path(new Path(new Path(out, segmentName), dirName),
+ name);
} else {
- wname = new Path(new Path(new Path(out, segmentName + "-" + slice), dirName), name);
+ wname = new Path(new Path(new Path(out, segmentName + "-" + slice),
+ dirName), name);
}
- res = SequenceFile.createWriter(fs, job, wname, Text.class,
+ res = SequenceFile.createWriter(fs, job, wname, Text.class,
CrawlDatum.class,
SequenceFileOutputFormat.getOutputCompressionType(job), progress);
sliceWriters.put(slice + dirName, res);
@@ -267,23 +290,30 @@ public class SegmentMerger extends Configured implements
}
// lazily create MapFile-s.
- private MapFile.Writer ensureMapFile(String slice, String dirName, Class<? extends Writable> clazz) throws IOException {
- if (slice == null) slice = DEFAULT_SLICE;
- MapFile.Writer res = (MapFile.Writer)sliceWriters.get(slice + dirName);
- if (res != null) return res;
+ private MapFile.Writer ensureMapFile(String slice, String dirName,
+ Class<? extends Writable> clazz) throws IOException {
+ if (slice == null)
+ slice = DEFAULT_SLICE;
+ MapFile.Writer res = (MapFile.Writer) sliceWriters.get(slice
+ + dirName);
+ if (res != null)
+ return res;
Path wname;
Path out = FileOutputFormat.getOutputPath(job);
if (slice == DEFAULT_SLICE) {
- wname = new Path(new Path(new Path(out, segmentName), dirName), name);
+ wname = new Path(new Path(new Path(out, segmentName), dirName),
+ name);
} else {
- wname = new Path(new Path(new Path(out, segmentName + "-" + slice), dirName), name);
+ wname = new Path(new Path(new Path(out, segmentName + "-" + slice),
+ dirName), name);
}
- CompressionType compType =
- SequenceFileOutputFormat.getOutputCompressionType(job);
+ CompressionType compType = SequenceFileOutputFormat
+ .getOutputCompressionType(job);
if (clazz.isAssignableFrom(ParseText.class)) {
compType = CompressionType.RECORD;
}
- res = new MapFile.Writer(job, fs, wname.toString(), Text.class, clazz, compType, progress);
+ res = new MapFile.Writer(job, fs, wname.toString(), Text.class,
+ clazz, compType, progress);
sliceWriters.put(slice + dirName, res);
return res;
}
@@ -293,9 +323,9 @@ public class SegmentMerger extends Configured implements
while (it.hasNext()) {
Object o = it.next();
if (o instanceof SequenceFile.Writer) {
- ((SequenceFile.Writer)o).close();
+ ((SequenceFile.Writer) o).close();
} else {
- ((MapFile.Writer)o).close();
+ ((MapFile.Writer) o).close();
}
}
}
@@ -306,14 +336,15 @@ public class SegmentMerger extends Configured implements
public SegmentMerger() {
super(null);
}
-
+
public SegmentMerger(Configuration conf) {
super(conf);
}
-
+
public void setConf(Configuration conf) {
super.setConf(conf);
- if (conf == null) return;
+ if (conf == null)
+ return;
if (conf.getBoolean("segment.merger.filter", false)) {
filters = new URLFilters(conf);
mergeFilters = new SegmentMergeFilters(conf);
@@ -335,15 +366,18 @@ public class SegmentMerger extends Configured implements
sliceSize = sliceSize / conf.getNumReduceTasks();
}
}
-
+
private Text newKey = new Text();
-
+
public void map(Text key, MetaWrapper value,
- OutputCollector<Text, MetaWrapper> output, Reporter reporter) throws IOException {
+ OutputCollector<Text, MetaWrapper> output, Reporter reporter)
+ throws IOException {
String url = key.toString();
if (normalizers != null) {
try {
- url = normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT); // normalize the url
+ url = normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT); // normalize
+ // the
+ // url
} catch (Exception e) {
LOG.warn("Skipping " + url + ":" + e.getMessage());
url = null;
@@ -357,7 +391,7 @@ public class SegmentMerger extends Configured implements
url = null;
}
}
- if(url != null) {
+ if (url != null) {
newKey.set(url);
output.collect(newKey, value);
}
@@ -365,12 +399,13 @@ public class SegmentMerger extends Configured implements
/**
* NOTE: in selecting the latest version we rely exclusively on the segment
- * name (not all segment data contain time information). Therefore it is extremely
- * important that segments be named in an increasing lexicographic order as
- * their creation time increases.
+ * name (not all segment data contain time information). Therefore it is
+ * extremely important that segments be named in an increasing lexicographic
+ * order as their creation time increases.
*/
public void reduce(Text key, Iterator<MetaWrapper> values,
- OutputCollector<Text, MetaWrapper> output, Reporter reporter) throws IOException {
+ OutputCollector<Text, MetaWrapper> output, Reporter reporter)
+ throws IOException {
CrawlDatum lastG = null;
CrawlDatum lastF = null;
CrawlDatum lastSig = null;
@@ -383,18 +418,17 @@ public class SegmentMerger extends Configured implements
String lastCname = null;
String lastPDname = null;
String lastPTname = null;
- TreeMap<String, ArrayList<CrawlDatum>> linked =
- new TreeMap<String, ArrayList<CrawlDatum>>();
+ TreeMap<String, ArrayList<CrawlDatum>> linked = new TreeMap<String, ArrayList<CrawlDatum>>();
while (values.hasNext()) {
MetaWrapper wrapper = values.next();
Object o = wrapper.get();
String spString = wrapper.getMeta(SEGMENT_PART_KEY);
if (spString == null) {
- throw new IOException("Null segment part, key=" + key);
+ throw new IOException("Null segment part, key=" + key);
}
SegmentPart sp = SegmentPart.parse(spString);
if (o instanceof CrawlDatum) {
- CrawlDatum val = (CrawlDatum)o;
+ CrawlDatum val = (CrawlDatum) o;
// check which output dir it belongs to
if (sp.partName.equals(CrawlDatum.GENERATE_DIR_NAME)) {
if (lastG == null) {
@@ -411,9 +445,9 @@ public class SegmentMerger extends Configured implements
// only consider fetch status and ignore fetch retry status
// https://issues.apache.org/jira/browse/NUTCH-1520
// https://issues.apache.org/jira/browse/NUTCH-1113
- if (CrawlDatum.hasFetchStatus(val) &&
- val.getStatus() != CrawlDatum.STATUS_FETCH_RETRY &&
- val.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
+ if (CrawlDatum.hasFetchStatus(val)
+ && val.getStatus() != CrawlDatum.STATUS_FETCH_RETRY
+ && val.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
if (lastF == null) {
lastF = val;
lastFname = sp.segmentName;
@@ -450,40 +484,40 @@ public class SegmentMerger extends Configured implements
}
} else if (o instanceof Content) {
if (lastC == null) {
- lastC = (Content)o;
+ lastC = (Content) o;
lastCname = sp.segmentName;
} else {
if (lastCname.compareTo(sp.segmentName) < 0) {
- lastC = (Content)o;
+ lastC = (Content) o;
lastCname = sp.segmentName;
}
}
} else if (o instanceof ParseData) {
if (lastPD == null) {
- lastPD = (ParseData)o;
+ lastPD = (ParseData) o;
lastPDname = sp.segmentName;
} else {
if (lastPDname.compareTo(sp.segmentName) < 0) {
- lastPD = (ParseData)o;
+ lastPD = (ParseData) o;
lastPDname = sp.segmentName;
}
}
} else if (o instanceof ParseText) {
if (lastPT == null) {
- lastPT = (ParseText)o;
+ lastPT = (ParseText) o;
lastPTname = sp.segmentName;
} else {
if (lastPTname.compareTo(sp.segmentName) < 0) {
- lastPT = (ParseText)o;
+ lastPT = (ParseText) o;
lastPTname = sp.segmentName;
}
}
}
}
- // perform filtering based on full merge record
- if (mergeFilters != null &&
- !mergeFilters.filter(key, lastG, lastF, lastSig, lastC, lastPD, lastPT,
- linked.isEmpty() ? null : linked.lastEntry().getValue())){
+ // perform filtering based on full merge record
+ if (mergeFilters != null
+ && !mergeFilters.filter(key, lastG, lastF, lastSig, lastC, lastPD,
+ lastPT, linked.isEmpty() ? null : linked.lastEntry().getValue())) {
return;
}
@@ -552,10 +586,12 @@ public class SegmentMerger extends Configured implements
}
}
- public void merge(Path out, Path[] segs, boolean filter, boolean normalize, long slice) throws Exception {
+ public void merge(Path out, Path[] segs, boolean filter, boolean normalize,
+ long slice) throws Exception {
String segmentName = Generator.generateSegmentName();
if (LOG.isInfoEnabled()) {
- LOG.info("Merging " + segs.length + " segments to " + out + "/" + segmentName);
+ LOG.info("Merging " + segs.length + " segments to " + out + "/"
+ + segmentName);
}
JobConf job = new NutchJob(getConf());
job.setJobName("mergesegs " + out + "/" + segmentName);
@@ -596,17 +632,24 @@ public class SegmentMerger extends Configured implements
pt = pt && fs.exists(ptDir);
}
StringBuffer sb = new StringBuffer();
- if (c) sb.append(" " + Content.DIR_NAME);
- if (g) sb.append(" " + CrawlDatum.GENERATE_DIR_NAME);
- if (f) sb.append(" " + CrawlDatum.FETCH_DIR_NAME);
- if (p) sb.append(" " + CrawlDatum.PARSE_DIR_NAME);
- if (pd) sb.append(" " + ParseData.DIR_NAME);
- if (pt) sb.append(" " + ParseText.DIR_NAME);
+ if (c)
+ sb.append(" " + Content.DIR_NAME);
+ if (g)
+ sb.append(" " + CrawlDatum.GENERATE_DIR_NAME);
+ if (f)
+ sb.append(" " + CrawlDatum.FETCH_DIR_NAME);
+ if (p)
+ sb.append(" " + CrawlDatum.PARSE_DIR_NAME);
+ if (pd)
+ sb.append(" " + ParseData.DIR_NAME);
+ if (pt)
+ sb.append(" " + ParseText.DIR_NAME);
if (LOG.isInfoEnabled()) {
LOG.info("SegmentMerger: using segment data from:" + sb.toString());
}
for (int i = 0; i < segs.length; i++) {
- if (segs[i] == null) continue;
+ if (segs[i] == null)
+ continue;
if (g) {
Path gDir = new Path(segs[i], CrawlDatum.GENERATE_DIR_NAME);
FileInputFormat.addInputPath(job, gDir);
@@ -639,9 +682,9 @@ public class SegmentMerger extends Configured implements
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(MetaWrapper.class);
job.setOutputFormat(SegmentOutputFormat.class);
-
+
setConf(job);
-
+
JobClient.runJob(job);
}
@@ -650,13 +693,19 @@ public class SegmentMerger extends Configured implements
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) {
- System.err.println("SegmentMerger output_dir (-dir segments | seg1 seg2 ...) [-filter] [-slice NNNN]");
- System.err.println("\toutput_dir\tname of the parent dir for output segment slice(s)");
- System.err.println("\t-dir segments\tparent dir containing several segments");
+ System.err
+ .println("SegmentMerger output_dir (-dir segments | seg1 seg2 ...) [-filter] [-slice NNNN]");
+ System.err
+ .println("\toutput_dir\tname of the parent dir for output segment slice(s)");
+ System.err
+ .println("\t-dir segments\tparent dir containing several segments");
System.err.println("\tseg1 seg2 ...\tlist of segment dirs");
- System.err.println("\t-filter\t\tfilter out URL-s prohibited by current URLFilters");
- System.err.println("\t-normalize\t\tnormalize URL via current URLNormalizers");
- System.err.println("\t-slice NNNN\tcreate many output segments, each containing NNNN URLs");
+ System.err
+ .println("\t-filter\t\tfilter out URL-s prohibited by current URLFilters");
+ System.err
+ .println("\t-normalize\t\tnormalize URL via current URLNormalizers");
+ System.err
+ .println("\t-slice NNNN\tcreate many output segments, each containing NNNN URLs");
return;
}
Configuration conf = NutchConfiguration.create();
@@ -688,7 +737,8 @@ public class SegmentMerger extends Configured implements
return;
}
SegmentMerger merger = new SegmentMerger(conf);
- merger.merge(out, segs.toArray(new Path[segs.size()]), filter, normalize, sliceSize);
+ merger.merge(out, segs.toArray(new Path[segs.size()]), filter, normalize,
+ sliceSize);
}
}
diff --git a/src/java/org/apache/nutch/segment/SegmentPart.java b/src/java/org/apache/nutch/segment/SegmentPart.java
index c515791f8..84247e405 100644
--- a/src/java/org/apache/nutch/segment/SegmentPart.java
+++ b/src/java/org/apache/nutch/segment/SegmentPart.java
@@ -30,16 +30,16 @@ public class SegmentPart {
public String segmentName;
/** Name of the segment part (ie. one of subdirectories inside a segment). */
public String partName;
-
+
public SegmentPart() {
-
+
}
-
+
public SegmentPart(String segmentName, String partName) {
this.segmentName = segmentName;
this.partName = partName;
}
-
+
/**
* Return a String representation of this class, in the form
* "segmentName/partName".
@@ -47,23 +47,27 @@ public class SegmentPart {
public String toString() {
return segmentName + "/" + partName;
}
-
+
/**
* Create SegmentPart from a FileSplit.
+ *
* @param split
- * @return A {@link SegmentPart} resultant from a
- * {@link FileSplit}.
+ * @return A {@link SegmentPart} resultant from a {@link FileSplit}.
* @throws Exception
*/
public static SegmentPart get(FileSplit split) throws IOException {
return get(split.getPath().toString());
}
-
+
/**
* Create SegmentPart from a full path of a location inside any segment part.
- * @param path full path into a segment part (may include "part-xxxxx" components)
+ *
+ * @param path
+ * full path into a segment part (may include "part-xxxxx"
+ * components)
* @return SegmentPart instance describing this part.
- * @throws IOException if any required path components are missing.
+ * @throws IOException
+ * if any required path components are missing.
*/
public static SegmentPart get(String path) throws IOException {
// find part name
@@ -87,12 +91,15 @@ public class SegmentPart {
String segment = dir.substring(idx + 1);
return new SegmentPart(segment, part);
}
-
+
/**
* Create SegmentPart from a String in format "segmentName/partName".
- * @param string input String
+ *
+ * @param string
+ * input String
* @return parsed instance of SegmentPart
- * @throws IOException if "/" is missing.
+ * @throws IOException
+ * if "/" is missing.
*/
public static SegmentPart parse(String string) throws IOException {
int idx = string.indexOf('/');
diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.java
index f88604f8c..7d0deceee 100644
--- a/src/java/org/apache/nutch/segment/SegmentReader.java
+++ b/src/java/org/apache/nutch/segment/SegmentReader.java
@@ -75,7 +75,7 @@ public class SegmentReader extends Configured implements
public static final Logger LOG = LoggerFactory.getLogger(SegmentReader.class);
long recNo = 0L;
-
+
private boolean co, fe, ge, pa, pd, pt;
private FileSystem fs;
@@ -84,33 +84,38 @@ public class SegmentReader extends Configured implements
private Text newKey = new Text();
public void map(WritableComparable<?> key, Writable value,
- OutputCollector<Text, NutchWritable> collector, Reporter reporter) throws IOException {
+ OutputCollector<Text, NutchWritable> collector, Reporter reporter)
+ throws IOException {
// convert on the fly from old formats with UTF8 keys.
// UTF8 deprecated and replaced by Text.
if (key instanceof Text) {
newKey.set(key.toString());
key = newKey;
}
- collector.collect((Text)key, new NutchWritable(value));
+ collector.collect((Text) key, new NutchWritable(value));
}
-
+
}
/** Implements a text output format */
public static class TextOutputFormat extends
FileOutputFormat<WritableComparable<?>, Writable> {
public RecordWriter<WritableComparable<?>, Writable> getRecordWriter(
- final FileSystem fs, JobConf job,
- String name, final Progressable progress) throws IOException {
+ final FileSystem fs, JobConf job, String name,
+ final Progressable progress) throws IOException {
- final Path segmentDumpFile = new Path(FileOutputFormat.getOutputPath(job), name);
+ final Path segmentDumpFile = new Path(
+ FileOutputFormat.getOutputPath(job), name);
// Get the old copy out of the way
- if (fs.exists(segmentDumpFile)) fs.delete(segmentDumpFile, true);
+ if (fs.exists(segmentDumpFile))
+ fs.delete(segmentDumpFile, true);
- final PrintStream printStream = new PrintStream(fs.create(segmentDumpFile));
+ final PrintStream printStream = new PrintStream(
+ fs.create(segmentDumpFile));
return new RecordWriter<WritableComparable<?>, Writable>() {
- public synchronized void write(WritableComparable<?> key, Writable value) throws IOException {
+ public synchronized void write(WritableComparable<?> key, Writable value)
+ throws IOException {
printStream.println(value);
}
@@ -124,9 +129,9 @@ public class SegmentReader extends Configured implements
public SegmentReader() {
super(null);
}
-
- public SegmentReader(Configuration conf, boolean co, boolean fe, boolean ge, boolean pa,
- boolean pd, boolean pt) {
+
+ public SegmentReader(Configuration conf, boolean co, boolean fe, boolean ge,
+ boolean pa, boolean pd, boolean pt) {
super(conf);
this.co = co;
this.fe = fe;
@@ -166,12 +171,12 @@ public class SegmentReader extends Configured implements
job.setBoolean("segment.reader.pt", this.pt);
return job;
}
-
- public void close() {}
+
+ public void close() {
+ }
public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<Text, Text> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
StringBuffer dump = new StringBuffer();
dump.append("\nRecno:: ").append(recNo++).append("\n");
@@ -194,7 +199,7 @@ public class SegmentReader extends Configured implements
}
public void dump(Path segment, Path output) throws IOException {
-
+
if (LOG.isInfoEnabled()) {
LOG.info("SegmentReader: dump segment: " + segment);
}
@@ -202,20 +207,30 @@ public class SegmentReader extends Configured implements
JobConf job = createJobConf();
job.setJobName("read " + segment);
- if (ge) FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
- if (fe) FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.FETCH_DIR_NAME));
- if (pa) FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.PARSE_DIR_NAME));
- if (co) FileInputFormat.addInputPath(job, new Path(segment, Content.DIR_NAME));
- if (pd) FileInputFormat.addInputPath(job, new Path(segment, ParseData.DIR_NAME));
- if (pt) FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME));
+ if (ge)
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.GENERATE_DIR_NAME));
+ if (fe)
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.FETCH_DIR_NAME));
+ if (pa)
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.PARSE_DIR_NAME));
+ if (co)
+ FileInputFormat.addInputPath(job, new Path(segment, Content.DIR_NAME));
+ if (pd)
+ FileInputFormat.addInputPath(job, new Path(segment, ParseData.DIR_NAME));
+ if (pt)
+ FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME));
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(InputCompatMapper.class);
job.setReducerClass(SegmentReader.class);
- Path tempDir = new Path(job.get("hadoop.tmp.dir", "/tmp") + "/segread-" + new java.util.Random().nextInt());
+ Path tempDir = new Path(job.get("hadoop.tmp.dir", "/tmp") + "/segread-"
+ + new java.util.Random().nextInt());
fs.delete(tempDir, true);
-
+
FileOutputFormat.setOutputPath(job, tempDir);
job.setOutputFormat(TextOutputFormat.class);
job.setOutputKeyClass(Text.class);
@@ -228,22 +243,25 @@ public class SegmentReader extends Configured implements
// remove the old file
fs.delete(dumpFile, true);
- FileStatus[] fstats = fs.listStatus(tempDir, HadoopFSUtil.getPassAllFilter());
+ FileStatus[] fstats = fs.listStatus(tempDir,
+ HadoopFSUtil.getPassAllFilter());
Path[] files = HadoopFSUtil.getPaths(fstats);
PrintWriter writer = null;
int currentRecordNumber = 0;
if (files.length > 0) {
- writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fs.create(dumpFile))));
+ writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
+ fs.create(dumpFile))));
try {
for (int i = 0; i < files.length; i++) {
Path partFile = files[i];
try {
- currentRecordNumber = append(fs, job, partFile, writer, currentRecordNumber);
+ currentRecordNumber = append(fs, job, partFile, writer,
+ currentRecordNumber);
} catch (IOException exception) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't copy the content of " + partFile.toString() +
- " into " + dumpFile.toString());
+ LOG.warn("Couldn't copy the content of " + partFile.toString()
+ + " into " + dumpFile.toString());
LOG.warn(exception.getMessage());
}
}
@@ -253,13 +271,16 @@ public class SegmentReader extends Configured implements
}
}
fs.delete(tempDir, true);
- if (LOG.isInfoEnabled()) { LOG.info("SegmentReader: done"); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("SegmentReader: done");
+ }
}
/** Appends two files and updates the Recno counter */
- private int append(FileSystem fs, Configuration conf, Path src, PrintWriter writer, int currentRecordNumber)
- throws IOException {
- BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(src)));
+ private int append(FileSystem fs, Configuration conf, Path src,
+ PrintWriter writer, int currentRecordNumber) throws IOException {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ fs.open(src)));
try {
String line = reader.readLine();
while (line != null) {
@@ -276,89 +297,101 @@ public class SegmentReader extends Configured implements
}
private static final String[][] keys = new String[][] {
- {"co", "Content::\n"},
- {"ge", "Crawl Generate::\n"},
- {"fe", "Crawl Fetch::\n"},
- {"pa", "Crawl Parse::\n"},
- {"pd", "ParseData::\n"},
- {"pt", "ParseText::\n"}
- };
+ { "co", "Content::\n" }, { "ge", "Crawl Generate::\n" },
+ { "fe", "Crawl Fetch::\n" }, { "pa", "Crawl Parse::\n" },
+ { "pd", "ParseData::\n" }, { "pt", "ParseText::\n" } };
public void get(final Path segment, final Text key, Writer writer,
- final Map<String, List<Writable>> results) throws Exception {
+ final Map<String, List<Writable>> results) throws Exception {
LOG.info("SegmentReader: get '" + key + "'");
ArrayList<Thread> threads = new ArrayList<Thread>();
- if (co) threads.add(new Thread() {
- public void run() {
- try {
- List<Writable> res = getMapRecords(new Path(segment, Content.DIR_NAME), key);
- results.put("co", res);
- } catch (Exception e) {
- LOG.error("Exception:", e);
+ if (co)
+ threads.add(new Thread() {
+ public void run() {
+ try {
+ List<Writable> res = getMapRecords(new Path(segment,
+ Content.DIR_NAME), key);
+ results.put("co", res);
+ } catch (Exception e) {
+ LOG.error("Exception:", e);
+ }
}
- }
- });
- if (fe) threads.add(new Thread() {
- public void run() {
- try {
- List<Writable> res = getMapRecords(new Path(segment, CrawlDatum.FETCH_DIR_NAME), key);
- results.put("fe", res);
- } catch (Exception e) {
- LOG.error("Exception:", e);
+ });
+ if (fe)
+ threads.add(new Thread() {
+ public void run() {
+ try {
+ List<Writable> res = getMapRecords(new Path(segment,
+ CrawlDatum.FETCH_DIR_NAME), key);
+ results.put("fe", res);
+ } catch (Exception e) {
+ LOG.error("Exception:", e);
+ }
}
- }
- });
- if (ge) threads.add(new Thread() {
- public void run() {
- try {
- List<Writable> res = getSeqRecords(new Path(segment, CrawlDatum.GENERATE_DIR_NAME), key);
- results.put("ge", res);
- } catch (Exception e) {
- LOG.error("Exception:", e);
+ });
+ if (ge)
+ threads.add(new Thread() {
+ public void run() {
+ try {
+ List<Writable> res = getSeqRecords(new Path(segment,
+ CrawlDatum.GENERATE_DIR_NAME), key);
+ results.put("ge", res);
+ } catch (Exception e) {
+ LOG.error("Exception:", e);
+ }
}
- }
- });
- if (pa) threads.add(new Thread() {
- public void run() {
- try {
- List<Writable> res = getSeqRecords(new Path(segment, CrawlDatum.PARSE_DIR_NAME), key);
- results.put("pa", res);
- } catch (Exception e) {
- LOG.error("Exception:", e);
+ });
+ if (pa)
+ threads.add(new Thread() {
+ public void run() {
+ try {
+ List<Writable> res = getSeqRecords(new Path(segment,
+ CrawlDatum.PARSE_DIR_NAME), key);
+ results.put("pa", res);
+ } catch (Exception e) {
+ LOG.error("Exception:", e);
+ }
}
- }
- });
- if (pd) threads.add(new Thread() {
- public void run() {
- try {
- List<Writable> res = getMapRecords(new Path(segment, ParseData.DIR_NAME), key);
- results.put("pd", res);
- } catch (Exception e) {
- LOG.error("Exception:", e);
+ });
+ if (pd)
+ threads.add(new Thread() {
+ public void run() {
+ try {
+ List<Writable> res = getMapRecords(new Path(segment,
+ ParseData.DIR_NAME), key);
+ results.put("pd", res);
+ } catch (Exception e) {
+ LOG.error("Exception:", e);
+ }
}
- }
- });
- if (pt) threads.add(new Thread() {
- public void run() {
- try {
- List<Writable> res = getMapRecords(new Path(segment, ParseText.DIR_NAME), key);
- results.put("pt", res);
- } catch (Exception e) {
- LOG.error("Exception:", e);
+ });
+ if (pt)
+ threads.add(new Thread() {
+ public void run() {
+ try {
+ List<Writable> res = getMapRecords(new Path(segment,
+ ParseText.DIR_NAME), key);
+ results.put("pt", res);
+ } catch (Exception e) {
+ LOG.error("Exception:", e);
+ }
}
- }
- });
+ });
Iterator<Thread> it = threads.iterator();
- while (it.hasNext()) it.next().start();
+ while (it.hasNext())
+ it.next().start();
int cnt;
do {
cnt = 0;
try {
Thread.sleep(5000);
- } catch (Exception e) {};
+ } catch (Exception e) {
+ }
+ ;
it = threads.iterator();
while (it.hasNext()) {
- if (it.next().isAlive()) cnt++;
+ if (it.next().isAlive())
+ cnt++;
}
if ((cnt > 0) && (LOG.isDebugEnabled())) {
LOG.debug("(" + cnt + " to retrieve)");
@@ -375,24 +408,25 @@ public class SegmentReader extends Configured implements
writer.flush();
}
}
-
+
private List<Writable> getMapRecords(Path dir, Text key) throws Exception {
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, dir, getConf());
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, dir,
+ getConf());
ArrayList<Writable> res = new ArrayList<Writable>();
Class<?> keyClass = readers[0].getKeyClass();
Class<?> valueClass = readers[0].getValueClass();
if (!keyClass.getName().equals("org.apache.hadoop.io.Text"))
throw new IOException("Incompatible key (" + keyClass.getName() + ")");
- Writable value = (Writable)valueClass.newInstance();
+ Writable value = (Writable) valueClass.newInstance();
// we don't know the partitioning schema
for (int i = 0; i < readers.length; i++) {
if (readers[i].get(key, value) != null) {
res.add(value);
- value = (Writable)valueClass.newInstance();
+ value = (Writable) valueClass.newInstance();
Text aKey = (Text) keyClass.newInstance();
while (readers[i].next(aKey, value) && aKey.equals(key)) {
res.add(value);
- value = (Writable)valueClass.newInstance();
+ value = (Writable) valueClass.newInstance();
}
}
readers[i].close();
@@ -401,19 +435,20 @@ public class SegmentReader extends Configured implements
}
private List<Writable> getSeqRecords(Path dir, Text key) throws Exception {
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(getConf(), dir);
+ SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(
+ getConf(), dir);
ArrayList<Writable> res = new ArrayList<Writable>();
Class<?> keyClass = readers[0].getKeyClass();
Class<?> valueClass = readers[0].getValueClass();
if (!keyClass.getName().equals("org.apache.hadoop.io.Text"))
throw new IOException("Incompatible key (" + keyClass.getName() + ")");
- Writable aKey = (Writable)keyClass.newInstance();
- Writable value = (Writable)valueClass.newInstance();
+ Writable aKey = (Writable) keyClass.newInstance();
+ Writable value = (Writable) valueClass.newInstance();
for (int i = 0; i < readers.length; i++) {
while (readers[i].next(aKey, value)) {
if (aKey.equals(key)) {
res.add(value);
- value = (Writable)valueClass.newInstance();
+ value = (Writable) valueClass.newInstance();
}
}
readers[i].close();
@@ -430,41 +465,55 @@ public class SegmentReader extends Configured implements
public long parsed = -1L;
public long parseErrors = -1L;
}
-
+
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
-
+
public void list(List<Path> dirs, Writer writer) throws Exception {
- writer.write("NAME\t\tGENERATED\tFETCHER START\t\tFETCHER END\t\tFETCHED\tPARSED\n");
+ writer
+ .write("NAME\t\tGENERATED\tFETCHER START\t\tFETCHER END\t\tFETCHED\tPARSED\n");
for (int i = 0; i < dirs.size(); i++) {
Path dir = dirs.get(i);
SegmentReaderStats stats = new SegmentReaderStats();
getStats(dir, stats);
writer.write(dir.getName() + "\t");
- if (stats.generated == -1) writer.write("?");
- else writer.write(stats.generated + "");
+ if (stats.generated == -1)
+ writer.write("?");
+ else
+ writer.write(stats.generated + "");
writer.write("\t\t");
- if (stats.start == -1) writer.write("?\t");
- else writer.write(sdf.format(new Date(stats.start)));
+ if (stats.start == -1)
+ writer.write("?\t");
+ else
+ writer.write(sdf.format(new Date(stats.start)));
writer.write("\t");
- if (stats.end == -1) writer.write("?");
- else writer.write(sdf.format(new Date(stats.end)));
+ if (stats.end == -1)
+ writer.write("?");
+ else
+ writer.write(sdf.format(new Date(stats.end)));
writer.write("\t");
- if (stats.fetched == -1) writer.write("?");
- else writer.write(stats.fetched + "");
+ if (stats.fetched == -1)
+ writer.write("?");
+ else
+ writer.write(stats.fetched + "");
writer.write("\t");
- if (stats.parsed == -1) writer.write("?");
- else writer.write(stats.parsed + "");
+ if (stats.parsed == -1)
+ writer.write("?");
+ else
+ writer.write(stats.parsed + "");
writer.write("\n");
writer.flush();
}
}
-
- public void getStats(Path segment, final SegmentReaderStats stats) throws Exception {
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(getConf(), new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
+
+ public void getStats(Path segment, final SegmentReaderStats stats)
+ throws Exception {
+ SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(
+ getConf(), new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
long cnt = 0L;
Text key = new Text();
for (int i = 0; i < readers.length; i++) {
- while (readers[i].next(key)) cnt++;
+ while (readers[i].next(key))
+ cnt++;
readers[i].close();
}
stats.generated = cnt;
@@ -474,12 +523,15 @@ public class SegmentReader extends Configured implements
long start = Long.MAX_VALUE;
long end = Long.MIN_VALUE;
CrawlDatum value = new CrawlDatum();
- MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(fs, fetchDir, getConf());
+ MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(fs, fetchDir,
+ getConf());
for (int i = 0; i < mreaders.length; i++) {
while (mreaders[i].next(key, value)) {
cnt++;
- if (value.getFetchTime() < start) start = value.getFetchTime();
- if (value.getFetchTime() > end) end = value.getFetchTime();
+ if (value.getFetchTime() < start)
+ start = value.getFetchTime();
+ if (value.getFetchTime() > end)
+ end = value.getFetchTime();
}
mreaders[i].close();
}
@@ -492,11 +544,13 @@ public class SegmentReader extends Configured implements
cnt = 0L;
long errors = 0L;
ParseData value = new ParseData();
- MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(fs, parseDir, getConf());
+ MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(fs, parseDir,
+ getConf());
for (int i = 0; i < mreaders.length; i++) {
while (mreaders[i].next(key, value)) {
cnt++;
- if (!value.getStatus().isSuccess()) errors++;
+ if (!value.getStatus().isSuccess())
+ errors++;
}
mreaders[i].close();
}
@@ -504,7 +558,7 @@ public class SegmentReader extends Configured implements
stats.parseErrors = errors;
}
}
-
+
private static final int MODE_DUMP = 0;
private static final int MODE_LIST = 1;
@@ -521,7 +575,8 @@ public class SegmentReader extends Configured implements
mode = MODE_DUMP;
else if (args[0].equals("-list"))
mode = MODE_LIST;
- else if (args[0].equals("-get")) mode = MODE_GET;
+ else if (args[0].equals("-get"))
+ mode = MODE_GET;
boolean co = true;
boolean fe = true;
@@ -553,63 +608,69 @@ public class SegmentReader extends Configured implements
}
Configuration conf = NutchConfiguration.create();
final FileSystem fs = FileSystem.get(conf);
- SegmentReader segmentReader = new SegmentReader(conf, co, fe, ge, pa, pd, pt);
+ SegmentReader segmentReader = new SegmentReader(conf, co, fe, ge, pa, pd,
+ pt);
// collect required args
switch (mode) {
- case MODE_DUMP:
- String input = args[1];
- if (input == null) {
- System.err.println("Missing required argument: <segment_dir>");
- usage();
- return;
- }
- String output = args.length > 2 ? args[2] : null;
- if (output == null) {
- System.err.println("Missing required argument: <output>");
- usage();
- return;
- }
- segmentReader.dump(new Path(input), new Path(output));
+ case MODE_DUMP:
+ String input = args[1];
+ if (input == null) {
+ System.err.println("Missing required argument: <segment_dir>");
+ usage();
return;
- case MODE_LIST:
- ArrayList<Path> dirs = new ArrayList<Path>();
- for (int i = 1; i < args.length; i++) {
- if (args[i] == null) continue;
- if (args[i].equals("-dir")) {
- Path dir = new Path(args[++i]);
- FileStatus[] fstats = fs.listStatus(dir, HadoopFSUtil.getPassDirectoriesFilter(fs));
- Path[] files = HadoopFSUtil.getPaths(fstats);
- if (files != null && files.length > 0) {
- dirs.addAll(Arrays.asList(files));
- }
- } else dirs.add(new Path(args[i]));
- }
- segmentReader.list(dirs, new OutputStreamWriter(System.out, "UTF-8"));
+ }
+ String output = args.length > 2 ? args[2] : null;
+ if (output == null) {
+ System.err.println("Missing required argument: <output>");
+ usage();
return;
- case MODE_GET:
- input = args[1];
- if (input == null) {
- System.err.println("Missing required argument: <segment_dir>");
- usage();
- return;
- }
- String key = args.length > 2 ? args[2] : null;
- if (key == null) {
- System.err.println("Missing required argument: <keyValue>");
- usage();
- return;
- }
- segmentReader.get(new Path(input), new Text(key), new OutputStreamWriter(System.out, "UTF-8"), new HashMap<String, List<Writable>>());
+ }
+ segmentReader.dump(new Path(input), new Path(output));
+ return;
+ case MODE_LIST:
+ ArrayList<Path> dirs = new ArrayList<Path>();
+ for (int i = 1; i < args.length; i++) {
+ if (args[i] == null)
+ continue;
+ if (args[i].equals("-dir")) {
+ Path dir = new Path(args[++i]);
+ FileStatus[] fstats = fs.listStatus(dir,
+ HadoopFSUtil.getPassDirectoriesFilter(fs));
+ Path[] files = HadoopFSUtil.getPaths(fstats);
+ if (files != null && files.length > 0) {
+ dirs.addAll(Arrays.asList(files));
+ }
+ } else
+ dirs.add(new Path(args[i]));
+ }
+ segmentReader.list(dirs, new OutputStreamWriter(System.out, "UTF-8"));
+ return;
+ case MODE_GET:
+ input = args[1];
+ if (input == null) {
+ System.err.println("Missing required argument: <segment_dir>");
+ usage();
return;
- default:
- System.err.println("Invalid operation: " + args[0]);
+ }
+ String key = args.length > 2 ? args[2] : null;
+ if (key == null) {
+ System.err.println("Missing required argument: <keyValue>");
usage();
return;
+ }
+ segmentReader.get(new Path(input), new Text(key), new OutputStreamWriter(
+ System.out, "UTF-8"), new HashMap<String, List<Writable>>());
+ return;
+ default:
+ System.err.println("Invalid operation: " + args[0]);
+ usage();
+ return;
}
}
private static void usage() {
- System.err.println("Usage: SegmentReader (-dump ... | -list ... | -get ...) [general options]\n");
+ System.err
+ .println("Usage: SegmentReader (-dump ... | -list ... | -get ...) [general options]\n");
System.err.println("* General options:");
System.err.println("\t-nocontent\tignore content directory");
System.err.println("\t-nofetch\tignore crawl_fetch directory");
@@ -618,21 +679,32 @@ public class SegmentReader extends Configured implements
System.err.println("\t-noparsedata\tignore parse_data directory");
System.err.println("\t-noparsetext\tignore parse_text directory");
System.err.println();
- System.err.println("* SegmentReader -dump <segment_dir> <output> [general options]");
- System.err.println(" Dumps content of a <segment_dir> as a text file to <output>.\n");
+ System.err
+ .println("* SegmentReader -dump <segment_dir> <output> [general options]");
+ System.err
+ .println(" Dumps content of a <segment_dir> as a text file to <output>.\n");
System.err.println("\t<segment_dir>\tname of the segment directory.");
- System.err.println("\t<output>\tname of the (non-existent) output directory.");
+ System.err
+ .println("\t<output>\tname of the (non-existent) output directory.");
System.err.println();
- System.err.println("* SegmentReader -list (<segment_dir1> ... | -dir <segments>) [general options]");
- System.err.println(" List a synopsis of segments in specified directories, or all segments in");
- System.err.println(" a directory <segments>, and print it on System.out\n");
- System.err.println("\t<segment_dir1> ...\tlist of segment directories to process");
- System.err.println("\t-dir <segments>\t\tdirectory that contains multiple segments");
+ System.err
+ .println("* SegmentReader -list (<segment_dir1> ... | -dir <segments>) [general options]");
+ System.err
+ .println(" List a synopsis of segments in specified directories, or all segments in");
+ System.err
+ .println(" a directory <segments>, and print it on System.out\n");
+ System.err
+ .println("\t<segment_dir1> ...\tlist of segment directories to process");
+ System.err
+ .println("\t-dir <segments>\t\tdirectory that contains multiple segments");
System.err.println();
- System.err.println("* SegmentReader -get <segment_dir> <keyValue> [general options]");
- System.err.println(" Get a specified record from a segment, and print it on System.out.\n");
+ System.err
+ .println("* SegmentReader -get <segment_dir> <keyValue> [general options]");
+ System.err
+ .println(" Get a specified record from a segment, and print it on System.out.\n");
System.err.println("\t<segment_dir>\tname of the segment directory.");
System.err.println("\t<keyValue>\tvalue of the key (url).");
- System.err.println("\t\tNote: put double-quotes around strings with spaces.");
+ System.err
+ .println("\t\tNote: put double-quotes around strings with spaces.");
}
}
diff --git a/src/java/org/apache/nutch/segment/package-info.java b/src/java/org/apache/nutch/segment/package-info.java
index da768f1cc..ecc0c2648 100644
--- a/src/java/org/apache/nutch/segment/package-info.java
+++ b/src/java/org/apache/nutch/segment/package-info.java
@@ -20,3 +20,4 @@
* fetch list, protocol status, raw content, parsed content, and extracted outgoing links.
*/
package org.apache.nutch.segment;
+
diff --git a/src/java/org/apache/nutch/tools/Benchmark.java b/src/java/org/apache/nutch/tools/Benchmark.java
index 014969875..447e7964a 100755
--- a/src/java/org/apache/nutch/tools/Benchmark.java
+++ b/src/java/org/apache/nutch/tools/Benchmark.java
@@ -52,13 +52,14 @@ public class Benchmark extends Configured implements Tool {
int res = ToolRunner.run(conf, new Benchmark(), args);
System.exit(res);
}
-
+
private static String getDate() {
- return new SimpleDateFormat("yyyyMMddHHmmss").format
- (new Date(System.currentTimeMillis()));
+ return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System
+ .currentTimeMillis()));
}
-
- private void createSeeds(FileSystem fs, Path seedsDir, int count) throws Exception {
+
+ private void createSeeds(FileSystem fs, Path seedsDir, int count)
+ throws Exception {
OutputStream os = fs.create(new Path(seedsDir, "seeds"));
for (int i = 0; i < count; i++) {
String url = "http://www.test-" + i + ".com/\r\n";
@@ -67,9 +68,9 @@ public class Benchmark extends Configured implements Tool {
os.flush();
os.close();
}
-
+
public static final class BenchmarkResults {
- Map<String,Map<String,Long>> timings = new HashMap<String,Map<String,Long>>();
+ Map<String, Map<String, Long>> timings = new HashMap<String, Map<String, Long>>();
List<String> runs = new ArrayList<String>();
List<String> stages = new ArrayList<String>();
int seeds, depth, threads;
@@ -77,7 +78,7 @@ public class Benchmark extends Configured implements Tool {
long topN;
long elapsed;
String plugins;
-
+
public void addTiming(String stage, String run, long timing) {
if (!runs.contains(run)) {
runs.add(run);
@@ -85,14 +86,14 @@ public class Benchmark extends Configured implements Tool {
if (!stages.contains(stage)) {
stages.add(stage);
}
- Map<String,Long> t = timings.get(stage);
+ Map<String, Long> t = timings.get(stage);
if (t == null) {
- t = new HashMap<String,Long>();
+ t = new HashMap<String, Long>();
timings.put(stage, t);
}
t.put(run, timing);
}
-
+
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("* Plugins:\t" + plugins + "\n");
@@ -103,8 +104,9 @@ public class Benchmark extends Configured implements Tool {
sb.append("* Delete:\t" + delete + "\n");
sb.append("* TOTAL ELAPSED:\t" + elapsed + "\n");
for (String stage : stages) {
- Map<String,Long> timing = timings.get(stage);
- if (timing == null) continue;
+ Map<String, Long> timing = timings.get(stage);
+ if (timing == null)
+ continue;
sb.append("- stage: " + stage + "\n");
for (String r : runs) {
Long Time = timing.get(r);
@@ -116,15 +118,16 @@ public class Benchmark extends Configured implements Tool {
}
return sb.toString();
}
-
+
public List<String> getStages() {
return stages;
}
+
public List<String> getRuns() {
return runs;
}
}
-
+
public int run(String[] args) throws Exception {
String plugins = "protocol-http|parse-tika|scoring-opic|urlfilter-regex|urlnormalizer-pass";
int seeds = 1;
@@ -132,17 +135,24 @@ public class Benchmark extends Configured implements Tool {
int threads = 10;
boolean delete = true;
long topN = Long.MAX_VALUE;
-
+
if (args.length == 0) {
- System.err.println("Usage: Benchmark [-seeds NN] [-depth NN] [-threads NN] [-keep] [-maxPerHost NN] [-plugins <regex>]");
- System.err.println("\t-seeds NN\tcreate NN unique hosts in a seed list (default: 1)");
+ System.err
+ .println("Usage: Benchmark [-seeds NN] [-depth NN] [-threads NN] [-keep] [-maxPerHost NN] [-plugins <regex>]");
+ System.err
+ .println("\t-seeds NN\tcreate NN unique hosts in a seed list (default: 1)");
System.err.println("\t-depth NN\tperform NN crawl cycles (default: 10)");
- System.err.println("\t-threads NN\tuse NN threads per Fetcher task (default: 10)");
- System.err.println("\t-keep\tkeep segment data (default: delete after updatedb)");
+ System.err
+ .println("\t-threads NN\tuse NN threads per Fetcher task (default: 10)");
+ System.err
+ .println("\t-keep\tkeep segment data (default: delete after updatedb)");
System.err.println("\t-plugins <regex>\toverride 'plugin.includes'.");
- System.err.println("\tNOTE: if not specified, this is reset to: " + plugins);
- System.err.println("\tNOTE: if 'default' is specified then a value set in nutch-default/nutch-site is used.");
- System.err.println("\t-maxPerHost NN\tmax. # of URLs per host in a fetchlist");
+ System.err.println("\tNOTE: if not specified, this is reset to: "
+ + plugins);
+ System.err
+ .println("\tNOTE: if 'default' is specified then a value set in nutch-default/nutch-site is used.");
+ System.err
+ .println("\t-maxPerHost NN\tmax. # of URLs per host in a fetchlist");
return -1;
}
int maxPerHost = Integer.MAX_VALUE;
@@ -164,13 +174,15 @@ public class Benchmark extends Configured implements Tool {
return -1;
}
}
- BenchmarkResults res = benchmark(seeds, depth, threads, maxPerHost, topN, delete, plugins);
+ BenchmarkResults res = benchmark(seeds, depth, threads, maxPerHost, topN,
+ delete, plugins);
System.out.println(res);
return 0;
}
-
- public BenchmarkResults benchmark(int seeds, int depth, int threads, int maxPerHost,
- long topN, boolean delete, String plugins) throws Exception {
+
+ public BenchmarkResults benchmark(int seeds, int depth, int threads,
+ int maxPerHost, long topN, boolean delete, String plugins)
+ throws Exception {
Configuration conf = getConf();
conf.set("http.proxy.host", "localhost");
conf.setInt("http.proxy.port", 8181);
@@ -180,11 +192,12 @@ public class Benchmark extends Configured implements Tool {
conf.set("plugin.includes", plugins);
}
conf.setInt(Generator.GENERATOR_MAX_COUNT, maxPerHost);
- conf.set(Generator.GENERATOR_COUNT_MODE, Generator.GENERATOR_COUNT_VALUE_HOST);
- JobConf job = new NutchJob(getConf());
+ conf.set(Generator.GENERATOR_COUNT_MODE,
+ Generator.GENERATOR_COUNT_VALUE_HOST);
+ JobConf job = new NutchJob(getConf());
FileSystem fs = FileSystem.get(job);
- Path dir = new Path(getConf().get("hadoop.tmp.dir"),
- "bench-" + System.currentTimeMillis());
+ Path dir = new Path(getConf().get("hadoop.tmp.dir"), "bench-"
+ + System.currentTimeMillis());
fs.mkdirs(dir);
Path rootUrlDir = new Path(dir, "seed");
fs.mkdirs(rootUrlDir);
@@ -194,7 +207,7 @@ public class Benchmark extends Configured implements Tool {
LOG.info("crawl started in: " + dir);
LOG.info("rootUrlDir = " + rootUrlDir);
LOG.info("threads = " + threads);
- LOG.info("depth = " + depth);
+ LOG.info("depth = " + depth);
}
BenchmarkResults res = new BenchmarkResults();
res.delete = delete;
@@ -213,17 +226,17 @@ public class Benchmark extends Configured implements Tool {
ParseSegment parseSegment = new ParseSegment(getConf());
CrawlDb crawlDbTool = new CrawlDb(getConf());
LinkDb linkDbTool = new LinkDb(getConf());
-
+
// initialize crawlDb
long start = System.currentTimeMillis();
injector.inject(crawlDb, rootUrlDir);
long delta = System.currentTimeMillis() - start;
res.addTiming("inject", "0", delta);
int i;
- for (i = 0; i < depth; i++) { // generate new segment
+ for (i = 0; i < depth; i++) { // generate new segment
start = System.currentTimeMillis();
- Path[] segs = generator.generate(crawlDb, segments, -1, topN, System
- .currentTimeMillis());
+ Path[] segs = generator.generate(crawlDb, segments, -1, topN,
+ System.currentTimeMillis());
delta = System.currentTimeMillis() - start;
res.addTiming("generate", i + "", delta);
if (segs == null) {
@@ -231,12 +244,12 @@ public class Benchmark extends Configured implements Tool {
break;
}
start = System.currentTimeMillis();
- fetcher.fetch(segs[0], threads); // fetch it
+ fetcher.fetch(segs[0], threads); // fetch it
delta = System.currentTimeMillis() - start;
res.addTiming("fetch", i + "", delta);
if (!Fetcher.isParsing(job)) {
start = System.currentTimeMillis();
- parseSegment.parse(segs[0]); // parse it, if needed
+ parseSegment.parse(segs[0]); // parse it, if needed
delta = System.currentTimeMillis() - start;
res.addTiming("parse", i + "", delta);
}
@@ -258,7 +271,9 @@ public class Benchmark extends Configured implements Tool {
if (i == 0) {
LOG.warn("No URLs to fetch - check your seed list and URL filters.");
}
- if (LOG.isInfoEnabled()) { LOG.info("crawl finished: " + dir); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("crawl finished: " + dir);
+ }
res.elapsed = System.currentTimeMillis() - res.elapsed;
CrawlDbReader dbreader = new CrawlDbReader();
dbreader.processStatJob(crawlDb.toString(), conf, false);
diff --git a/src/java/org/apache/nutch/tools/DmozParser.java b/src/java/org/apache/nutch/tools/DmozParser.java
index ef66b3cf5..54ec54380 100644
--- a/src/java/org/apache/nutch/tools/DmozParser.java
+++ b/src/java/org/apache/nutch/tools/DmozParser.java
@@ -35,16 +35,15 @@ import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.util.NutchConfiguration;
-
/** Utility that converts DMOZ RDF into a flat file of URLs to be injected. */
public class DmozParser {
public static final Logger LOG = LoggerFactory.getLogger(DmozParser.class);
-
- long pages = 0;
+
+ long pages = 0;
/**
- * This filter fixes characters that might offend our parser.
- * This lets us be tolerant of errors that might appear in the input XML.
+ * This filter fixes characters that might offend our parser. This lets us be
+ * tolerant of errors that might appear in the input XML.
*/
private static class XMLCharFilter extends FilterReader {
private boolean lastBad = false;
@@ -56,9 +55,9 @@ public class DmozParser {
public int read() throws IOException {
int c = in.read();
int value = c;
- if (c != -1 && !(XMLChar.isValid(c))) // fix invalid characters
+ if (c != -1 && !(XMLChar.isValid(c))) // fix invalid characters
value = 'X';
- else if (lastBad && c == '<') { // fix mis-matched brackets
+ else if (lastBad && c == '<') { // fix mis-matched brackets
in.mark(1);
if (in.read() != '/')
value = 'X';
@@ -69,37 +68,35 @@ public class DmozParser {
return value;
}
- public int read(char[] cbuf, int off, int len)
- throws IOException {
+ public int read(char[] cbuf, int off, int len) throws IOException {
int n = in.read(cbuf, off, len);
if (n != -1) {
for (int i = 0; i < n; i++) {
- char c = cbuf[off+i];
+ char c = cbuf[off + i];
char value = c;
- if (!(XMLChar.isValid(c))) // fix invalid characters
+ if (!(XMLChar.isValid(c))) // fix invalid characters
value = 'X';
- else if (lastBad && c == '<') { // fix mis-matched brackets
- if (i != n-1 && cbuf[off+i+1] != '/')
+ else if (lastBad && c == '<') { // fix mis-matched brackets
+ if (i != n - 1 && cbuf[off + i + 1] != '/')
value = 'X';
}
lastBad = (c == 65533);
- cbuf[off+i] = value;
+ cbuf[off + i] = value;
}
}
return n;
}
}
-
/**
- * The RDFProcessor receives tag messages during a parse
- * of RDF XML data. We build whatever structures we need
- * from these messages.
+ * The RDFProcessor receives tag messages during a parse of RDF XML data. We
+ * build whatever structures we need from these messages.
*/
private class RDFProcessor extends DefaultHandler {
String curURL = null, curSection = null;
- boolean titlePending = false, descPending = false, insideAdultSection = false;
- Pattern topicPattern = null;
+ boolean titlePending = false, descPending = false,
+ insideAdultSection = false;
+ Pattern topicPattern = null;
StringBuffer title = new StringBuffer(), desc = new StringBuffer();
XMLReader reader;
int subsetDenom;
@@ -108,10 +105,12 @@ public class DmozParser {
Locator location;
/**
- * Pass in an XMLReader, plus a flag as to whether we
- * should include adult material.
+ * Pass in an XMLReader, plus a flag as to whether we should include adult
+ * material.
*/
- public RDFProcessor(XMLReader reader, int subsetDenom, boolean includeAdult, int skew, Pattern topicPattern) throws IOException {
+ public RDFProcessor(XMLReader reader, int subsetDenom,
+ boolean includeAdult, int skew, Pattern topicPattern)
+ throws IOException {
this.reader = reader;
this.subsetDenom = subsetDenom;
this.includeAdult = includeAdult;
@@ -127,20 +126,21 @@ public class DmozParser {
/**
* Start of an XML elt
*/
- public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
+ public void startElement(String namespaceURI, String localName,
+ String qName, Attributes atts) throws SAXException {
if ("Topic".equals(qName)) {
curSection = atts.getValue("r:id");
} else if ("ExternalPage".equals(qName)) {
// Porn filter
- if ((! includeAdult) && curSection.startsWith("Top/Adult")) {
+ if ((!includeAdult) && curSection.startsWith("Top/Adult")) {
return;
}
-
+
if (topicPattern != null && !topicPattern.matcher(curSection).matches()) {
return;
}
- // Subset denominator filter.
+ // Subset denominator filter.
// Only emit with a chance of 1/denominator.
String url = atts.getValue("about");
int hashValue = MD5Hash.digest(url).hashCode();
@@ -173,18 +173,18 @@ public class DmozParser {
* Termination of XML elt
*/
public void endElement(String namespaceURI, String localName, String qName)
- throws SAXException {
+ throws SAXException {
if (curURL != null) {
if ("ExternalPage".equals(qName)) {
//
- // Inc the number of pages, insert the page, and
+ // Inc the number of pages, insert the page, and
// possibly print status.
//
- System.out.println(curURL);
+ System.out.println(curURL);
pages++;
//
- // Clear out the link text. This is what
+ // Clear out the link text. This is what
// you would use for adding to the linkdb.
//
if (title.length() > 0) {
@@ -219,15 +219,13 @@ public class DmozParser {
}
/**
- * From time to time the Parser will set the "current location"
- * by calling this function. It's useful for emitting locations
- * for error messages.
+ * From time to time the Parser will set the "current location" by calling
+ * this function. It's useful for emitting locations for error messages.
*/
public void setDocumentLocator(Locator locator) {
location = locator;
}
-
//
// Interface ErrorHandler
//
@@ -247,11 +245,11 @@ public class DmozParser {
public void errorError(SAXParseException spe) {
if (LOG.isErrorEnabled()) {
LOG.error("Fatal err: " + spe.toString() + ": " + spe.getMessage());
- LOG.error("Last known line is " + location.getLineNumber() +
- ", column " + location.getColumnNumber());
+ LOG.error("Last known line is " + location.getLineNumber()
+ + ", column " + location.getColumnNumber());
}
}
-
+
/**
* Emit exception warning message
*/
@@ -263,34 +261,33 @@ public class DmozParser {
}
/**
- * Iterate through all the items in this structured DMOZ file.
- * Add each URL to the web db.
+ * Iterate through all the items in this structured DMOZ file. Add each URL to
+ * the web db.
*/
public void parseDmozFile(File dmozFile, int subsetDenom,
- boolean includeAdult,
- int skew,
- Pattern topicPattern)
+ boolean includeAdult, int skew, Pattern topicPattern)
- throws IOException, SAXException, ParserConfigurationException {
+ throws IOException, SAXException, ParserConfigurationException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
// Create our own processor to receive SAX events
- RDFProcessor rp =
- new RDFProcessor(reader, subsetDenom, includeAdult,
- skew, topicPattern);
+ RDFProcessor rp = new RDFProcessor(reader, subsetDenom, includeAdult, skew,
+ topicPattern);
reader.setContentHandler(rp);
reader.setErrorHandler(rp);
LOG.info("skew = " + rp.hashSkew);
//
- // Open filtered text stream. The TextFilter makes sure that
+ // Open filtered text stream. The TextFilter makes sure that
// only appropriate XML-approved Text characters are received.
// Any non-conforming characters are silently skipped.
//
- XMLCharFilter in = new XMLCharFilter(new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(dmozFile)), "UTF-8")));
+ XMLCharFilter in = new XMLCharFilter(new BufferedReader(
+ new InputStreamReader(new BufferedInputStream(new FileInputStream(
+ dmozFile)), "UTF-8")));
try {
InputSource is = new InputSource(in);
reader.parse(is);
@@ -304,18 +301,17 @@ public class DmozParser {
}
}
- private static void addTopicsFromFile(String topicFile,
- Vector<String> topics)
- throws IOException {
+ private static void addTopicsFromFile(String topicFile, Vector<String> topics)
+ throws IOException {
BufferedReader in = null;
try {
- in = new BufferedReader(new InputStreamReader(new FileInputStream(topicFile), "UTF-8"));
+ in = new BufferedReader(new InputStreamReader(new FileInputStream(
+ topicFile), "UTF-8"));
String line = null;
while ((line = in.readLine()) != null) {
topics.addElement(new String(line));
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.toString());
}
@@ -324,18 +320,19 @@ public class DmozParser {
in.close();
}
}
-
+
/**
- * Command-line access. User may add URLs via a flat text file
- * or the structured DMOZ file. By default, we ignore Adult
- * material (as categorized by DMOZ).
+ * Command-line access. User may add URLs via a flat text file or the
+ * structured DMOZ file. By default, we ignore Adult material (as categorized
+ * by DMOZ).
*/
public static void main(String argv[]) throws Exception {
if (argv.length < 1) {
- System.err.println("Usage: DmozParser <dmoz_file> [-subset <subsetDenominator>] [-includeAdultMaterial] [-skew skew] [-topicFile <topic list file>] [-topic <topic> [-topic <topic> [...]]]");
+ System.err
+ .println("Usage: DmozParser <dmoz_file> [-subset <subsetDenominator>] [-includeAdultMaterial] [-skew skew] [-topicFile <topic list file>] [-topic <topic> [-topic <topic> [...]]]");
return;
}
-
+
//
// Parse the command line, figure out what kind of
// URL file we need to load
@@ -344,9 +341,9 @@ public class DmozParser {
int skew = 0;
String dmozFile = argv[0];
boolean includeAdult = false;
- Pattern topicPattern = null;
+ Pattern topicPattern = null;
Vector<String> topics = new Vector<String>();
-
+
Configuration conf = NutchConfiguration.create();
FileSystem fs = FileSystem.get(conf);
try {
@@ -354,16 +351,16 @@ public class DmozParser {
if ("-includeAdultMaterial".equals(argv[i])) {
includeAdult = true;
} else if ("-subset".equals(argv[i])) {
- subsetDenom = Integer.parseInt(argv[i+1]);
+ subsetDenom = Integer.parseInt(argv[i + 1]);
i++;
} else if ("-topic".equals(argv[i])) {
- topics.addElement(argv[i+1]);
+ topics.addElement(argv[i + 1]);
i++;
} else if ("-topicFile".equals(argv[i])) {
- addTopicsFromFile(argv[i+1], topics);
+ addTopicsFromFile(argv[i + 1], topics);
i++;
} else if ("-skew".equals(argv[i])) {
- skew = Integer.parseInt(argv[i+1]);
+ skew = Integer.parseInt(argv[i + 1]);
i++;
}
}
@@ -371,21 +368,21 @@ public class DmozParser {
DmozParser parser = new DmozParser();
if (!topics.isEmpty()) {
- String regExp = new String("^(");
+ String regExp = new String("^(");
int j = 0;
- for ( ; j < topics.size() - 1; ++j) {
+ for (; j < topics.size() - 1; ++j) {
regExp = regExp.concat(topics.get(j));
regExp = regExp.concat("|");
}
regExp = regExp.concat(topics.get(j));
- regExp = regExp.concat(").*");
+ regExp = regExp.concat(").*");
LOG.info("Topic selection pattern = " + regExp);
- topicPattern = Pattern.compile(regExp);
+ topicPattern = Pattern.compile(regExp);
}
- parser.parseDmozFile(new File(dmozFile), subsetDenom,
- includeAdult, skew, topicPattern);
-
+ parser.parseDmozFile(new File(dmozFile), subsetDenom, includeAdult, skew,
+ topicPattern);
+
} finally {
fs.close();
}
diff --git a/src/java/org/apache/nutch/tools/FileDumper.java b/src/java/org/apache/nutch/tools/FileDumper.java
index 0f0923b1b..cb719c90f 100644
--- a/src/java/org/apache/nutch/tools/FileDumper.java
+++ b/src/java/org/apache/nutch/tools/FileDumper.java
@@ -54,20 +54,26 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * <p>The file dumper tool enables one to reverse generate the raw content
- * from Nutch segment data directories. </p>
+ * <p>
+ * The file dumper tool enables one to reverse generate the raw content from
+ * Nutch segment data directories.
+ * </p>
* <p>
* The tool has a number of immediate uses:
* <ol>
* <li>one can see what a page looked like at the time it was crawled</li>
* <li>one can see different media types acquired as part of the crawl</li>
- * <li>it enables us to see webpages before we augment them with additional metadata,
- * this can be handy for providing a provenance trail for your crawl data.</li>
+ * <li>it enables us to see webpages before we augment them with additional
+ * metadata, this can be handy for providing a provenance trail for your crawl
+ * data.</li>
* </ol>
* </p>
- * <p>Upon successful completion the tool displays a very convenient JSON snippet
- * detailing the mimetype classifications and the counts of documents which
- * fall into those classifications. An example is as follows:</p>
+ * <p>
+ * Upon successful completion the tool displays a very convenient JSON snippet
+ * detailing the mimetype classifications and the counts of documents which fall
+ * into those classifications. An example is as follows:
+ * </p>
+ *
* <pre>
* {@code
* INFO: File Types:
@@ -92,45 +98,53 @@ import org.slf4j.LoggerFactory;
* }
* }
* </pre>
- * <p>In the case above the tool would have been run with the <b>-mimeType
- * image/png image/jpeg image/vnd.microsoft.icon video/quicktime image/gif</b>
+ * <p>
+ * In the case above the tool would have been run with the <b>-mimeType
+ * image/png image/jpeg image/vnd.microsoft.icon video/quicktime image/gif</b>
* flag and corresponding values activated.
- *
+ *
*/
public class FileDumper {
private static final Logger LOG = LoggerFactory.getLogger(FileDumper.class
.getName());
-
/**
- * Dumps the reverse engineered raw content from the provided segment directories
- * if a parent directory contains more than one segment, otherwise a single segment
- * can be passed as an argument.
- * @param outputDir the directory you wish to dump the raw content to. This directory will be created.
- * @param segmentRootDir a directory containing one or more segments.
- * @param mimeTypes an array of mime types we have to dump, all others will be filtered out.
+ * Dumps the reverse engineered raw content from the provided segment
+ * directories if a parent directory contains more than one segment, otherwise
+ * a single segment can be passed as an argument.
+ *
+ * @param outputDir
+ * the directory you wish to dump the raw content to. This directory
+ * will be created.
+ * @param segmentRootDir
+ * a directory containing one or more segments.
+ * @param mimeTypes
+ * an array of mime types we have to dump, all others will be
+ * filtered out.
* @throws Exception
*/
- public void dump(File outputDir, File segmentRootDir, String[] mimeTypes) throws Exception {
- if (mimeTypes == null) LOG.info("Accepting all mimetypes.");
- //total file counts
+ public void dump(File outputDir, File segmentRootDir, String[] mimeTypes)
+ throws Exception {
+ if (mimeTypes == null)
+ LOG.info("Accepting all mimetypes.");
+ // total file counts
Map<String, Integer> typeCounts = new HashMap<String, Integer>();
- //filtered file counts
+ // filtered file counts
Map<String, Integer> filteredCounts = new HashMap<String, Integer>();
Configuration conf = NutchConfiguration.create();
FileSystem fs = FileSystem.get(conf);
int fileCount = 0;
- File[] segmentDirs = segmentRootDir
- .listFiles(new FileFilter() {
+ File[] segmentDirs = segmentRootDir.listFiles(new FileFilter() {
- @Override
- public boolean accept(File file) {
- return file.canRead() && file.isDirectory();
- }
- });
+ @Override
+ public boolean accept(File file) {
+ return file.canRead() && file.isDirectory();
+ }
+ });
if (segmentDirs == null) {
- System.err.println("No segment directories found in [" + segmentRootDir.getAbsolutePath() + "]");
+ System.err.println("No segment directories found in ["
+ + segmentRootDir.getAbsolutePath() + "]");
return;
}
@@ -138,18 +152,17 @@ public class FileDumper {
LOG.info("Processing segment: [" + segment.getAbsolutePath() + "]");
DataOutputStream doutputStream = null;
try {
- String segmentPath = segment.getAbsolutePath()
- + "/" + Content.DIR_NAME + "/part-00000/data";
+ String segmentPath = segment.getAbsolutePath() + "/" + Content.DIR_NAME
+ + "/part-00000/data";
Path file = new Path(segmentPath);
if (!new File(file.toString()).exists()) {
LOG.warn("Skipping segment: [" + segmentPath
+ "]: no data directory present");
continue;
}
- SequenceFile.Reader reader = new SequenceFile.Reader(fs, file,
- conf);
+ SequenceFile.Reader reader = new SequenceFile.Reader(fs, file, conf);
- Writable key = (Writable)reader.getKeyClass().newInstance();
+ Writable key = (Writable) reader.getKeyClass().newInstance();
Content content = null;
while (reader.next(key)) {
@@ -158,35 +171,33 @@ public class FileDumper {
String url = key.toString();
String baseName = FilenameUtils.getBaseName(url);
String extension = FilenameUtils.getExtension(url);
- if (extension == null || (extension != null &&
- extension.equals(""))){
+ if (extension == null || (extension != null && extension.equals(""))) {
extension = "html";
}
String filename = baseName + "." + extension;
ByteArrayInputStream bas = null;
Boolean filter = false;
- try{
+ try {
bas = new ByteArrayInputStream(content.getContent());
String mimeType = new Tika().detect(content.getContent());
collectStats(typeCounts, mimeType);
if (mimeType != null) {
- if (mimeTypes == null || Arrays.asList(mimeTypes).contains(mimeType)) {
+ if (mimeTypes == null
+ || Arrays.asList(mimeTypes).contains(mimeType)) {
collectStats(filteredCounts, mimeType);
filter = true;
}
}
- }
- catch(Exception e){
+ } catch (Exception e) {
e.printStackTrace();
- LOG.warn("Tika is unable to detect type for: ["+url+"]");
- }
- finally{
- if(bas != null){
- try{
+ LOG.warn("Tika is unable to detect type for: [" + url + "]");
+ } finally {
+ if (bas != null) {
+ try {
bas.close();
+ } catch (Exception ignore) {
}
- catch(Exception ignore){}
}
}
@@ -199,51 +210,58 @@ public class FileDumper {
IOUtils.write(content.getContent(), output);
fileCount++;
} else {
- LOG.info("Skipping writing: ["
- + outputFullPath + "]: file already exists");
+ LOG.info("Skipping writing: [" + outputFullPath
+ + "]: file already exists");
}
}
}
reader.close();
- }
- finally {
+ } finally {
fs.close();
- if (doutputStream != null){
- try{
+ if (doutputStream != null) {
+ try {
doutputStream.close();
+ } catch (Exception ignore) {
}
- catch (Exception ignore){}
}
}
}
- LOG.info("Dumper File Stats: " + displayFileTypes(typeCounts, filteredCounts));
+ LOG.info("Dumper File Stats: "
+ + displayFileTypes(typeCounts, filteredCounts));
}
/**
* Main method for invoking this tool
- * @param args 1) output directory (which will be created) to host the
- * raw data and 2) a directory containing one or more segments.
+ *
+ * @param args
+ * 1) output directory (which will be created) to host the raw data
+ * and 2) a directory containing one or more segments.
* @throws Exception
*/
public static void main(String[] args) throws Exception {
- //boolean options
+ // boolean options
Option helpOpt = new Option("h", "help", false, "show this help message");
- //argument options
+ // argument options
@SuppressWarnings("static-access")
- Option outputOpt = OptionBuilder.withArgName("outputDir")
- .hasArg().withDescription("output directory (which will be created) to host the raw data")
- .create("outputDir");
+ Option outputOpt = OptionBuilder
+ .withArgName("outputDir")
+ .hasArg()
+ .withDescription(
+ "output directory (which will be created) to host the raw data")
+ .create("outputDir");
@SuppressWarnings("static-access")
- Option segOpt = OptionBuilder.withArgName("segment")
- .hasArgs().withDescription("the segment(s) to use")
- .create("segment");
+ Option segOpt = OptionBuilder.withArgName("segment").hasArgs()
+ .withDescription("the segment(s) to use").create("segment");
@SuppressWarnings("static-access")
- Option mimeOpt = OptionBuilder.withArgName("mimetype")
- .hasArgs().withDescription("an optional list of mimetypes to dump, excluding all others. Defaults to all.")
- .create("mimetype");
+ Option mimeOpt = OptionBuilder
+ .withArgName("mimetype")
+ .hasArgs()
+ .withDescription(
+ "an optional list of mimetypes to dump, excluding all others. Defaults to all.")
+ .create("mimetype");
- //create the options
+ // create the options
Options options = new Options();
options.addOption(helpOpt);
options.addOption(outputOpt);
@@ -267,13 +285,14 @@ public class FileDumper {
if (!outputDir.exists()) {
LOG.warn("Output directory: [" + outputDir.getAbsolutePath()
+ "]: does not exist, creating it.");
- if(!outputDir.mkdirs()) throw new Exception("Unable to create: ["+outputDir.getAbsolutePath()+"]");
+ if (!outputDir.mkdirs())
+ throw new Exception("Unable to create: ["
+ + outputDir.getAbsolutePath() + "]");
}
FileDumper dumper = new FileDumper();
dumper.dump(outputDir, segmentRootDir, mimeTypes);
- }
- catch(Exception e) {
+ } catch (Exception e) {
LOG.error("FileDumper: " + StringUtils.stringifyException(e));
e.printStackTrace();
return;
@@ -282,13 +301,13 @@ public class FileDumper {
private void collectStats(Map<String, Integer> typeCounts, String mimeType) {
typeCounts.put(mimeType,
- typeCounts.containsKey(mimeType) ? typeCounts.get(mimeType) + 1
- : 1);
+ typeCounts.containsKey(mimeType) ? typeCounts.get(mimeType) + 1 : 1);
}
- private String displayFileTypes(Map<String, Integer> typeCounts, Map<String, Integer> filteredCounts) {
- StringBuilder builder = new StringBuilder();
- //print total stats
+ private String displayFileTypes(Map<String, Integer> typeCounts,
+ Map<String, Integer> filteredCounts) {
+ StringBuilder builder = new StringBuilder();
+ // print total stats
builder.append("\n TOTAL Stats:\n");
builder.append(" {\n");
for (String mimeType : typeCounts.keySet()) {
diff --git a/src/java/org/apache/nutch/tools/FreeGenerator.java b/src/java/org/apache/nutch/tools/FreeGenerator.java
index 7f068132d..138372f7f 100644
--- a/src/java/org/apache/nutch/tools/FreeGenerator.java
+++ b/src/java/org/apache/nutch/tools/FreeGenerator.java
@@ -54,19 +54,20 @@ import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.TimingUtil;
/**
- * This tool generates fetchlists (segments to be fetched) from plain text
- * files containing one URL per line. It's useful when arbitrary URL-s need to
- * be fetched without adding them first to the CrawlDb, or during testing.
+ * This tool generates fetchlists (segments to be fetched) from plain text files
+ * containing one URL per line. It's useful when arbitrary URL-s need to be
+ * fetched without adding them first to the CrawlDb, or during testing.
*/
public class FreeGenerator extends Configured implements Tool {
- private static final Logger LOG = LoggerFactory.getLogger(FreeGenerator.class);
-
+ private static final Logger LOG = LoggerFactory
+ .getLogger(FreeGenerator.class);
+
private static final String FILTER_KEY = "free.generator.filter";
private static final String NORMALIZE_KEY = "free.generator.normalize";
- public static class FG extends MapReduceBase
- implements Mapper<WritableComparable<?>, Text, Text, Generator.SelectorEntry>,
- Reducer<Text, Generator.SelectorEntry, Text, CrawlDatum> {
+ public static class FG extends MapReduceBase implements
+ Mapper<WritableComparable<?>, Text, Text, Generator.SelectorEntry>,
+ Reducer<Text, Generator.SelectorEntry, Text, CrawlDatum> {
private URLNormalizers normalizers = null;
private URLFilters filters = null;
private ScoringFilters scfilters;
@@ -89,13 +90,15 @@ public class FreeGenerator extends Configured implements Tool {
Generator.SelectorEntry entry = new Generator.SelectorEntry();
- public void map(WritableComparable<?> key, Text value, OutputCollector<Text,
- Generator.SelectorEntry> output, Reporter reporter) throws IOException {
+ public void map(WritableComparable<?> key, Text value,
+ OutputCollector<Text, Generator.SelectorEntry> output, Reporter reporter)
+ throws IOException {
// value is a line of text
String urlString = value.toString();
try {
if (normalizers != null) {
- urlString = normalizers.normalize(urlString, URLNormalizers.SCOPE_INJECT);
+ urlString = normalizers.normalize(urlString,
+ URLNormalizers.SCOPE_INJECT);
}
if (urlString != null && filters != null) {
urlString = filters.filter(urlString);
@@ -105,7 +108,8 @@ public class FreeGenerator extends Configured implements Tool {
scfilters.injectedScore(url, datum);
}
} catch (Exception e) {
- LOG.warn("Error adding url '" + value.toString() + "', skipping: " + StringUtils.stringifyException(e));
+ LOG.warn("Error adding url '" + value.toString() + "', skipping: "
+ + StringUtils.stringifyException(e));
return;
}
if (urlString == null) {
@@ -122,8 +126,10 @@ public class FreeGenerator extends Configured implements Tool {
}
public void reduce(Text key, Iterator<Generator.SelectorEntry> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter) throws IOException {
- // pick unique urls from values - discard the reduce key due to hash collisions
+ OutputCollector<Text, CrawlDatum> output, Reporter reporter)
+ throws IOException {
+ // pick unique urls from values - discard the reduce key due to hash
+ // collisions
HashMap<Text, CrawlDatum> unique = new HashMap<Text, CrawlDatum>();
while (values.hasNext()) {
Generator.SelectorEntry entry = values.next();
@@ -138,12 +144,17 @@ public class FreeGenerator extends Configured implements Tool {
public int run(String[] args) throws Exception {
if (args.length < 2) {
- System.err.println("Usage: FreeGenerator <inputDir> <segmentsDir> [-filter] [-normalize]");
- System.err.println("\tinputDir\tinput directory containing one or more input files.");
- System.err.println("\t\tEach text file contains a list of URLs, one URL per line");
- System.err.println("\tsegmentsDir\toutput directory, where new segment will be created");
+ System.err
+ .println("Usage: FreeGenerator <inputDir> <segmentsDir> [-filter] [-normalize]");
+ System.err
+ .println("\tinputDir\tinput directory containing one or more input files.");
+ System.err
+ .println("\t\tEach text file contains a list of URLs, one URL per line");
+ System.err
+ .println("\tsegmentsDir\toutput directory, where new segment will be created");
System.err.println("\t-filter\trun current URLFilters on input URLs");
- System.err.println("\t-normalize\trun current URLNormalizers on input URLs");
+ System.err
+ .println("\t-normalize\trun current URLNormalizers on input URLs");
return -1;
}
boolean filter = false;
@@ -181,8 +192,8 @@ public class FreeGenerator extends Configured implements Tool {
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
job.setOutputKeyComparatorClass(Generator.HashComparator.class);
- FileOutputFormat.setOutputPath(job, new Path(args[1],
- new Path(segName, CrawlDatum.GENERATE_DIR_NAME)));
+ FileOutputFormat.setOutputPath(job, new Path(args[1], new Path(segName,
+ CrawlDatum.GENERATE_DIR_NAME)));
try {
JobClient.runJob(job);
} catch (Exception e) {
@@ -190,12 +201,14 @@ public class FreeGenerator extends Configured implements Tool {
return -1;
}
long end = System.currentTimeMillis();
- LOG.info("FreeGenerator: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("FreeGenerator: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
return 0;
}
public static void main(String[] args) throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new FreeGenerator(), args);
+ int res = ToolRunner.run(NutchConfiguration.create(), new FreeGenerator(),
+ args);
System.exit(res);
}
}
diff --git a/src/java/org/apache/nutch/tools/ResolveUrls.java b/src/java/org/apache/nutch/tools/ResolveUrls.java
index 8e49caa9b..2b1c63b99 100644
--- a/src/java/org/apache/nutch/tools/ResolveUrls.java
+++ b/src/java/org/apache/nutch/tools/ResolveUrls.java
@@ -59,8 +59,7 @@ public class ResolveUrls {
/**
* A Thread which gets the ip address of a single host by name.
*/
- private static class ResolverThread
- extends Thread {
+ private static class ResolverThread extends Thread {
private String url = null;
@@ -74,14 +73,13 @@ public class ResolveUrls {
String host = URLUtil.getHost(url);
long start = System.currentTimeMillis();
try {
-
- // get the address by name and if no error is thrown then it
+
+ // get the address by name and if no error is thrown then it
// is resolved successfully
InetAddress.getByName(host);
LOG.info("Resolved: " + host);
numResolved.incrementAndGet();
- }
- catch (Exception uhe) {
+ } catch (Exception uhe) {
LOG.info("Error Resolving: " + host);
numErrored.incrementAndGet();
}
@@ -93,8 +91,8 @@ public class ResolveUrls {
}
/**
- * Creates a thread pool for resolving urls. Reads in the url file on the
- * local filesystem. For each url it attempts to resolve it keeping a total
+ * Creates a thread pool for resolving urls. Reads in the url file on the
+ * local filesystem. For each url it attempts to resolve it keeping a total
* account of the number resolved, errored, and the amount of time.
*/
public void resolveUrls() {
@@ -103,13 +101,13 @@ public class ResolveUrls {
// create a thread pool with a fixed number of threads
pool = Executors.newFixedThreadPool(numThreads);
-
+
// read in the urls file and loop through each line, one url per line
BufferedReader buffRead = new BufferedReader(new FileReader(new File(
- urlsFile)));
+ urlsFile)));
String urlStr = null;
while ((urlStr = buffRead.readLine()) != null) {
-
+
// spin up a resolver thread per url
LOG.info("Starting: " + urlStr);
pool.execute(new ResolverThread(urlStr));
@@ -119,9 +117,8 @@ public class ResolveUrls {
// the thread pool to give urls time to finish resolving
buffRead.close();
pool.awaitTermination(60, TimeUnit.SECONDS);
- }
- catch (Exception e) {
-
+ } catch (Exception e) {
+
// on error shutdown the thread pool immediately
pool.shutdownNow();
LOG.info(StringUtils.stringifyException(e));
@@ -129,15 +126,16 @@ public class ResolveUrls {
// shutdown the thread pool and log totals
pool.shutdown();
- LOG.info("Total: " + numTotal.get() + ", Resovled: "
- + numResolved.get() + ", Errored: " + numErrored.get()
- + ", Average Time: " + totalTime.get() / numTotal.get());
+ LOG.info("Total: " + numTotal.get() + ", Resovled: " + numResolved.get()
+ + ", Errored: " + numErrored.get() + ", Average Time: "
+ + totalTime.get() / numTotal.get());
}
/**
* Create a new ResolveUrls with a file from the local file system.
- *
- * @param urlsFile The local urls file, one url per line.
+ *
+ * @param urlsFile
+ * The local urls file, one url per line.
*/
public ResolveUrls(String urlsFile) {
this(urlsFile, 100);
@@ -145,10 +143,12 @@ public class ResolveUrls {
/**
* Create a new ResolveUrls with a urls file and a number of threads for the
- * Thread pool. Number of threads is 100 by default.
+ * Thread pool. Number of threads is 100 by default.
*
- * @param urlsFile The local urls file, one url per line.
- * @param numThreads The number of threads used to resolve urls in parallel.
+ * @param urlsFile
+ * The local urls file, one url per line.
+ * @param numThreads
+ * The number of threads used to resolve urls in parallel.
*/
public ResolveUrls(String urlsFile, int numThreads) {
this.urlsFile = urlsFile;
@@ -165,13 +165,13 @@ public class ResolveUrls {
OptionBuilder.withDescription("show this help message");
Option helpOpts = OptionBuilder.create("help");
options.addOption(helpOpts);
-
+
OptionBuilder.withArgName("urls");
OptionBuilder.hasArg();
OptionBuilder.withDescription("the urls file to check");
Option urlOpts = OptionBuilder.create("urls");
options.addOption(urlOpts);
-
+
OptionBuilder.withArgName("numThreads");
OptionBuilder.hasArgs();
OptionBuilder.withDescription("the number of threads to use");
@@ -197,8 +197,7 @@ public class ResolveUrls {
}
ResolveUrls resolve = new ResolveUrls(urls, numThreads);
resolve.resolveUrls();
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("ResolveUrls: " + StringUtils.stringifyException(e));
}
}
diff --git a/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java b/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java
index 9e60c0611..0eb7bf6e2 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java
@@ -30,21 +30,22 @@ import org.apache.hadoop.mapred.Reporter;
/**
* A input format the reads arc files.
*/
-public class ArcInputFormat
- extends FileInputFormat<Text, BytesWritable> {
+public class ArcInputFormat extends FileInputFormat<Text, BytesWritable> {
/**
* Returns the <code>RecordReader</code> for reading the arc file.
*
- * @param split The InputSplit of the arc file to process.
- * @param job The job configuration.
- * @param reporter The progress reporter.
+ * @param split
+ * The InputSplit of the arc file to process.
+ * @param job
+ * The job configuration.
+ * @param reporter
+ * The progress reporter.
*/
public RecordReader<Text, BytesWritable> getRecordReader(InputSplit split,
- JobConf job, Reporter reporter)
- throws IOException {
+ JobConf job, Reporter reporter) throws IOException {
reporter.setStatus(split.toString());
- return new ArcRecordReader(job, (FileSplit)split);
+ return new ArcRecordReader(job, (FileSplit) split);
}
}
diff --git a/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java b/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
index 60c97cc8b..e9ff58d4b 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
@@ -34,23 +34,28 @@ import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
/**
- * <p>The <code>ArchRecordReader</code> class provides a record reader which
- * reads records from arc files.</p>
+ * <p>
+ * The <code>ArchRecordReader</code> class provides a record reader which reads
+ * records from arc files.
+ * </p>
*
- * <p>Arc files are essentially tars of gzips. Each record in an arc file is
- * a compressed gzip. Multiple records are concatenated together to form a
- * complete arc. For more information on the arc file format see
- * {@link http://www.archive.org/web/researcher/ArcFileFormat.php } .</p>
+ * <p>
+ * Arc files are essentially tars of gzips. Each record in an arc file is a
+ * compressed gzip. Multiple records are concatenated together to form a
+ * complete arc. For more information on the arc file format see {@link http
+ * ://www.archive.org/web/researcher/ArcFileFormat.php } .
+ * </p>
*
- * <p>Arc files are used by the internet archive and grub projects.</p>
+ * <p>
+ * Arc files are used by the internet archive and grub projects.
+ * </p>
*
- * see {@link http://www.archive.org/ }
- * see {@link http://www.grub.org/ }
+ * see {@link http://www.archive.org/ } see {@link http://www.grub.org/ }
*/
-public class ArcRecordReader
- implements RecordReader<Text, BytesWritable> {
+public class ArcRecordReader implements RecordReader<Text, BytesWritable> {
- public static final Logger LOG = LoggerFactory.getLogger(ArcRecordReader.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(ArcRecordReader.class);
protected Configuration conf;
protected long splitStart = 0;
@@ -60,30 +65,32 @@ public class ArcRecordReader
protected long fileLen = 0;
protected FSDataInputStream in;
- private static byte[] MAGIC = {(byte)0x1F, (byte)0x8B};
+ private static byte[] MAGIC = { (byte) 0x1F, (byte) 0x8B };
/**
- * <p>Returns true if the byte array passed matches the gzip header magic
- * number.</p>
+ * <p>
+ * Returns true if the byte array passed matches the gzip header magic number.
+ * </p>
*
- * @param input The byte array to check.
+ * @param input
+ * The byte array to check.
*
* @return True if the byte array matches the gzip header magic number.
*/
public static boolean isMagic(byte[] input) {
- // check for null and incorrect length
+ // check for null and incorrect length
if (input == null || input.length != MAGIC.length) {
return false;
}
-
+
// check byte by byte
for (int i = 0; i < MAGIC.length; i++) {
if (MAGIC[i] != input[i]) {
return false;
}
}
-
+
// must match
return true;
}
@@ -91,13 +98,16 @@ public class ArcRecordReader
/**
* Constructor that sets the configuration and file split.
*
- * @param conf The job configuration.
- * @param split The file split to read from.
+ * @param conf
+ * The job configuration.
+ * @param split
+ * The file split to read from.
*
- * @throws IOException If an IO error occurs while initializing file split.
+ * @throws IOException
+ * If an IO error occurs while initializing file split.
*/
public ArcRecordReader(Configuration conf, FileSplit split)
- throws IOException {
+ throws IOException {
Path path = split.getPath();
FileSystem fs = path.getFileSystem(conf);
@@ -113,8 +123,7 @@ public class ArcRecordReader
/**
* Closes the record reader resources.
*/
- public void close()
- throws IOException {
+ public void close() throws IOException {
this.in.close();
}
@@ -137,63 +146,64 @@ public class ArcRecordReader
*
* @return The long of the current position in the file.
*/
- public long getPos()
- throws IOException {
+ public long getPos() throws IOException {
return in.getPos();
}
/**
- * Returns the percentage of progress in processing the file. This will be
+ * Returns the percentage of progress in processing the file. This will be
* represented as a float from 0 to 1 with 1 being 100% completed.
*
* @return The percentage of progress as a float from 0 to 1.
*/
- public float getProgress()
- throws IOException {
-
+ public float getProgress() throws IOException {
+
// if we haven't even started
if (splitEnd == splitStart) {
return 0.0f;
- }
- else {
- // the progress is current pos - where we started / length of the split
- return Math.min(1.0f, (getPos() - splitStart) / (float)splitLen);
+ } else {
+ // the progress is current pos - where we started / length of the split
+ return Math.min(1.0f, (getPos() - splitStart) / (float) splitLen);
}
}
/**
- * <p>Returns true if the next record in the split is read into the key and
- * value pair. The key will be the arc record header and the values will be
- * the raw content bytes of the arc record.</p>
+ * <p>
+ * Returns true if the next record in the split is read into the key and value
+ * pair. The key will be the arc record header and the values will be the raw
+ * content bytes of the arc record.
+ * </p>
*
- * @param key The record key
- * @param value The record value
+ * @param key
+ * The record key
+ * @param value
+ * The record value
*
* @return True if the next record is read.
*
- * @throws IOException If an error occurs while reading the record value.
+ * @throws IOException
+ * If an error occurs while reading the record value.
*/
- public boolean next(Text key, BytesWritable value)
- throws IOException {
+ public boolean next(Text key, BytesWritable value) throws IOException {
try {
-
+
// get the starting position on the input stream
long startRead = in.getPos();
byte[] magicBuffer = null;
-
+
// we need this loop to handle false positives in reading of gzip records
while (true) {
-
+
// while we haven't passed the end of the split
if (startRead >= splitEnd) {
return false;
}
-
+
// scanning for the gzip header
boolean foundStart = false;
while (!foundStart) {
-
+
// start at the current file position and scan for 1K at time, break
// if there is no more to read
startRead = in.getPos();
@@ -202,13 +212,13 @@ public class ArcRecordReader
if (read < 0) {
break;
}
-
- // scan the byte array for the gzip header magic number. This happens
+
+ // scan the byte array for the gzip header magic number. This happens
// byte by byte
for (int i = 0; i < read - 1; i++) {
byte[] testMagic = new byte[2];
- System.arraycopy(magicBuffer, i, testMagic, 0, 2);
- if (isMagic(testMagic)) {
+ System.arraycopy(magicBuffer, i, testMagic, 0, 2);
+ if (isMagic(testMagic)) {
// set the next start to the current gzip header
startRead += i;
foundStart = true;
@@ -216,14 +226,14 @@ public class ArcRecordReader
}
}
}
-
+
// seek to the start of the gzip header
in.seek(startRead);
ByteArrayOutputStream baos = null;
int totalRead = 0;
try {
-
+
// read 4K of the gzip at a time putting into a byte array
byte[] buffer = new byte[4096];
GZIPInputStream zin = new GZIPInputStream(in);
@@ -233,9 +243,8 @@ public class ArcRecordReader
baos.write(buffer, 0, gzipRead);
totalRead += gzipRead;
}
- }
- catch (Exception e) {
-
+ } catch (Exception e) {
+
// there are times we get false positives where the gzip header exists
// but it is not an actual gzip record, so we ignore it and start
// over seeking
@@ -248,7 +257,7 @@ public class ArcRecordReader
// change the output stream to a byte array
byte[] content = baos.toByteArray();
-
+
// the first line of the raw content in arc files is the header
int eol = 0;
for (int i = 0; i < content.length; i++) {
@@ -257,34 +266,33 @@ public class ArcRecordReader
break;
}
}
-
+
// create the header and the raw content minus the header
String header = new String(content, 0, eol).trim();
byte[] raw = new byte[(content.length - eol) - 1];
System.arraycopy(content, eol + 1, raw, 0, raw.length);
-
+
// populate key and values with the header and raw content.
Text keyText = key;
keyText.set(header);
BytesWritable valueBytes = value;
valueBytes.set(raw, 0, raw.length);
- // TODO: It would be best to start at the end of the gzip read but
- // the bytes read in gzip don't match raw bytes in the file so we
- // overshoot the next header. With this current method you get
+ // TODO: It would be best to start at the end of the gzip read but
+ // the bytes read in gzip don't match raw bytes in the file so we
+ // overshoot the next header. With this current method you get
// some false positives but don't miss records.
if (startRead + 1 < fileLen) {
in.seek(startRead + 1);
}
-
+
// populated the record, now return
return true;
}
+ } catch (Exception e) {
+ LOG.equals(StringUtils.stringifyException(e));
}
- catch (Exception e) {
- LOG.equals(StringUtils.stringifyException(e));
- }
-
+
// couldn't populate the record or there is no next record to read
return false;
}
diff --git a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
index e2300f53a..39b8d95db 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
@@ -61,18 +61,22 @@ import org.apache.nutch.util.StringUtil;
import org.apache.nutch.util.TimingUtil;
/**
- * <p>The <code>ArcSegmentCreator</code> is a replacement for fetcher that will
- * take arc files as input and produce a nutch segment as output.</p>
+ * <p>
+ * The <code>ArcSegmentCreator</code> is a replacement for fetcher that will
+ * take arc files as input and produce a nutch segment as output.
+ * </p>
*
- * <p>Arc files are tars of compressed gzips which are produced by both the
- * internet archive project and the grub distributed crawler project.</p>
+ * <p>
+ * Arc files are tars of compressed gzips which are produced by both the
+ * internet archive project and the grub distributed crawler project.
+ * </p>
*
*/
-public class ArcSegmentCreator
- extends Configured
- implements Tool, Mapper<Text, BytesWritable, Text, NutchWritable> {
+public class ArcSegmentCreator extends Configured implements Tool,
+ Mapper<Text, BytesWritable, Text, NutchWritable> {
- public static final Logger LOG = LoggerFactory.getLogger(ArcSegmentCreator.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(ArcSegmentCreator.class);
public static final String URL_VERSION = "arc.url.version";
private JobConf jobConf;
private URLFilters urlFilters;
@@ -88,7 +92,9 @@ public class ArcSegmentCreator
}
/**
- * <p>Constructor that sets the job configuration.</p>
+ * <p>
+ * Constructor that sets the job configuration.
+ * </p>
*
* @param conf
*/
@@ -104,17 +110,19 @@ public class ArcSegmentCreator
public static synchronized String generateSegmentName() {
try {
Thread.sleep(1000);
- }
- catch (Throwable t) {
+ } catch (Throwable t) {
}
return sdf.format(new Date(System.currentTimeMillis()));
}
/**
- * <p>Configures the job. Sets the url filters, scoring filters, url normalizers
- * and other relevant data.</p>
+ * <p>
+ * Configures the job. Sets the url filters, scoring filters, url normalizers
+ * and other relevant data.
+ * </p>
*
- * @param job The job configuration.
+ * @param job
+ * The job configuration.
*/
public void configure(JobConf job) {
@@ -132,23 +140,31 @@ public class ArcSegmentCreator
}
/**
- * <p>Parses the raw content of a single record to create output. This method
- * is almost the same as the {@link org.apache.nutch.Fetcher#output} method in
- * terms of processing and output.
+ * <p>
+ * Parses the raw content of a single record to create output. This method is
+ * almost the same as the {@link org.apache.nutch.Fetcher#output} method in
+ * terms of processing and output.
*
- * @param output The job output collector.
- * @param segmentName The name of the segment to create.
- * @param key The url of the record.
- * @param datum The CrawlDatum of the record.
- * @param content The raw content of the record
- * @param pstatus The protocol status
- * @param status The fetch status.
+ * @param output
+ * The job output collector.
+ * @param segmentName
+ * The name of the segment to create.
+ * @param key
+ * The url of the record.
+ * @param datum
+ * The CrawlDatum of the record.
+ * @param content
+ * The raw content of the record
+ * @param pstatus
+ * The protocol status
+ * @param status
+ * The fetch status.
*
* @return The result of the parse in a ParseStatus object.
*/
- private ParseStatus output(OutputCollector<Text, NutchWritable> output, String segmentName,
- Text key, CrawlDatum datum, Content content, ProtocolStatus pstatus,
- int status) {
+ private ParseStatus output(OutputCollector<Text, NutchWritable> output,
+ String segmentName, Text key, CrawlDatum datum, Content content,
+ ProtocolStatus pstatus, int status) {
// set the fetch status and the fetch time
datum.setStatus(status);
@@ -164,8 +180,7 @@ public class ArcSegmentCreator
// add score to content metadata so that ParseSegment can pick it up.
try {
scfilters.passScoreBeforeParsing(key, datum, content);
- }
- catch (Exception e) {
+ } catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
}
@@ -175,16 +190,15 @@ public class ArcSegmentCreator
// parse the content
parseResult = this.parseUtil.parse(content);
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.warn("Error parsing: " + key + ": "
- + StringUtils.stringifyException(e));
+ + StringUtils.stringifyException(e));
}
// set the content signature
if (parseResult == null) {
byte[] signature = SignatureFactory.getSignature(getConf()).calculate(
- content, new ParseStatus().getEmptyParse(getConf()));
+ content, new ParseStatus().getEmptyParse(getConf()));
datum.setSignature(signature);
}
@@ -193,7 +207,7 @@ public class ArcSegmentCreator
output.collect(key, new NutchWritable(content));
if (parseResult != null) {
- for (Entry <Text, Parse> entry : parseResult) {
+ for (Entry<Text, Parse> entry : parseResult) {
Text url = entry.getKey();
Parse parse = entry.getValue();
ParseStatus parseStatus = parse.getData().getStatus();
@@ -203,35 +217,34 @@ public class ArcSegmentCreator
parse = parseStatus.getEmptyParse(getConf());
}
- // Calculate page signature.
- byte[] signature = SignatureFactory.getSignature(getConf()).calculate(
- content, parse);
+ // Calculate page signature.
+ byte[] signature = SignatureFactory.getSignature(getConf())
+ .calculate(content, parse);
// Ensure segment name and score are in parseData metadata
- parse.getData().getContentMeta().set(Nutch.SEGMENT_NAME_KEY,
- segmentName);
- parse.getData().getContentMeta().set(Nutch.SIGNATURE_KEY,
- StringUtil.toHexString(signature));
+ parse.getData().getContentMeta()
+ .set(Nutch.SEGMENT_NAME_KEY, segmentName);
+ parse.getData().getContentMeta()
+ .set(Nutch.SIGNATURE_KEY, StringUtil.toHexString(signature));
// Pass fetch time to content meta
- parse.getData().getContentMeta().set(Nutch.FETCH_TIME_KEY,
- Long.toString(datum.getFetchTime()));
+ parse.getData().getContentMeta()
+ .set(Nutch.FETCH_TIME_KEY, Long.toString(datum.getFetchTime()));
if (url.equals(key))
datum.setSignature(signature);
try {
scfilters.passScoreAfterParsing(url, content, parse);
- }
- catch (Exception e) {
+ } catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
}
}
output.collect(url, new NutchWritable(new ParseImpl(new ParseText(
- parse.getText()), parse.getData(), parse.isCanonical())));
+ parse.getText()), parse.getData(), parse.isCanonical())));
}
}
- }
- catch (IOException e) {
+ } catch (IOException e) {
if (LOG.isErrorEnabled()) {
- LOG.error("ArcSegmentCreator caught:" + StringUtils.stringifyException(e));
+ LOG.error("ArcSegmentCreator caught:"
+ + StringUtils.stringifyException(e));
}
}
@@ -243,42 +256,51 @@ public class ArcSegmentCreator
}
}
}
-
+
return null;
}
/**
- * <p>Logs any error that occurs during conversion.</p>
+ * <p>
+ * Logs any error that occurs during conversion.
+ * </p>
*
- * @param url The url we are parsing.
- * @param t The error that occured.
+ * @param url
+ * The url we are parsing.
+ * @param t
+ * The error that occured.
*/
private void logError(Text url, Throwable t) {
if (LOG.isInfoEnabled()) {
- LOG.info("Conversion of " + url + " failed with: " +
- StringUtils.stringifyException(t));
+ LOG.info("Conversion of " + url + " failed with: "
+ + StringUtils.stringifyException(t));
}
}
/**
- * <p>Runs the Map job to translate an arc record into output for Nutch
- * segments.</p>
+ * <p>
+ * Runs the Map job to translate an arc record into output for Nutch segments.
+ * </p>
*
- * @param key The arc record header.
- * @param bytes The arc record raw content bytes.
- * @param output The output collecter.
- * @param reporter The progress reporter.
+ * @param key
+ * The arc record header.
+ * @param bytes
+ * The arc record raw content bytes.
+ * @param output
+ * The output collecter.
+ * @param reporter
+ * The progress reporter.
*/
public void map(Text key, BytesWritable bytes,
- OutputCollector<Text, NutchWritable> output, Reporter reporter)
- throws IOException {
+ OutputCollector<Text, NutchWritable> output, Reporter reporter)
+ throws IOException {
String[] headers = key.toString().split("\\s+");
String urlStr = headers[0];
String version = headers[2];
String contentType = headers[3];
-
- // arcs start with a file description. for now we ignore this as it is not
+
+ // arcs start with a file description. for now we ignore this as it is not
// a content record
if (urlStr.startsWith("filedesc://")) {
LOG.info("Ignoring file header: " + urlStr);
@@ -286,18 +308,17 @@ public class ArcSegmentCreator
}
LOG.info("Processing: " + urlStr);
- // get the raw bytes from the arc file, create a new crawldatum
+ // get the raw bytes from the arc file, create a new crawldatum
Text url = new Text();
CrawlDatum datum = new CrawlDatum(CrawlDatum.STATUS_DB_FETCHED, interval,
- 1.0f);
+ 1.0f);
String segmentName = getConf().get(Nutch.SEGMENT_NAME_KEY);
// normalize and filter the urls
try {
urlStr = normalizers.normalize(urlStr, URLNormalizers.SCOPE_FETCHER);
urlStr = urlFilters.filter(urlStr); // filter the url
- }
- catch (Exception e) {
+ } catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Skipping " + url + ":" + e);
}
@@ -312,37 +333,41 @@ public class ArcSegmentCreator
// set the protocol status to success and the crawl status to success
// create the content from the normalized url and the raw bytes from
- // the arc file, TODO: currently this doesn't handle text of errors
+ // the arc file, TODO: currently this doesn't handle text of errors
// pages (i.e. 404, etc.). We assume we won't get those.
ProtocolStatus status = ProtocolStatus.STATUS_SUCCESS;
- Content content = new Content(urlStr, urlStr, bytes.getBytes(), contentType,
- new Metadata(), getConf());
-
+ Content content = new Content(urlStr, urlStr, bytes.getBytes(),
+ contentType, new Metadata(), getConf());
+
// set the url version into the metadata
content.getMetadata().set(URL_VERSION, version);
ParseStatus pstatus = null;
pstatus = output(output, segmentName, url, datum, content, status,
- CrawlDatum.STATUS_FETCH_SUCCESS);
+ CrawlDatum.STATUS_FETCH_SUCCESS);
reporter.progress();
- }
- catch (Throwable t) { // unexpected exception
+ } catch (Throwable t) { // unexpected exception
logError(url, t);
output(output, segmentName, url, datum, null, null,
- CrawlDatum.STATUS_FETCH_RETRY);
+ CrawlDatum.STATUS_FETCH_RETRY);
}
}
}
/**
- * <p>Creates the arc files to segments job.</p>
+ * <p>
+ * Creates the arc files to segments job.
+ * </p>
*
- * @param arcFiles The path to the directory holding the arc files
- * @param segmentsOutDir The output directory for writing the segments
+ * @param arcFiles
+ * The path to the directory holding the arc files
+ * @param segmentsOutDir
+ * The output directory for writing the segments
*
- * @throws IOException If an IO error occurs while running the job.
+ * @throws IOException
+ * If an IO error occurs while running the job.
*/
public void createSegments(Path arcFiles, Path segmentsOutDir)
- throws IOException {
+ throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -366,17 +391,17 @@ public class ArcSegmentCreator
JobClient.runJob(job);
long end = System.currentTimeMillis();
- LOG.info("ArcSegmentCreator: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("ArcSegmentCreator: finished at " + sdf.format(end)
+ + ", elapsed: " + TimingUtil.elapsedTime(start, end));
}
- public static void main(String args[])
- throws Exception {
- int res = ToolRunner.run(NutchConfiguration.create(), new ArcSegmentCreator(), args);
+ public static void main(String args[]) throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(),
+ new ArcSegmentCreator(), args);
System.exit(res);
}
- public int run(String[] args)
- throws Exception {
+ public int run(String[] args) throws Exception {
String usage = "Usage: ArcSegmentCreator <arcFiles> <segmentsOutDir>";
@@ -393,8 +418,7 @@ public class ArcSegmentCreator
// create the segments from the arc files
createSegments(arcFiles, segmentsOutDir);
return 0;
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOG.error("ArcSegmentCreator: " + StringUtils.stringifyException(e));
return -1;
}
diff --git a/src/java/org/apache/nutch/tools/arc/package-info.java b/src/java/org/apache/nutch/tools/arc/package-info.java
index f069594ae..cb6e115f5 100644
--- a/src/java/org/apache/nutch/tools/arc/package-info.java
+++ b/src/java/org/apache/nutch/tools/arc/package-info.java
@@ -20,3 +20,4 @@
* <a href="http://archive.org/web/researcher/ArcFileFormat.php">Arc file format</a>.
*/
package org.apache.nutch.tools.arc;
+
diff --git a/src/java/org/apache/nutch/tools/package-info.java b/src/java/org/apache/nutch/tools/package-info.java
index 5d2b211c3..3b868c587 100644
--- a/src/java/org/apache/nutch/tools/package-info.java
+++ b/src/java/org/apache/nutch/tools/package-info.java
@@ -19,3 +19,4 @@
* Miscellaneous tools.
*/
package org.apache.nutch.tools;
+
diff --git a/src/java/org/apache/nutch/util/CommandRunner.java b/src/java/org/apache/nutch/util/CommandRunner.java
index 21d699ad7..593d590fb 100644
--- a/src/java/org/apache/nutch/util/CommandRunner.java
+++ b/src/java/org/apache/nutch/util/CommandRunner.java
@@ -82,11 +82,11 @@ public class CommandRunner {
}
public void evaluate() throws IOException {
- this.exec();
+ this.exec();
}
/**
- *
+ *
* @return process exit value (return code) or -1 if timed out.
* @throws IOException
*/
@@ -94,13 +94,11 @@ public class CommandRunner {
Process proc = Runtime.getRuntime().exec(_command);
_barrier = new CyclicBarrier(3 + ((_stdin != null) ? 1 : 0));
- PullerThread so =
- new PullerThread("STDOUT", proc.getInputStream(), _stdout);
+ PullerThread so = new PullerThread("STDOUT", proc.getInputStream(), _stdout);
so.setDaemon(true);
so.start();
- PullerThread se =
- new PullerThread("STDERR", proc.getErrorStream(), _stderr);
+ PullerThread se = new PullerThread("STDERR", proc.getErrorStream(), _stderr);
se.setDaemon(true);
se.start();
@@ -145,11 +143,11 @@ public class CommandRunner {
Thread.sleep(1000);
_xit = proc.exitValue();
} catch (InterruptedException ie) {
- if (Thread.interrupted()) {
- break; // stop waiting on an interrupt for this thread
- } else {
- continue;
- }
+ if (Thread.interrupted()) {
+ break; // stop waiting on an interrupt for this thread
+ } else {
+ continue;
+ }
} catch (IllegalThreadStateException iltse) {
continue;
}
@@ -181,11 +179,8 @@ public class CommandRunner {
private boolean _closeInput;
- protected PumperThread(
- String name,
- InputStream is,
- OutputStream os,
- boolean closeInput) {
+ protected PumperThread(String name, InputStream is, OutputStream os,
+ boolean closeInput) {
super(name);
_is = is;
_os = os;
@@ -218,12 +213,12 @@ public class CommandRunner {
}
}
try {
- _barrier.await();
- } catch (InterruptedException ie) {
- /* IGNORE */
- } catch (BrokenBarrierException bbe) {
- /* IGNORE */
- }
+ _barrier.await();
+ } catch (InterruptedException ie) {
+ /* IGNORE */
+ } catch (BrokenBarrierException bbe) {
+ /* IGNORE */
+ }
}
}
@@ -269,8 +264,9 @@ public class CommandRunner {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-timeout")) {
- timeout = Integer.parseInt(args[++i]);;
- } else if (i != args.length-2) {
+ timeout = Integer.parseInt(args[++i]);
+ ;
+ } else if (i != args.length - 2) {
System.err.println(usage);
System.exit(-1);
} else {
@@ -290,6 +286,6 @@ public class CommandRunner {
cr.evaluate();
- System.err.println("output value: "+cr.getExitValue());
+ System.err.println("output value: " + cr.getExitValue());
}
}
diff --git a/src/java/org/apache/nutch/util/DeflateUtils.java b/src/java/org/apache/nutch/util/DeflateUtils.java
index 940ca896f..58635228d 100644
--- a/src/java/org/apache/nutch/util/DeflateUtils.java
+++ b/src/java/org/apache/nutch/util/DeflateUtils.java
@@ -28,19 +28,18 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * A collection of utility methods for working on deflated data.
+ * A collection of utility methods for working on deflated data.
*/
public class DeflateUtils {
-
+
private static final Logger LOG = LoggerFactory.getLogger(DeflateUtils.class);
private static final int EXPECTED_COMPRESSION_RATIO = 5;
private static final int BUF_SIZE = 4096;
/**
- * Returns an inflated copy of the input array. If the deflated
- * input has been truncated or corrupted, a best-effort attempt is
- * made to inflate as much as possible. If no data can be extracted
- * <code>null</code> is returned.
+ * Returns an inflated copy of the input array. If the deflated input has been
+ * truncated or corrupted, a best-effort attempt is made to inflate as much as
+ * possible. If no data can be extracted <code>null</code> is returned.
*/
public static final byte[] inflateBestEffort(byte[] in) {
return inflateBestEffort(in, Integer.MAX_VALUE);
@@ -48,37 +47,36 @@ public class DeflateUtils {
/**
* Returns an inflated copy of the input array, truncated to
- * <code>sizeLimit</code> bytes, if necessary. If the deflated input
- * has been truncated or corrupted, a best-effort attempt is made to
- * inflate as much as possible. If no data can be extracted
- * <code>null</code> is returned.
+ * <code>sizeLimit</code> bytes, if necessary. If the deflated input has been
+ * truncated or corrupted, a best-effort attempt is made to inflate as much as
+ * possible. If no data can be extracted <code>null</code> is returned.
*/
public static final byte[] inflateBestEffort(byte[] in, int sizeLimit) {
- // decompress using InflaterInputStream
- ByteArrayOutputStream outStream =
- new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
+ // decompress using InflaterInputStream
+ ByteArrayOutputStream outStream = new ByteArrayOutputStream(
+ EXPECTED_COMPRESSION_RATIO * in.length);
// "true" because HTTP does not provide zlib headers
Inflater inflater = new Inflater(true);
- InflaterInputStream inStream =
- new InflaterInputStream(new ByteArrayInputStream(in), inflater);
+ InflaterInputStream inStream = new InflaterInputStream(
+ new ByteArrayInputStream(in), inflater);
byte[] buf = new byte[BUF_SIZE];
int written = 0;
while (true) {
try {
- int size = inStream.read(buf);
- if (size <= 0)
- break;
- if ((written + size) > sizeLimit) {
- outStream.write(buf, 0, sizeLimit - written);
- break;
- }
- outStream.write(buf, 0, size);
- written+= size;
+ int size = inStream.read(buf);
+ if (size <= 0)
+ break;
+ if ((written + size) > sizeLimit) {
+ outStream.write(buf, 0, sizeLimit - written);
+ break;
+ }
+ outStream.write(buf, 0, size);
+ written += size;
} catch (Exception e) {
- LOG.info( "Caught Exception in inflateBestEffort", e );
- break;
+ LOG.info("Caught Exception in inflateBestEffort", e);
+ break;
}
}
try {
@@ -89,23 +87,24 @@ public class DeflateUtils {
return outStream.toByteArray();
}
-
/**
- * Returns an inflated copy of the input array.
- * @throws IOException if the input cannot be properly decompressed
+ * Returns an inflated copy of the input array.
+ *
+ * @throws IOException
+ * if the input cannot be properly decompressed
*/
public static final byte[] inflate(byte[] in) throws IOException {
- // decompress using InflaterInputStream
- ByteArrayOutputStream outStream =
- new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
+ // decompress using InflaterInputStream
+ ByteArrayOutputStream outStream = new ByteArrayOutputStream(
+ EXPECTED_COMPRESSION_RATIO * in.length);
- InflaterInputStream inStream =
- new InflaterInputStream ( new ByteArrayInputStream(in) );
+ InflaterInputStream inStream = new InflaterInputStream(
+ new ByteArrayInputStream(in));
byte[] buf = new byte[BUF_SIZE];
while (true) {
int size = inStream.read(buf);
- if (size <= 0)
+ if (size <= 0)
break;
outStream.write(buf, 0, size);
}
@@ -118,9 +117,9 @@ public class DeflateUtils {
* Returns a deflated copy of the input array.
*/
public static final byte[] deflate(byte[] in) {
- // compress using DeflaterOutputStream
- ByteArrayOutputStream byteOut =
- new ByteArrayOutputStream(in.length / EXPECTED_COMPRESSION_RATIO);
+ // compress using DeflaterOutputStream
+ ByteArrayOutputStream byteOut = new ByteArrayOutputStream(in.length
+ / EXPECTED_COMPRESSION_RATIO);
DeflaterOutputStream outStream = new DeflaterOutputStream(byteOut);
diff --git a/src/java/org/apache/nutch/util/DomUtil.java b/src/java/org/apache/nutch/util/DomUtil.java
index 4beb92e2f..9595bf4ed 100644
--- a/src/java/org/apache/nutch/util/DomUtil.java
+++ b/src/java/org/apache/nutch/util/DomUtil.java
@@ -38,7 +38,6 @@ import org.xml.sax.SAXException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public class DomUtil {
private final static Logger LOG = LoggerFactory.getLogger(DomUtil.class);
@@ -61,10 +60,10 @@ public class DomUtil {
input.setEncoding("UTF-8");
parser.parse(input);
int i = 0;
- while (! (parser.getDocument().getChildNodes().item(i) instanceof Element)) {
- i++;
- }
- element = (Element)parser.getDocument().getChildNodes().item(i);
+ while (!(parser.getDocument().getChildNodes().item(i) instanceof Element)) {
+ i++;
+ }
+ element = (Element) parser.getDocument().getChildNodes().item(i);
} catch (FileNotFoundException e) {
LOG.error("Error: ", e);
} catch (SAXException e) {
diff --git a/src/java/org/apache/nutch/util/EncodingDetector.java b/src/java/org/apache/nutch/util/EncodingDetector.java
index 6a3a9fdf4..4e62dd335 100644
--- a/src/java/org/apache/nutch/util/EncodingDetector.java
+++ b/src/java/org/apache/nutch/util/EncodingDetector.java
@@ -39,27 +39,26 @@ import com.ibm.icu.text.CharsetMatch;
/**
* A simple class for detecting character encodings.
- *
+ *
* <p>
* Broadly this encompasses two functions, which are distinctly separate:
- *
+ *
* <ol>
- * <li>Auto detecting a set of "clues" from input text.</li>
- * <li>Taking a set of clues and making a "best guess" as to the
- * "real" encoding.</li>
+ * <li>Auto detecting a set of "clues" from input text.</li>
+ * <li>Taking a set of clues and making a "best guess" as to the "real"
+ * encoding.</li>
* </ol>
* </p>
- *
+ *
* <p>
- * A caller will often have some extra information about what the
- * encoding might be (e.g. from the HTTP header or HTML meta-tags, often
- * wrong but still potentially useful clues). The types of clues may differ
- * from caller to caller. Thus a typical calling sequence is:
+ * A caller will often have some extra information about what the encoding might
+ * be (e.g. from the HTTP header or HTML meta-tags, often wrong but still
+ * potentially useful clues). The types of clues may differ from caller to
+ * caller. Thus a typical calling sequence is:
* <ul>
- * <li>Run step (1) to generate a set of auto-detected clues;</li>
- * <li>Combine these clues with the caller-dependent "extra clues"
- * available;</li>
- * <li>Run step (2) to guess what the most probable answer is.</li>
+ * <li>Run step (1) to generate a set of auto-detected clues;</li>
+ * <li>Combine these clues with the caller-dependent "extra clues" available;</li>
+ * <li>Run step (2) to guess what the most probable answer is.</li>
* </p>
*/
public class EncodingDetector {
@@ -89,34 +88,32 @@ public class EncodingDetector {
}
public String toString() {
- return value + " (" + source +
- ((confidence >= 0) ? ", " + confidence + "% confidence" : "") + ")";
+ return value + " (" + source
+ + ((confidence >= 0) ? ", " + confidence + "% confidence" : "") + ")";
}
public boolean isEmpty() {
- return (value==null || "".equals(value));
+ return (value == null || "".equals(value));
}
public boolean meetsThreshold() {
- return (confidence < 0 ||
- (minConfidence >= 0 && confidence >= minConfidence));
+ return (confidence < 0 || (minConfidence >= 0 && confidence >= minConfidence));
}
}
- public static final Logger LOG = LoggerFactory.getLogger(EncodingDetector.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(EncodingDetector.class);
public static final int NO_THRESHOLD = -1;
- public static final String MIN_CONFIDENCE_KEY =
- "encodingdetector.charset.min.confidence";
+ public static final String MIN_CONFIDENCE_KEY = "encodingdetector.charset.min.confidence";
- private static final HashMap<String, String> ALIASES =
- new HashMap<String, String>();
+ private static final HashMap<String, String> ALIASES = new HashMap<String, String>();
private static final HashSet<String> DETECTABLES = new HashSet<String>();
// CharsetDetector will die without a minimum amount of data.
- private static final int MIN_LENGTH=4;
+ private static final int MIN_LENGTH = 4;
static {
DETECTABLES.add("text/html");
@@ -129,23 +126,22 @@ public class EncodingDetector {
DETECTABLES.add("application/rss+xml");
DETECTABLES.add("application/xhtml+xml");
/*
- * the following map is not an alias mapping table, but
- * maps character encodings which are often used in mislabelled
- * documents to their correct encodings. For instance,
- * there are a lot of documents labelled 'ISO-8859-1' which contain
- * characters not covered by ISO-8859-1 but covered by windows-1252.
- * Because windows-1252 is a superset of ISO-8859-1 (sharing code points
- * for the common part), it's better to treat ISO-8859-1 as
- * synonymous with windows-1252 than to reject, as invalid, documents
- * labelled as ISO-8859-1 that have characters outside ISO-8859-1.
+ * the following map is not an alias mapping table, but maps character
+ * encodings which are often used in mislabelled documents to their correct
+ * encodings. For instance, there are a lot of documents labelled
+ * 'ISO-8859-1' which contain characters not covered by ISO-8859-1 but
+ * covered by windows-1252. Because windows-1252 is a superset of ISO-8859-1
+ * (sharing code points for the common part), it's better to treat
+ * ISO-8859-1 as synonymous with windows-1252 than to reject, as invalid,
+ * documents labelled as ISO-8859-1 that have characters outside ISO-8859-1.
*/
ALIASES.put("ISO-8859-1", "windows-1252");
ALIASES.put("EUC-KR", "x-windows-949");
ALIASES.put("x-EUC-CN", "GB18030");
ALIASES.put("GBK", "GB18030");
- //ALIASES.put("Big5", "Big5HKSCS");
- //ALIASES.put("TIS620", "Cp874");
- //ALIASES.put("ISO-8859-11", "Cp874");
+ // ALIASES.put("Big5", "Big5HKSCS");
+ // ALIASES.put("TIS620", "Cp874");
+ // ALIASES.put("ISO-8859-11", "Cp874");
}
@@ -188,8 +184,9 @@ public class EncodingDetector {
}
// add character encoding coming from HTTP response header
- addClue(parseCharacterEncoding(
- content.getMetadata().get(Response.CONTENT_TYPE)), "header");
+ addClue(
+ parseCharacterEncoding(content.getMetadata().get(Response.CONTENT_TYPE)),
+ "header");
}
public void addClue(String value, String source, int confidence) {
@@ -208,21 +205,23 @@ public class EncodingDetector {
/**
* Guess the encoding with the previously specified list of clues.
- *
- * @param content Content instance
- * @param defaultValue Default encoding to return if no encoding can be
- * detected with enough confidence. Note that this will <b>not</b> be
- * normalized with {@link EncodingDetector#resolveEncodingAlias}
- *
+ *
+ * @param content
+ * Content instance
+ * @param defaultValue
+ * Default encoding to return if no encoding can be detected with
+ * enough confidence. Note that this will <b>not</b> be normalized
+ * with {@link EncodingDetector#resolveEncodingAlias}
+ *
* @return Guessed encoding or defaultValue
*/
public String guessEncoding(Content content, String defaultValue) {
/*
- * This algorithm could be replaced by something more sophisticated;
- * ideally we would gather a bunch of data on where various clues
- * (autodetect, HTTP headers, HTML meta tags, etc.) disagree, tag each with
- * the correct answer, and use machine learning/some statistical method
- * to generate a better heuristic.
+ * This algorithm could be replaced by something more sophisticated; ideally
+ * we would gather a bunch of data on where various clues (autodetect, HTTP
+ * headers, HTML meta tags, etc.) disagree, tag each with the correct
+ * answer, and use machine learning/some statistical method to generate a
+ * better heuristic.
*/
String base = content.getBaseUrl();
@@ -232,10 +231,9 @@ public class EncodingDetector {
}
/*
- * Go down the list of encoding "clues". Use a clue if:
- * 1. Has a confidence value which meets our confidence threshold, OR
- * 2. Doesn't meet the threshold, but is the best try,
- * since nothing else is available.
+ * Go down the list of encoding "clues". Use a clue if: 1. Has a confidence
+ * value which meets our confidence threshold, OR 2. Doesn't meet the
+ * threshold, but is the best try, since nothing else is available.
*/
EncodingClue defaultClue = new EncodingClue(defaultValue, "default");
EncodingClue bestClue = defaultClue;
@@ -247,8 +245,8 @@ public class EncodingDetector {
String charset = clue.value;
if (minConfidence >= 0 && clue.confidence >= minConfidence) {
if (LOG.isTraceEnabled()) {
- LOG.trace(base + ": Choosing encoding: " + charset +
- " with confidence " + clue.confidence);
+ LOG.trace(base + ": Choosing encoding: " + charset
+ + " with confidence " + clue.confidence);
}
return resolveEncodingAlias(charset).toLowerCase();
} else if (clue.confidence == NO_THRESHOLD && bestClue == defaultClue) {
@@ -268,10 +266,10 @@ public class EncodingDetector {
}
/*
- * Strictly for analysis, look for "disagreements." The top guess from
- * each source is examined; if these meet the threshold and disagree, then
- * we log the information -- useful for testing or generating training data
- * for a better heuristic.
+ * Strictly for analysis, look for "disagreements." The top guess from each
+ * source is examined; if these meet the threshold and disagree, then we log
+ * the information -- useful for testing or generating training data for a
+ * better heuristic.
*/
private void findDisagreements(String url, List<EncodingClue> newClues) {
HashSet<String> valsSeen = new HashSet<String>();
@@ -293,9 +291,9 @@ public class EncodingDetector {
if (disagreement) {
// dump all values in case of disagreement
StringBuffer sb = new StringBuffer();
- sb.append("Disagreement: "+url+"; ");
+ sb.append("Disagreement: " + url + "; ");
for (int i = 0; i < newClues.size(); i++) {
- if (i>0) {
+ if (i > 0) {
sb.append(", ");
}
sb.append(newClues.get(i));
@@ -310,7 +308,7 @@ public class EncodingDetector {
return null;
String canonicalName = new String(Charset.forName(encoding).name());
return ALIASES.containsKey(canonicalName) ? ALIASES.get(canonicalName)
- : canonicalName;
+ : canonicalName;
} catch (Exception e) {
LOG.warn("Invalid encoding " + encoding + " detected, using default.");
return null;
@@ -318,14 +316,14 @@ public class EncodingDetector {
}
/**
- * Parse the character encoding from the specified content type header.
- * If the content type is null, or there is no explicit character encoding,
- * <code>null</code> is returned.
- * <br />
- * This method was copied from org.apache.catalina.util.RequestUtil,
- * which is licensed under the Apache License, Version 2.0 (the "License").
- *
- * @param contentType a content type header
+ * Parse the character encoding from the specified content type header. If the
+ * content type is null, or there is no explicit character encoding,
+ * <code>null</code> is returned. <br />
+ * This method was copied from org.apache.catalina.util.RequestUtil, which is
+ * licensed under the Apache License, Version 2.0 (the "License").
+ *
+ * @param contentType
+ * a content type header
*/
public static String parseCharacterEncoding(String contentType) {
if (contentType == null)
@@ -339,7 +337,7 @@ public class EncodingDetector {
encoding = encoding.substring(0, end);
encoding = encoding.trim();
if ((encoding.length() > 2) && (encoding.startsWith("\""))
- && (encoding.endsWith("\"")))
+ && (encoding.endsWith("\"")))
encoding = encoding.substring(1, encoding.length() - 1);
return (encoding.trim());
@@ -352,12 +350,12 @@ public class EncodingDetector {
}
Configuration conf = NutchConfiguration.create();
- EncodingDetector detector =
- new EncodingDetector(NutchConfiguration.create());
+ EncodingDetector detector = new EncodingDetector(
+ NutchConfiguration.create());
// do everything as bytes; don't want any conversion
- BufferedInputStream istr =
- new BufferedInputStream(new FileInputStream(args[0]));
+ BufferedInputStream istr = new BufferedInputStream(new FileInputStream(
+ args[0]));
ByteArrayOutputStream ostr = new ByteArrayOutputStream();
byte[] bytes = new byte[1000];
boolean more = true;
@@ -376,8 +374,8 @@ public class EncodingDetector {
byte[] data = ostr.toByteArray();
// make a fake Content
- Content content =
- new Content("", "", data, "text/html", new Metadata(), conf);
+ Content content = new Content("", "", data, "text/html", new Metadata(),
+ conf);
detector.autoDetectClues(content, true);
String encoding = detector.guessEncoding(content,
diff --git a/src/java/org/apache/nutch/util/FSUtils.java b/src/java/org/apache/nutch/util/FSUtils.java
index 2815665ce..6aed8d591 100644
--- a/src/java/org/apache/nutch/util/FSUtils.java
+++ b/src/java/org/apache/nutch/util/FSUtils.java
@@ -33,16 +33,20 @@ public class FSUtils {
* path. If removeOld is set to false then the old path will be set to the
* name current.old.
*
- * @param fs The FileSystem.
- * @param current The end path, the one being replaced.
- * @param replacement The path to replace with.
- * @param removeOld True if we are removing the current path.
+ * @param fs
+ * The FileSystem.
+ * @param current
+ * The end path, the one being replaced.
+ * @param replacement
+ * The path to replace with.
+ * @param removeOld
+ * True if we are removing the current path.
*
- * @throws IOException If an error occurs during replacement.
+ * @throws IOException
+ * If an error occurs during replacement.
*/
public static void replace(FileSystem fs, Path current, Path replacement,
- boolean removeOld)
- throws IOException {
+ boolean removeOld) throws IOException {
// rename any current path to old
Path old = new Path(current + ".old");
@@ -60,12 +64,14 @@ public class FSUtils {
/**
* Closes a group of SequenceFile readers.
*
- * @param readers The SequenceFile readers to close.
- * @throws IOException If an error occurs while closing a reader.
+ * @param readers
+ * The SequenceFile readers to close.
+ * @throws IOException
+ * If an error occurs while closing a reader.
*/
public static void closeReaders(SequenceFile.Reader[] readers)
- throws IOException {
-
+ throws IOException {
+
// loop through the readers, closing one by one
if (readers != null) {
for (int i = 0; i < readers.length; i++) {
@@ -80,12 +86,13 @@ public class FSUtils {
/**
* Closes a group of MapFile readers.
*
- * @param readers The MapFile readers to close.
- * @throws IOException If an error occurs while closing a reader.
+ * @param readers
+ * The MapFile readers to close.
+ * @throws IOException
+ * If an error occurs while closing a reader.
*/
- public static void closeReaders(MapFile.Reader[] readers)
- throws IOException {
-
+ public static void closeReaders(MapFile.Reader[] readers) throws IOException {
+
// loop through the readers closing one by one
if (readers != null) {
for (int i = 0; i < readers.length; i++) {
diff --git a/src/java/org/apache/nutch/util/GZIPUtils.java b/src/java/org/apache/nutch/util/GZIPUtils.java
index 2c1d56eba..63b10e2c4 100644
--- a/src/java/org/apache/nutch/util/GZIPUtils.java
+++ b/src/java/org/apache/nutch/util/GZIPUtils.java
@@ -28,19 +28,18 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * A collection of utility methods for working on GZIPed data.
+ * A collection of utility methods for working on GZIPed data.
*/
public class GZIPUtils {
-
+
private static final Logger LOG = LoggerFactory.getLogger(GZIPUtils.class);
- private static final int EXPECTED_COMPRESSION_RATIO= 5;
- private static final int BUF_SIZE= 4096;
+ private static final int EXPECTED_COMPRESSION_RATIO = 5;
+ private static final int BUF_SIZE = 4096;
/**
- * Returns an gunzipped copy of the input array. If the gzipped
- * input has been truncated or corrupted, a best-effort attempt is
- * made to unzip as much as possible. If no data can be extracted
- * <code>null</code> is returned.
+ * Returns an gunzipped copy of the input array. If the gzipped input has been
+ * truncated or corrupted, a best-effort attempt is made to unzip as much as
+ * possible. If no data can be extracted <code>null</code> is returned.
*/
public static final byte[] unzipBestEffort(byte[] in) {
return unzipBestEffort(in, Integer.MAX_VALUE);
@@ -48,33 +47,32 @@ public class GZIPUtils {
/**
* Returns an gunzipped copy of the input array, truncated to
- * <code>sizeLimit</code> bytes, if necessary. If the gzipped input
- * has been truncated or corrupted, a best-effort attempt is made to
- * unzip as much as possible. If no data can be extracted
- * <code>null</code> is returned.
+ * <code>sizeLimit</code> bytes, if necessary. If the gzipped input has been
+ * truncated or corrupted, a best-effort attempt is made to unzip as much as
+ * possible. If no data can be extracted <code>null</code> is returned.
*/
public static final byte[] unzipBestEffort(byte[] in, int sizeLimit) {
try {
- // decompress using GZIPInputStream
- ByteArrayOutputStream outStream =
- new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
+ // decompress using GZIPInputStream
+ ByteArrayOutputStream outStream = new ByteArrayOutputStream(
+ EXPECTED_COMPRESSION_RATIO * in.length);
- GZIPInputStream inStream =
- new GZIPInputStream ( new ByteArrayInputStream(in) );
+ GZIPInputStream inStream = new GZIPInputStream(new ByteArrayInputStream(
+ in));
byte[] buf = new byte[BUF_SIZE];
int written = 0;
while (true) {
try {
int size = inStream.read(buf);
- if (size <= 0)
+ if (size <= 0)
break;
if ((written + size) > sizeLimit) {
outStream.write(buf, 0, sizeLimit - written);
break;
}
outStream.write(buf, 0, size);
- written+= size;
+ written += size;
} catch (Exception e) {
break;
}
@@ -91,23 +89,23 @@ public class GZIPUtils {
}
}
-
/**
- * Returns an gunzipped copy of the input array.
- * @throws IOException if the input cannot be properly decompressed
+ * Returns an gunzipped copy of the input array.
+ *
+ * @throws IOException
+ * if the input cannot be properly decompressed
*/
public static final byte[] unzip(byte[] in) throws IOException {
- // decompress using GZIPInputStream
- ByteArrayOutputStream outStream =
- new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
+ // decompress using GZIPInputStream
+ ByteArrayOutputStream outStream = new ByteArrayOutputStream(
+ EXPECTED_COMPRESSION_RATIO * in.length);
- GZIPInputStream inStream =
- new GZIPInputStream ( new ByteArrayInputStream(in) );
+ GZIPInputStream inStream = new GZIPInputStream(new ByteArrayInputStream(in));
byte[] buf = new byte[BUF_SIZE];
while (true) {
int size = inStream.read(buf);
- if (size <= 0)
+ if (size <= 0)
break;
outStream.write(buf, 0, size);
}
@@ -121,11 +119,11 @@ public class GZIPUtils {
*/
public static final byte[] zip(byte[] in) {
try {
- // compress using GZIPOutputStream
- ByteArrayOutputStream byteOut=
- new ByteArrayOutputStream(in.length / EXPECTED_COMPRESSION_RATIO);
+ // compress using GZIPOutputStream
+ ByteArrayOutputStream byteOut = new ByteArrayOutputStream(in.length
+ / EXPECTED_COMPRESSION_RATIO);
- GZIPOutputStream outStream= new GZIPOutputStream(byteOut);
+ GZIPOutputStream outStream = new GZIPOutputStream(byteOut);
try {
outStream.write(in);
@@ -146,5 +144,5 @@ public class GZIPUtils {
return null;
}
}
-
+
}
diff --git a/src/java/org/apache/nutch/util/GenericWritableConfigurable.java b/src/java/org/apache/nutch/util/GenericWritableConfigurable.java
index 7f03115e9..755aad010 100644
--- a/src/java/org/apache/nutch/util/GenericWritableConfigurable.java
+++ b/src/java/org/apache/nutch/util/GenericWritableConfigurable.java
@@ -24,12 +24,15 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.GenericWritable;
import org.apache.hadoop.io.Writable;
-/** A generic Writable wrapper that can inject Configuration to {@link Configurable}s */
-public abstract class GenericWritableConfigurable extends GenericWritable
- implements Configurable {
+/**
+ * A generic Writable wrapper that can inject Configuration to
+ * {@link Configurable}s
+ */
+public abstract class GenericWritableConfigurable extends GenericWritable
+ implements Configurable {
private Configuration conf;
-
+
public Configuration getConf() {
return conf;
}
@@ -37,7 +40,7 @@ public abstract class GenericWritableConfigurable extends GenericWritable
public void setConf(Configuration conf) {
this.conf = conf;
}
-
+
@Override
public void readFields(DataInput in) throws IOException {
byte type = in.readByte();
@@ -50,8 +53,8 @@ public abstract class GenericWritableConfigurable extends GenericWritable
}
Writable w = get();
if (w instanceof Configurable)
- ((Configurable)w).setConf(conf);
+ ((Configurable) w).setConf(conf);
w.readFields(in);
}
-
+
}
diff --git a/src/java/org/apache/nutch/util/HadoopFSUtil.java b/src/java/org/apache/nutch/util/HadoopFSUtil.java
index 0d0143e90..92af7f7a0 100644
--- a/src/java/org/apache/nutch/util/HadoopFSUtil.java
+++ b/src/java/org/apache/nutch/util/HadoopFSUtil.java
@@ -25,48 +25,48 @@ import org.apache.hadoop.fs.PathFilter;
public class HadoopFSUtil {
- /**
- * Returns PathFilter that passes all paths through.
- */
- public static PathFilter getPassAllFilter() {
- return new PathFilter() {
- public boolean accept(Path arg0) {
- return true;
- }
- };
- }
+ /**
+ * Returns PathFilter that passes all paths through.
+ */
+ public static PathFilter getPassAllFilter() {
+ return new PathFilter() {
+ public boolean accept(Path arg0) {
+ return true;
+ }
+ };
+ }
+
+ /**
+ * Returns PathFilter that passes directories through.
+ */
+ public static PathFilter getPassDirectoriesFilter(final FileSystem fs) {
+ return new PathFilter() {
+ public boolean accept(final Path path) {
+ try {
+ return fs.getFileStatus(path).isDir();
+ } catch (IOException ioe) {
+ return false;
+ }
+ }
- /**
- * Returns PathFilter that passes directories through.
- */
- public static PathFilter getPassDirectoriesFilter(final FileSystem fs) {
- return new PathFilter() {
- public boolean accept(final Path path) {
- try {
- return fs.getFileStatus(path).isDir();
- } catch (IOException ioe) {
- return false;
- }
- }
+ };
+ }
- };
+ /**
+ * Turns an array of FileStatus into an array of Paths.
+ */
+ public static Path[] getPaths(FileStatus[] stats) {
+ if (stats == null) {
+ return null;
}
-
- /**
- * Turns an array of FileStatus into an array of Paths.
- */
- public static Path[] getPaths(FileStatus[] stats) {
- if (stats == null) {
- return null;
- }
- if (stats.length == 0) {
- return new Path[0];
- }
- Path[] res = new Path[stats.length];
- for (int i = 0; i < stats.length; i++) {
- res[i] = stats[i].getPath();
- }
- return res;
+ if (stats.length == 0) {
+ return new Path[0];
+ }
+ Path[] res = new Path[stats.length];
+ for (int i = 0; i < stats.length; i++) {
+ res[i] = stats[i].getPath();
}
+ return res;
+ }
}
diff --git a/src/java/org/apache/nutch/util/LockUtil.java b/src/java/org/apache/nutch/util/LockUtil.java
index 47ed0191a..053f694ce 100644
--- a/src/java/org/apache/nutch/util/LockUtil.java
+++ b/src/java/org/apache/nutch/util/LockUtil.java
@@ -28,22 +28,29 @@ import org.apache.hadoop.fs.Path;
* @author Andrzej Bialecki
*/
public class LockUtil {
-
+
/**
* Create a lock file.
- * @param fs filesystem
- * @param lockFile name of the lock file
- * @param accept if true, and the target file exists, consider it valid. If false
- * and the target file exists, throw an IOException.
- * @throws IOException if accept is false, and the target file already exists,
- * or if it's a directory.
+ *
+ * @param fs
+ * filesystem
+ * @param lockFile
+ * name of the lock file
+ * @param accept
+ * if true, and the target file exists, consider it valid. If false
+ * and the target file exists, throw an IOException.
+ * @throws IOException
+ * if accept is false, and the target file already exists, or if
+ * it's a directory.
*/
- public static void createLockFile(FileSystem fs, Path lockFile, boolean accept) throws IOException {
+ public static void createLockFile(FileSystem fs, Path lockFile, boolean accept)
+ throws IOException {
if (fs.exists(lockFile)) {
- if(!accept)
+ if (!accept)
throw new IOException("lock file " + lockFile + " already exists.");
if (fs.getFileStatus(lockFile).isDir())
- throw new IOException("lock file " + lockFile + " already exists and is a directory.");
+ throw new IOException("lock file " + lockFile
+ + " already exists and is a directory.");
// do nothing - the file already exists.
} else {
// make sure parents exist
@@ -55,16 +62,23 @@ public class LockUtil {
/**
* Remove lock file. NOTE: applications enforce the semantics of this file -
* this method simply removes any file with a given name.
- * @param fs filesystem
- * @param lockFile lock file name
+ *
+ * @param fs
+ * filesystem
+ * @param lockFile
+ * lock file name
* @return false, if the lock file doesn't exist. True, if it existed and was
- * successfully removed.
- * @throws IOException if lock file exists but it is a directory.
+ * successfully removed.
+ * @throws IOException
+ * if lock file exists but it is a directory.
*/
- public static boolean removeLockFile(FileSystem fs, Path lockFile) throws IOException {
- if (!fs.exists(lockFile)) return false;
+ public static boolean removeLockFile(FileSystem fs, Path lockFile)
+ throws IOException {
+ if (!fs.exists(lockFile))
+ return false;
if (fs.getFileStatus(lockFile).isDir())
- throw new IOException("lock file " + lockFile + " exists but is a directory!");
+ throw new IOException("lock file " + lockFile
+ + " exists but is a directory!");
return fs.delete(lockFile, false);
}
}
diff --git a/src/java/org/apache/nutch/util/MimeUtil.java b/src/java/org/apache/nutch/util/MimeUtil.java
index 781fab165..9d26abbfb 100644
--- a/src/java/org/apache/nutch/util/MimeUtil.java
+++ b/src/java/org/apache/nutch/util/MimeUtil.java
@@ -45,12 +45,12 @@ import org.apache.nutch.protocol.ProtocolOutput;
* @author mattmann
* @since NUTCH-608
*
- * <p>
- * This is a facade class to insulate Nutch from its underlying Mime Type
- * substrate library, <a href="http://incubator.apache.org/tika/">Apache Tika</a>.
- * Any mime handling code should be placed in this utility class, and hidden
- * from the Nutch classes that rely on it.
- * </p>
+ * <p>
+ * This is a facade class to insulate Nutch from its underlying Mime Type
+ * substrate library, <a href="http://incubator.apache.org/tika/">Apache
+ * Tika</a>. Any mime handling code should be placed in this utility
+ * class, and hidden from the Nutch classes that rely on it.
+ * </p>
*/
public final class MimeUtil {
@@ -66,7 +66,8 @@ public final class MimeUtil {
private boolean mimeMagic;
/* our log stream */
- private static final Logger LOG = LoggerFactory.getLogger(MimeUtil.class.getName());
+ private static final Logger LOG = LoggerFactory.getLogger(MimeUtil.class
+ .getName());
public MimeUtil(Configuration conf) {
tika = new Tika();
@@ -75,25 +76,26 @@ public final class MimeUtil {
.getName());
if (mimeTypez == null) {
try {
- String customMimeTypeFile = conf.get("mime.types.file");
- if (customMimeTypeFile!=null && customMimeTypeFile.equals("")==false){
- try {
- mimeTypez = MimeTypesFactory.create(conf
- .getConfResourceAsInputStream(customMimeTypeFile));
- }
- catch (Exception e){
- LOG.error("Can't load mime.types.file : "+customMimeTypeFile+" using Tika's default");
- }
+ String customMimeTypeFile = conf.get("mime.types.file");
+ if (customMimeTypeFile != null
+ && customMimeTypeFile.equals("") == false) {
+ try {
+ mimeTypez = MimeTypesFactory.create(conf
+ .getConfResourceAsInputStream(customMimeTypeFile));
+ } catch (Exception e) {
+ LOG.error("Can't load mime.types.file : " + customMimeTypeFile
+ + " using Tika's default");
}
- if (mimeTypez==null)
- mimeTypez = MimeTypes.getDefaultMimeTypes();
+ }
+ if (mimeTypez == null)
+ mimeTypez = MimeTypes.getDefaultMimeTypes();
} catch (Exception e) {
- LOG.error("Exception in MimeUtil "+e.getMessage());
+ LOG.error("Exception in MimeUtil " + e.getMessage());
throw new RuntimeException(e);
}
objectCache.setObject(MimeTypes.class.getName(), mimeTypez);
}
-
+
this.mimeTypes = mimeTypez;
this.mimeMagic = conf.getBoolean("mime.type.magic", true);
}
@@ -129,14 +131,13 @@ public final class MimeUtil {
/**
* A facade interface to trying all the possible mime type resolution
* strategies available within Tika. First, the mime type provided in
- * <code>typeName</code> is cleaned, with {@link #cleanMimeType(String)}.
- * Then the cleaned mime type is looked up in the underlying Tika
- * {@link MimeTypes} registry, by its cleaned name. If the {@link MimeType}
- * is found, then that mime type is used, otherwise URL resolution is
- * used to try and determine the mime type. However, if
- * <code>mime.type.magic</code> is enabled in {@link NutchConfiguration},
- * then mime type magic resolution is used to try and obtain a
- * better-than-the-default approximation of the {@link MimeType}.
+ * <code>typeName</code> is cleaned, with {@link #cleanMimeType(String)}. Then
+ * the cleaned mime type is looked up in the underlying Tika {@link MimeTypes}
+ * registry, by its cleaned name. If the {@link MimeType} is found, then that
+ * mime type is used, otherwise URL resolution is used to try and determine
+ * the mime type. However, if <code>mime.type.magic</code> is enabled in
+ * {@link NutchConfiguration}, then mime type magic resolution is used to try
+ * and obtain a better-than-the-default approximation of the {@link MimeType}.
*
* @param typeName
* The original mime type, returned from a {@link ProtocolOutput}.
@@ -176,7 +177,7 @@ public final class MimeUtil {
throw new RuntimeException(e);
}
} else {
- retType = type.getName();
+ retType = type.getName();
}
// if magic is enabled use mime magic to guess if the mime type returned
@@ -194,14 +195,15 @@ public final class MimeUtil {
InputStream stream = TikaInputStream.get(data);
try {
magicType = tika.detect(stream, tikaMeta);
- } finally {
- stream.close();
+ } finally {
+ stream.close();
}
- } catch (IOException ignore) {}
+ } catch (IOException ignore) {
+ }
if (magicType != null && !magicType.equals(MimeTypes.OCTET_STREAM)
- && !magicType.equals(MimeTypes.PLAIN_TEXT)
- && retType != null && !retType.equals(magicType)) {
+ && !magicType.equals(MimeTypes.PLAIN_TEXT) && retType != null
+ && !retType.equals(magicType)) {
// If magic enabled and the current mime type differs from that of the
// one returned from the magic, take the magic mimeType
@@ -224,12 +226,12 @@ public final class MimeUtil {
/**
* Facade interface to Tika's underlying {@link MimeTypes#getMimeType(String)}
* method.
- *
+ *
* @param url
* A string representation of the document {@link URL} to sense the
* {@link MimeType} for.
- * @return An appropriate {@link MimeType}, identified from the given
- * Document url in string form.
+ * @return An appropriate {@link MimeType}, identified from the given Document
+ * url in string form.
*/
public String getMimeType(String url) {
return tika.detect(url);
@@ -238,11 +240,11 @@ public final class MimeUtil {
/**
* A facade interface to Tika's underlying {@link MimeTypes#forName(String)}
* method.
- *
+ *
* @param name
* The name of a valid {@link MimeType} in the Tika mime registry.
- * @return The object representation of the {@link MimeType}, if it exists,
- * or null otherwise.
+ * @return The object representation of the {@link MimeType}, if it exists, or
+ * null otherwise.
*/
public String forName(String name) {
try {
@@ -257,7 +259,7 @@ public final class MimeUtil {
/**
* Facade interface to Tika's underlying {@link MimeTypes#getMimeType(File)}
* method.
- *
+ *
* @param f
* The {@link File} to sense the {@link MimeType} for.
* @return The {@link MimeType} of the given {@link File}, or null if it
@@ -273,5 +275,4 @@ public final class MimeUtil {
}
}
-
}
diff --git a/src/java/org/apache/nutch/util/NodeWalker.java b/src/java/org/apache/nutch/util/NodeWalker.java
index f7eba06f9..c99bae04f 100644
--- a/src/java/org/apache/nutch/util/NodeWalker.java
+++ b/src/java/org/apache/nutch/util/NodeWalker.java
@@ -22,13 +22,17 @@ import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
- * <p>A utility class that allows the walking of any DOM tree using a stack
- * instead of recursion. As the node tree is walked the next node is popped
- * off of the stack and all of its children are automatically added to the
- * stack to be called in tree order.</p>
+ * <p>
+ * A utility class that allows the walking of any DOM tree using a stack instead
+ * of recursion. As the node tree is walked the next node is popped off of the
+ * stack and all of its children are automatically added to the stack to be
+ * called in tree order.
+ * </p>
*
- * <p>Currently this class is not thread safe. It is assumed that only one
- * thread will be accessing the <code>NodeWalker</code> at any given time.</p>
+ * <p>
+ * Currently this class is not thread safe. It is assumed that only one thread
+ * will be accessing the <code>NodeWalker</code> at any given time.
+ * </p>
*/
public class NodeWalker {
@@ -36,7 +40,7 @@ public class NodeWalker {
private Node currentNode;
private NodeList currentChildren;
private Stack<Node> nodes;
-
+
/**
* Starts the <code>Node</code> tree from the root node.
*
@@ -47,68 +51,74 @@ public class NodeWalker {
nodes = new Stack<Node>();
nodes.add(rootNode);
}
-
+
/**
- * <p>Returns the next <code>Node</code> on the stack and pushes all of its
- * children onto the stack, allowing us to walk the node tree without the
- * use of recursion. If there are no more nodes on the stack then null is
- * returned.</p>
+ * <p>
+ * Returns the next <code>Node</code> on the stack and pushes all of its
+ * children onto the stack, allowing us to walk the node tree without the use
+ * of recursion. If there are no more nodes on the stack then null is
+ * returned.
+ * </p>
*
- * @return Node The next <code>Node</code> on the stack or null if there
- * isn't a next node.
+ * @return Node The next <code>Node</code> on the stack or null if there isn't
+ * a next node.
*/
public Node nextNode() {
-
+
// if no next node return null
if (!hasNext()) {
return null;
}
-
+
// pop the next node off of the stack and push all of its children onto
// the stack
currentNode = nodes.pop();
currentChildren = currentNode.getChildNodes();
int childLen = (currentChildren != null) ? currentChildren.getLength() : 0;
-
+
// put the children node on the stack in first to last order
for (int i = childLen - 1; i >= 0; i--) {
nodes.add(currentChildren.item(i));
}
-
+
return currentNode;
}
-
+
/**
- * <p>Skips over and removes from the node stack the children of the last
- * node. When getting a next node from the walker, that node's children
- * are automatically added to the stack. You can call this method to remove
- * those children from the stack.</p>
+ * <p>
+ * Skips over and removes from the node stack the children of the last node.
+ * When getting a next node from the walker, that node's children are
+ * automatically added to the stack. You can call this method to remove those
+ * children from the stack.
+ * </p>
+ *
+ * <p>
+ * This is useful when you don't want to process deeper into the current path
+ * of the node tree but you want to continue processing sibling nodes.
+ * </p>
*
- * <p>This is useful when you don't want to process deeper into the
- * current path of the node tree but you want to continue processing sibling
- * nodes.</p>
- *
*/
public void skipChildren() {
-
+
int childLen = (currentChildren != null) ? currentChildren.getLength() : 0;
-
- for (int i = 0 ; i < childLen ; i++) {
+
+ for (int i = 0; i < childLen; i++) {
Node child = nodes.peek();
if (child.equals(currentChildren.item(i))) {
nodes.pop();
}
}
}
-
+
/**
* Return the current node.
+ *
* @return Node
*/
public Node getCurrentNode() {
return currentNode;
}
-
+
/**
* @return returns true if there are more nodes on the current stack.
*
diff --git a/src/java/org/apache/nutch/util/NutchConfiguration.java b/src/java/org/apache/nutch/util/NutchConfiguration.java
index 47d410bb5..ac71a93d4 100644
--- a/src/java/org/apache/nutch/util/NutchConfiguration.java
+++ b/src/java/org/apache/nutch/util/NutchConfiguration.java
@@ -23,37 +23,42 @@ import java.util.UUID;
import org.apache.hadoop.conf.Configuration;
-
-/** Utility to create Hadoop {@link Configuration}s that include Nutch-specific
- * resources. */
+/**
+ * Utility to create Hadoop {@link Configuration}s that include Nutch-specific
+ * resources.
+ */
public class NutchConfiguration {
public static final String UUID_KEY = "nutch.conf.uuid";
-
- private NutchConfiguration() {} // singleton
-
+
+ private NutchConfiguration() {
+ } // singleton
+
/*
- * Configuration.hashCode() doesn't return values that
- * correspond to a unique set of parameters. This is a workaround
- * so that we can track instances of Configuration created by Nutch.
+ * Configuration.hashCode() doesn't return values that correspond to a unique
+ * set of parameters. This is a workaround so that we can track instances of
+ * Configuration created by Nutch.
*/
private static void setUUID(Configuration conf) {
UUID uuid = UUID.randomUUID();
conf.set(UUID_KEY, uuid.toString());
}
-
+
/**
- * Retrieve a Nutch UUID of this configuration object, or null
- * if the configuration was created elsewhere.
- * @param conf configuration instance
+ * Retrieve a Nutch UUID of this configuration object, or null if the
+ * configuration was created elsewhere.
+ *
+ * @param conf
+ * configuration instance
* @return uuid or null
*/
public static String getUUID(Configuration conf) {
return conf.get(UUID_KEY);
}
- /** Create a {@link Configuration} for Nutch. This will load the standard
- * Nutch resources, <code>nutch-default.xml</code> and
- * <code>nutch-site.xml</code> overrides.
+ /**
+ * Create a {@link Configuration} for Nutch. This will load the standard Nutch
+ * resources, <code>nutch-default.xml</code> and <code>nutch-site.xml</code>
+ * overrides.
*/
public static Configuration create() {
Configuration conf = new Configuration();
@@ -61,14 +66,19 @@ public class NutchConfiguration {
addNutchResources(conf);
return conf;
}
-
- /** Create a {@link Configuration} from supplied properties.
- * @param addNutchResources if true, then first <code>nutch-default.xml</code>,
- * and then <code>nutch-site.xml</code> will be loaded prior to applying the
- * properties. Otherwise these resources won't be used.
- * @param nutchProperties a set of properties to define (or override)
+
+ /**
+ * Create a {@link Configuration} from supplied properties.
+ *
+ * @param addNutchResources
+ * if true, then first <code>nutch-default.xml</code>, and then
+ * <code>nutch-site.xml</code> will be loaded prior to applying the
+ * properties. Otherwise these resources won't be used.
+ * @param nutchProperties
+ * a set of properties to define (or override)
*/
- public static Configuration create(boolean addNutchResources, Properties nutchProperties) {
+ public static Configuration create(boolean addNutchResources,
+ Properties nutchProperties) {
Configuration conf = new Configuration();
setUUID(conf);
if (addNutchResources) {
@@ -83,8 +93,8 @@ public class NutchConfiguration {
/**
* Add the standard Nutch resources to {@link Configuration}.
*
- * @param conf Configuration object to which
- * configuration is to be added.
+ * @param conf
+ * Configuration object to which configuration is to be added.
*/
private static Configuration addNutchResources(Configuration conf) {
conf.addResource("nutch-default.xml");
@@ -92,4 +102,3 @@ public class NutchConfiguration {
return conf;
}
}
-
diff --git a/src/java/org/apache/nutch/util/NutchJob.java b/src/java/org/apache/nutch/util/NutchJob.java
index fef433fe8..8b4f8e0de 100644
--- a/src/java/org/apache/nutch/util/NutchJob.java
+++ b/src/java/org/apache/nutch/util/NutchJob.java
@@ -20,7 +20,7 @@ package org.apache.nutch.util;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.JobConf;
-/** A {@link JobConf} for Nutch jobs. */
+/** A {@link JobConf} for Nutch jobs. */
public class NutchJob extends JobConf {
public NutchJob(Configuration conf) {
@@ -28,4 +28,3 @@ public class NutchJob extends JobConf {
}
}
-
diff --git a/src/java/org/apache/nutch/util/ObjectCache.java b/src/java/org/apache/nutch/util/ObjectCache.java
index 7cb7b5772..0277ee6b1 100644
--- a/src/java/org/apache/nutch/util/ObjectCache.java
+++ b/src/java/org/apache/nutch/util/ObjectCache.java
@@ -24,35 +24,33 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
public class ObjectCache {
-
+
private static final Logger LOG = LoggerFactory.getLogger(ObjectCache.class);
-
- private static final WeakHashMap<Configuration, ObjectCache> CACHE =
- new WeakHashMap<Configuration, ObjectCache>();
+
+ private static final WeakHashMap<Configuration, ObjectCache> CACHE = new WeakHashMap<Configuration, ObjectCache>();
private final HashMap<String, Object> objectMap;
-
+
private ObjectCache() {
objectMap = new HashMap<String, Object>();
}
-
+
public synchronized static ObjectCache get(Configuration conf) {
ObjectCache objectCache = CACHE.get(conf);
if (objectCache == null) {
- LOG.debug("No object cache found for conf=" + conf
- + ", instantiating a new object cache");
+ LOG.debug("No object cache found for conf=" + conf
+ + ", instantiating a new object cache");
objectCache = new ObjectCache();
CACHE.put(conf, objectCache);
}
return objectCache;
}
-
+
public synchronized Object getObject(String key) {
return objectMap.get(key);
}
-
+
public synchronized void setObject(String key, Object value) {
objectMap.put(key, value);
}
}
-
diff --git a/src/java/org/apache/nutch/util/PrefixStringMatcher.java b/src/java/org/apache/nutch/util/PrefixStringMatcher.java
index d30530d7e..e323b6753 100644
--- a/src/java/org/apache/nutch/util/PrefixStringMatcher.java
+++ b/src/java/org/apache/nutch/util/PrefixStringMatcher.java
@@ -21,46 +21,47 @@ import java.util.Collection;
import java.util.Iterator;
/**
- * A class for efficiently matching <code>String</code>s against a set
- * of prefixes.
+ * A class for efficiently matching <code>String</code>s against a set of
+ * prefixes.
*/
public class PrefixStringMatcher extends TrieStringMatcher {
/**
* Creates a new <code>PrefixStringMatcher</code> which will match
- * <code>String</code>s with any prefix in the supplied array.
- * Zero-length <code>Strings</code> are ignored.
+ * <code>String</code>s with any prefix in the supplied array. Zero-length
+ * <code>Strings</code> are ignored.
*/
public PrefixStringMatcher(String[] prefixes) {
super();
- for (int i= 0; i < prefixes.length; i++)
+ for (int i = 0; i < prefixes.length; i++)
addPatternForward(prefixes[i]);
}
/**
* Creates a new <code>PrefixStringMatcher</code> which will match
- * <code>String</code>s with any prefix in the supplied
+ * <code>String</code>s with any prefix in the supplied
* <code>Collection</code>.
- *
- * @throws ClassCastException if any <code>Object</code>s in the
- * collection are not <code>String</code>s
+ *
+ * @throws ClassCastException
+ * if any <code>Object</code>s in the collection are not
+ * <code>String</code>s
*/
public PrefixStringMatcher(Collection<String> prefixes) {
super();
- Iterator<String> iter= prefixes.iterator();
+ Iterator<String> iter = prefixes.iterator();
while (iter.hasNext())
addPatternForward(iter.next());
}
/**
- * Returns true if the given <code>String</code> is matched by a
- * prefix in the trie
+ * Returns true if the given <code>String</code> is matched by a prefix in the
+ * trie
*/
public boolean matches(String input) {
- TrieNode node= root;
- for (int i= 0; i < input.length(); i++) {
- node= node.getChild(input.charAt(i));
- if (node == null)
+ TrieNode node = root;
+ for (int i = 0; i < input.length(); i++) {
+ node = node.getChild(input.charAt(i));
+ if (node == null)
return false;
if (node.isTerminal())
return true;
@@ -73,13 +74,13 @@ public class PrefixStringMatcher extends TrieStringMatcher {
* or <code>null<code> if no match exists.
*/
public String shortestMatch(String input) {
- TrieNode node= root;
- for (int i= 0; i < input.length(); i++) {
- node= node.getChild(input.charAt(i));
- if (node == null)
+ TrieNode node = root;
+ for (int i = 0; i < input.length(); i++) {
+ node = node.getChild(input.charAt(i));
+ if (node == null)
return null;
if (node.isTerminal())
- return input.substring(0, i+1);
+ return input.substring(0, i + 1);
}
return null;
}
@@ -89,29 +90,26 @@ public class PrefixStringMatcher extends TrieStringMatcher {
* or <code>null<code> if no match exists.
*/
public String longestMatch(String input) {
- TrieNode node= root;
- String result= null;
- for (int i= 0; i < input.length(); i++) {
- node= node.getChild(input.charAt(i));
- if (node == null)
+ TrieNode node = root;
+ String result = null;
+ for (int i = 0; i < input.length(); i++) {
+ node = node.getChild(input.charAt(i));
+ if (node == null)
break;
if (node.isTerminal())
- result= input.substring(0, i+1);
+ result = input.substring(0, i + 1);
}
return result;
}
public static final void main(String[] argv) {
- PrefixStringMatcher matcher=
- new PrefixStringMatcher(
- new String[]
- {"abcd", "abc", "aac", "baz", "foo", "foobar"} );
+ PrefixStringMatcher matcher = new PrefixStringMatcher(new String[] {
+ "abcd", "abc", "aac", "baz", "foo", "foobar" });
- String[] tests= {"a", "ab", "abc", "abcdefg", "apple", "aa", "aac",
- "aaccca", "abaz", "baz", "bazooka", "fo", "foobar",
- "kite", };
+ String[] tests = { "a", "ab", "abc", "abcdefg", "apple", "aa", "aac",
+ "aaccca", "abaz", "baz", "bazooka", "fo", "foobar", "kite", };
- for (int i= 0; i < tests.length; i++) {
+ for (int i = 0; i < tests.length; i++) {
System.out.println("testing: " + tests[i]);
System.out.println(" matches: " + matcher.matches(tests[i]));
System.out.println(" shortest: " + matcher.shortestMatch(tests[i]));
diff --git a/src/java/org/apache/nutch/util/StringUtil.java b/src/java/org/apache/nutch/util/StringUtil.java
index 060733158..149269f7e 100644
--- a/src/java/org/apache/nutch/util/StringUtil.java
+++ b/src/java/org/apache/nutch/util/StringUtil.java
@@ -18,42 +18,42 @@
package org.apache.nutch.util;
/**
- * A collection of String processing utility methods.
+ * A collection of String processing utility methods.
*/
public class StringUtil {
/**
- * Returns a copy of <code>s</code> padded with trailing spaces so
- * that it's length is <code>length</code>. Strings already
- * <code>length</code> characters long or longer are not altered.
+ * Returns a copy of <code>s</code> padded with trailing spaces so that it's
+ * length is <code>length</code>. Strings already <code>length</code>
+ * characters long or longer are not altered.
*/
public static String rightPad(String s, int length) {
- StringBuffer sb= new StringBuffer(s);
- for (int i= length - s.length(); i > 0; i--)
+ StringBuffer sb = new StringBuffer(s);
+ for (int i = length - s.length(); i > 0; i--)
sb.append(" ");
return sb.toString();
}
/**
- * Returns a copy of <code>s</code> padded with leading spaces so
- * that it's length is <code>length</code>. Strings already
- * <code>length</code> characters long or longer are not altered.
+ * Returns a copy of <code>s</code> padded with leading spaces so that it's
+ * length is <code>length</code>. Strings already <code>length</code>
+ * characters long or longer are not altered.
*/
public static String leftPad(String s, int length) {
- StringBuffer sb= new StringBuffer();
- for (int i= length - s.length(); i > 0; i--)
+ StringBuffer sb = new StringBuffer();
+ for (int i = length - s.length(); i > 0; i--)
sb.append(" ");
sb.append(s);
return sb.toString();
}
-
- private static final char[] HEX_DIGITS =
- {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
+ private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6',
+ '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* Convenience call for {@link #toHexString(byte[], String, int)}, where
* <code>sep = null; lineLen = Integer.MAX_VALUE</code>.
+ *
* @param buf
*/
public static String toHexString(byte[] buf) {
@@ -63,37 +63,48 @@ public class StringUtil {
/**
* Get a text representation of a byte[] as hexadecimal String, where each
* pair of hexadecimal digits corresponds to consecutive bytes in the array.
- * @param buf input data
- * @param sep separate every pair of hexadecimal digits with this separator, or
- * null if no separation is needed.
- * @param lineLen break the output String into lines containing output for lineLen
- * bytes.
+ *
+ * @param buf
+ * input data
+ * @param sep
+ * separate every pair of hexadecimal digits with this separator, or
+ * null if no separation is needed.
+ * @param lineLen
+ * break the output String into lines containing output for lineLen
+ * bytes.
*/
public static String toHexString(byte[] buf, String sep, int lineLen) {
- if (buf == null) return null;
- if (lineLen <= 0) lineLen = Integer.MAX_VALUE;
+ if (buf == null)
+ return null;
+ if (lineLen <= 0)
+ lineLen = Integer.MAX_VALUE;
StringBuffer res = new StringBuffer(buf.length * 2);
for (int i = 0; i < buf.length; i++) {
int b = buf[i];
res.append(HEX_DIGITS[(b >> 4) & 0xf]);
res.append(HEX_DIGITS[b & 0xf]);
- if (i > 0 && (i % lineLen) == 0) res.append('\n');
- else if (sep != null && i < lineLen - 1) res.append(sep);
+ if (i > 0 && (i % lineLen) == 0)
+ res.append('\n');
+ else if (sep != null && i < lineLen - 1)
+ res.append(sep);
}
return res.toString();
}
-
+
/**
* Convert a String containing consecutive (no inside whitespace) hexadecimal
- * digits into a corresponding byte array. If the number of digits is not even,
- * a '0' will be appended in the front of the String prior to conversion.
- * Leading and trailing whitespace is ignored.
- * @param text input text
+ * digits into a corresponding byte array. If the number of digits is not
+ * even, a '0' will be appended in the front of the String prior to
+ * conversion. Leading and trailing whitespace is ignored.
+ *
+ * @param text
+ * input text
* @return converted byte array, or null if unable to convert
*/
public static byte[] fromHexString(String text) {
text = text.trim();
- if (text.length() % 2 != 0) text = "0" + text;
+ if (text.length() % 2 != 0)
+ text = "0" + text;
int resLen = text.length() / 2;
int loNibble, hiNibble;
byte[] res = new byte[resLen];
@@ -101,12 +112,13 @@ public class StringUtil {
int j = i << 1;
hiNibble = charToNibble(text.charAt(j));
loNibble = charToNibble(text.charAt(j + 1));
- if (loNibble == -1 || hiNibble == -1) return null;
- res[i] = (byte)(hiNibble << 4 | loNibble);
+ if (loNibble == -1 || hiNibble == -1)
+ return null;
+ res[i] = (byte) (hiNibble << 4 | loNibble);
}
return res;
}
-
+
private static final int charToNibble(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
@@ -125,7 +137,7 @@ public class StringUtil {
public static boolean isEmpty(String str) {
return (str == null) || (str.equals(""));
}
-
+
/**
* Simple character substitution which cleans all � chars from a given String.
*/
@@ -136,8 +148,8 @@ public class StringUtil {
public static void main(String[] args) {
if (args.length != 1)
System.out.println("Usage: StringUtil <encoding name>");
- else
- System.out.println(args[0] + " is resolved to " +
- EncodingDetector.resolveEncodingAlias(args[0]));
+ else
+ System.out.println(args[0] + " is resolved to "
+ + EncodingDetector.resolveEncodingAlias(args[0]));
}
}
diff --git a/src/java/org/apache/nutch/util/SuffixStringMatcher.java b/src/java/org/apache/nutch/util/SuffixStringMatcher.java
index e4d592e53..a967c0177 100644
--- a/src/java/org/apache/nutch/util/SuffixStringMatcher.java
+++ b/src/java/org/apache/nutch/util/SuffixStringMatcher.java
@@ -21,8 +21,8 @@ import java.util.Collection;
import java.util.Iterator;
/**
- * A class for efficiently matching <code>String</code>s against a set
- * of suffixes. Zero-length <code>Strings</code> are ignored.
+ * A class for efficiently matching <code>String</code>s against a set of
+ * suffixes. Zero-length <code>Strings</code> are ignored.
*/
public class SuffixStringMatcher extends TrieStringMatcher {
@@ -32,7 +32,7 @@ public class SuffixStringMatcher extends TrieStringMatcher {
*/
public SuffixStringMatcher(String[] suffixes) {
super();
- for (int i= 0; i < suffixes.length; i++)
+ for (int i = 0; i < suffixes.length; i++)
addPatternBackward(suffixes[i]);
}
@@ -43,20 +43,20 @@ public class SuffixStringMatcher extends TrieStringMatcher {
*/
public SuffixStringMatcher(Collection<String> suffixes) {
super();
- Iterator<String> iter= suffixes.iterator();
+ Iterator<String> iter = suffixes.iterator();
while (iter.hasNext())
addPatternBackward(iter.next());
}
/**
- * Returns true if the given <code>String</code> is matched by a
- * suffix in the trie
+ * Returns true if the given <code>String</code> is matched by a suffix in the
+ * trie
*/
public boolean matches(String input) {
- TrieNode node= root;
- for (int i= input.length() - 1; i >= 0; i--) {
- node= node.getChild(input.charAt(i));
- if (node == null)
+ TrieNode node = root;
+ for (int i = input.length() - 1; i >= 0; i--) {
+ node = node.getChild(input.charAt(i));
+ if (node == null)
return false;
if (node.isTerminal())
return true;
@@ -64,16 +64,15 @@ public class SuffixStringMatcher extends TrieStringMatcher {
return false;
}
-
/**
* Returns the shortest suffix of <code>input<code> that is matched,
* or <code>null<code> if no match exists.
*/
public String shortestMatch(String input) {
- TrieNode node= root;
- for (int i= input.length() - 1; i >= 0; i--) {
- node= node.getChild(input.charAt(i));
- if (node == null)
+ TrieNode node = root;
+ for (int i = input.length() - 1; i >= 0; i--) {
+ node = node.getChild(input.charAt(i));
+ if (node == null)
return null;
if (node.isTerminal())
return input.substring(i);
@@ -86,29 +85,26 @@ public class SuffixStringMatcher extends TrieStringMatcher {
* or <code>null<code> if no match exists.
*/
public String longestMatch(String input) {
- TrieNode node= root;
- String result= null;
- for (int i= input.length() - 1; i >= 0; i--) {
- node= node.getChild(input.charAt(i));
- if (node == null)
+ TrieNode node = root;
+ String result = null;
+ for (int i = input.length() - 1; i >= 0; i--) {
+ node = node.getChild(input.charAt(i));
+ if (node == null)
break;
if (node.isTerminal())
- result= input.substring(i);
+ result = input.substring(i);
}
return result;
}
public static final void main(String[] argv) {
- SuffixStringMatcher matcher=
- new SuffixStringMatcher(
- new String[]
- {"a", "abcd", "bcd", "bcdefg", "defg", "aac", "baz", "foo", "foobar"} );
+ SuffixStringMatcher matcher = new SuffixStringMatcher(new String[] { "a",
+ "abcd", "bcd", "bcdefg", "defg", "aac", "baz", "foo", "foobar" });
- String[] tests= {"a", "ac", "abcd", "abcdefg", "apple", "aa", "aac",
- "aaccca", "abaz", "baz", "bazooka", "fo", "foobar",
- "kite", };
+ String[] tests = { "a", "ac", "abcd", "abcdefg", "apple", "aa", "aac",
+ "aaccca", "abaz", "baz", "bazooka", "fo", "foobar", "kite", };
- for (int i= 0; i < tests.length; i++) {
+ for (int i = 0; i < tests.length; i++) {
System.out.println("testing: " + tests[i]);
System.out.println(" matches: " + matcher.matches(tests[i]));
System.out.println(" shortest: " + matcher.shortestMatch(tests[i]));
diff --git a/src/java/org/apache/nutch/util/TimingUtil.java b/src/java/org/apache/nutch/util/TimingUtil.java
index 8ed5ca8e2..8f77969a5 100644
--- a/src/java/org/apache/nutch/util/TimingUtil.java
+++ b/src/java/org/apache/nutch/util/TimingUtil.java
@@ -21,35 +21,39 @@ import java.text.NumberFormat;
public class TimingUtil {
- private static long[] TIME_FACTOR = { 60 * 60 * 1000, 60 * 1000, 1000 };
-
- /**
- * Calculate the elapsed time between two times specified in milliseconds.
- * @param start The start of the time period
- * @param end The end of the time period
- * @return a string of the form "XhYmZs" when the elapsed time is X hours, Y minutes and Z seconds or null if start > end.
- */
- public static String elapsedTime(long start, long end){
- if (start > end) {
- return null;
- }
-
- long[] elapsedTime = new long[TIME_FACTOR.length];
-
- for (int i = 0; i < TIME_FACTOR.length; i++) {
- elapsedTime[i] = start > end ? -1 : (end - start) / TIME_FACTOR[i];
- start += TIME_FACTOR[i] * elapsedTime[i];
- }
-
- NumberFormat nf = NumberFormat.getInstance();
- nf.setMinimumIntegerDigits(2);
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < elapsedTime.length; i++) {
- if (i > 0) {
- buf.append(":");
- }
- buf.append(nf.format(elapsedTime[i]));
- }
- return buf.toString();
+ private static long[] TIME_FACTOR = { 60 * 60 * 1000, 60 * 1000, 1000 };
+
+ /**
+ * Calculate the elapsed time between two times specified in milliseconds.
+ *
+ * @param start
+ * The start of the time period
+ * @param end
+ * The end of the time period
+ * @return a string of the form "XhYmZs" when the elapsed time is X hours, Y
+ * minutes and Z seconds or null if start > end.
+ */
+ public static String elapsedTime(long start, long end) {
+ if (start > end) {
+ return null;
}
+
+ long[] elapsedTime = new long[TIME_FACTOR.length];
+
+ for (int i = 0; i < TIME_FACTOR.length; i++) {
+ elapsedTime[i] = start > end ? -1 : (end - start) / TIME_FACTOR[i];
+ start += TIME_FACTOR[i] * elapsedTime[i];
+ }
+
+ NumberFormat nf = NumberFormat.getInstance();
+ nf.setMinimumIntegerDigits(2);
+ StringBuffer buf = new StringBuffer();
+ for (int i = 0; i < elapsedTime.length; i++) {
+ if (i > 0) {
+ buf.append(":");
+ }
+ buf.append(nf.format(elapsedTime[i]));
+ }
+ return buf.toString();
+ }
}
diff --git a/src/java/org/apache/nutch/util/TrieStringMatcher.java b/src/java/org/apache/nutch/util/TrieStringMatcher.java
index 140296215..95f06ad6f 100644
--- a/src/java/org/apache/nutch/util/TrieStringMatcher.java
+++ b/src/java/org/apache/nutch/util/TrieStringMatcher.java
@@ -17,21 +17,19 @@
package org.apache.nutch.util;
-
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
/**
- * TrieStringMatcher is a base class for simple tree-based string
- * matching.
- *
+ * TrieStringMatcher is a base class for simple tree-based string matching.
+ *
*/
public abstract class TrieStringMatcher {
protected TrieNode root;
protected TrieStringMatcher() {
- this.root= new TrieNode('\000', false);
+ this.root = new TrieNode('\000', false);
}
/**
@@ -44,20 +42,19 @@ public abstract class TrieStringMatcher {
protected boolean terminal;
/**
- * Creates a new TrieNode, which contains the given
- * <code>nodeChar</code>. If <code>isTerminal</code> is
- * <code>true</code>, the new node is a <em>terminal</em> node in
- * the trie.
- */
+ * Creates a new TrieNode, which contains the given <code>nodeChar</code>.
+ * If <code>isTerminal</code> is <code>true</code>, the new node is a
+ * <em>terminal</em> node in the trie.
+ */
TrieNode(char nodeChar, boolean isTerminal) {
- this.nodeChar= nodeChar;
- this.terminal= isTerminal;
- this.childrenList= new LinkedList<TrieNode>();
+ this.nodeChar = nodeChar;
+ this.terminal = isTerminal;
+ this.childrenList = new LinkedList<TrieNode>();
}
/**
- * Returns <code>true</code> if this node is a <em>terminal</em>
- * node in the trie.
+ * Returns <code>true</code> if this node is a <em>terminal</em> node in the
+ * trie.
*/
boolean isTerminal() {
return terminal;
@@ -65,67 +62,68 @@ public abstract class TrieStringMatcher {
/**
* Returns the child node of this node whose node-character is
- * <code>nextChar</code>. If no such node exists, one will be is
- * added. If <em>isTerminal</em> is <code>true</code>, the node
- * will be a terminal node in the trie.
+ * <code>nextChar</code>. If no such node exists, one will be is added. If
+ * <em>isTerminal</em> is <code>true</code>, the node will be a terminal
+ * node in the trie.
*/
TrieNode getChildAddIfNotPresent(char nextChar, boolean isTerminal) {
if (childrenList == null) {
- childrenList= new LinkedList<TrieNode>();
+ childrenList = new LinkedList<TrieNode>();
childrenList.addAll(Arrays.asList(children));
- children= null;
+ children = null;
}
if (childrenList.size() == 0) {
- TrieNode newNode= new TrieNode(nextChar, isTerminal);
+ TrieNode newNode = new TrieNode(nextChar, isTerminal);
childrenList.add(newNode);
return newNode;
}
- ListIterator<TrieNode> iter= childrenList.listIterator();
- TrieNode node= iter.next();
- while ( (node.nodeChar < nextChar) && iter.hasNext() )
- node= iter.next();
-
+ ListIterator<TrieNode> iter = childrenList.listIterator();
+ TrieNode node = iter.next();
+ while ((node.nodeChar < nextChar) && iter.hasNext())
+ node = iter.next();
+
if (node.nodeChar == nextChar) {
- node.terminal= node.terminal | isTerminal;
+ node.terminal = node.terminal | isTerminal;
return node;
}
- if (node.nodeChar > nextChar)
+ if (node.nodeChar > nextChar)
iter.previous();
- TrieNode newNode= new TrieNode(nextChar, isTerminal);
+ TrieNode newNode = new TrieNode(nextChar, isTerminal);
iter.add(newNode);
- return newNode;
+ return newNode;
}
/**
* Returns the child node of this node whose node-character is
- * <code>nextChar</code>. If no such node exists,
- * <code>null</code> is returned.
+ * <code>nextChar</code>. If no such node exists, <code>null</code> is
+ * returned.
*/
TrieNode getChild(char nextChar) {
if (children == null) {
- children= childrenList.toArray(new TrieNode[childrenList.size()]);
- childrenList= null;
+ children = childrenList.toArray(new TrieNode[childrenList.size()]);
+ childrenList = null;
Arrays.sort(children);
}
- int min= 0;
- int max= children.length - 1;
- int mid= 0;
+ int min = 0;
+ int max = children.length - 1;
+ int mid = 0;
while (min < max) {
- mid= (min + max) / 2;
- if (children[mid].nodeChar == nextChar)
+ mid = (min + max) / 2;
+ if (children[mid].nodeChar == nextChar)
return children[mid];
if (children[mid].nodeChar < nextChar)
- min= mid + 1;
- else // if (children[mid].nodeChar > nextChar)
- max= mid - 1;
+ min = mid + 1;
+ else
+ // if (children[mid].nodeChar > nextChar)
+ max = mid - 1;
}
- if (min == max)
+ if (min == max)
if (children[min].nodeChar == nextChar)
return children[min];
@@ -133,59 +131,57 @@ public abstract class TrieStringMatcher {
}
public int compareTo(TrieNode other) {
- if (this.nodeChar < other.nodeChar)
+ if (this.nodeChar < other.nodeChar)
return -1;
- if (this.nodeChar == other.nodeChar)
+ if (this.nodeChar == other.nodeChar)
return 0;
-// if (this.nodeChar > other.nodeChar)
+ // if (this.nodeChar > other.nodeChar)
return 1;
}
}
/**
* Returns the next {@link TrieNode} visited, given that you are at
- * <code>node</code>, and the the next character in the input is
- * the <code>idx</code>'th character of <code>s</code>.
+ * <code>node</code>, and the the next character in the input is the
+ * <code>idx</code>'th character of <code>s</code>.
*/
protected final TrieNode matchChar(TrieNode node, String s, int idx) {
return node.getChild(s.charAt(idx));
}
/**
- * Adds any necessary nodes to the trie so that the given
- * <code>String</code> can be decoded and the last character is
- * represented by a terminal node. Zero-length <code>Strings</code>
- * are ignored.
+ * Adds any necessary nodes to the trie so that the given <code>String</code>
+ * can be decoded and the last character is represented by a terminal node.
+ * Zero-length <code>Strings</code> are ignored.
*/
protected final void addPatternForward(String s) {
- TrieNode node= root;
- int stop= s.length() - 1;
+ TrieNode node = root;
+ int stop = s.length() - 1;
int i;
if (s.length() > 0) {
- for (i= 0; i < stop; i++)
- node= node.getChildAddIfNotPresent(s.charAt(i), false);
- node= node.getChildAddIfNotPresent(s.charAt(i), true);
+ for (i = 0; i < stop; i++)
+ node = node.getChildAddIfNotPresent(s.charAt(i), false);
+ node = node.getChildAddIfNotPresent(s.charAt(i), true);
}
}
/**
- * Adds any necessary nodes to the trie so that the given
- * <code>String</code> can be decoded <em>in reverse</em> and the
- * first character is represented by a terminal node. Zero-length
- * <code>Strings</code> are ignored.
+ * Adds any necessary nodes to the trie so that the given <code>String</code>
+ * can be decoded <em>in reverse</em> and the first character is represented
+ * by a terminal node. Zero-length <code>Strings</code> are ignored.
*/
protected final void addPatternBackward(String s) {
- TrieNode node= root;
+ TrieNode node = root;
if (s.length() > 0) {
- for (int i= s.length()-1; i > 0; i--)
- node= node.getChildAddIfNotPresent(s.charAt(i), false);
- node= node.getChildAddIfNotPresent(s.charAt(0), true);
+ for (int i = s.length() - 1; i > 0; i--)
+ node = node.getChildAddIfNotPresent(s.charAt(i), false);
+ node = node.getChildAddIfNotPresent(s.charAt(0), true);
}
}
/**
- * Returns true if the given <code>String</code> is matched by a
- * pattern in the trie
+ * Returns true if the given <code>String</code> is matched by a pattern in
+ * the trie
*/
public abstract boolean matches(String input);
diff --git a/src/java/org/apache/nutch/util/URLUtil.java b/src/java/org/apache/nutch/util/URLUtil.java
index 68b792e29..3e696cb49 100644
--- a/src/java/org/apache/nutch/util/URLUtil.java
+++ b/src/java/org/apache/nutch/util/URLUtil.java
@@ -26,17 +26,20 @@ import org.apache.nutch.util.domain.DomainSuffixes;
/** Utility class for URL analysis */
public class URLUtil {
-
+
/**
- * Resolve relative URL-s and fix a java.net.URL error
- * in handling of URLs with pure query targets.
- * @param base base url
- * @param target target url (may be relative)
+ * Resolve relative URL-s and fix a java.net.URL error in handling of URLs
+ * with pure query targets.
+ *
+ * @param base
+ * base url
+ * @param target
+ * target url (may be relative)
* @return resolved absolute url.
* @throws MalformedURLException
*/
public static URL resolveURL(URL base, String target)
- throws MalformedURLException {
+ throws MalformedURLException {
target = target.trim();
// handle the case that there is a target that is a pure query,
@@ -58,9 +61,10 @@ public class URLUtil {
}
/** Handle the case in RFC3986 section 5.4.1 example 7, and similar. */
- static URL fixPureQueryTargets(URL base, String target)
- throws MalformedURLException {
- if (!target.startsWith("?")) return new URL(base, target);
+ static URL fixPureQueryTargets(URL base, String target)
+ throws MalformedURLException {
+ if (!target.startsWith("?"))
+ return new URL(base, target);
String basePath = base.getPath();
String baseRightMost = "";
@@ -69,63 +73,75 @@ public class URLUtil {
baseRightMost = basePath.substring(baseRightMostIdx + 1);
}
- if (target.startsWith("?")) target = baseRightMost + target;
+ if (target.startsWith("?"))
+ target = baseRightMost + target;
return new URL(base, target);
}
- private static Pattern IP_PATTERN = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");
+ private static Pattern IP_PATTERN = Pattern
+ .compile("(\\d{1,3}\\.){3}(\\d{1,3})");
- /** Returns the domain name of the url. The domain name of a url is
- * the substring of the url's hostname, w/o subdomain names. As an
- * example <br><code>
+ /**
+ * Returns the domain name of the url. The domain name of a url is the
+ * substring of the url's hostname, w/o subdomain names. As an example <br>
+ * <code>
* getDomainName(conf, new URL(http://lucene.apache.org/))
* </code><br>
- * will return <br><code> apache.org</code>
- * */
+ * will return <br>
+ * <code> apache.org</code>
+ * */
public static String getDomainName(URL url) {
DomainSuffixes tlds = DomainSuffixes.getInstance();
String host = url.getHost();
- //it seems that java returns hostnames ending with .
- if(host.endsWith("."))
+ // it seems that java returns hostnames ending with .
+ if (host.endsWith("."))
host = host.substring(0, host.length() - 1);
- if(IP_PATTERN.matcher(host).matches())
+ if (IP_PATTERN.matcher(host).matches())
return host;
-
+
int index = 0;
String candidate = host;
- for(;index >= 0;) {
+ for (; index >= 0;) {
index = candidate.indexOf('.');
- String subCandidate = candidate.substring(index+1);
- if(tlds.isDomainSuffix(subCandidate)) {
- return candidate;
+ String subCandidate = candidate.substring(index + 1);
+ if (tlds.isDomainSuffix(subCandidate)) {
+ return candidate;
}
candidate = subCandidate;
}
return candidate;
}
- /** Returns the domain name of the url. The domain name of a url is
- * the substring of the url's hostname, w/o subdomain names. As an
- * example <br><code>
+ /**
+ * Returns the domain name of the url. The domain name of a url is the
+ * substring of the url's hostname, w/o subdomain names. As an example <br>
+ * <code>
* getDomainName(conf, new http://lucene.apache.org/)
* </code><br>
- * will return <br><code> apache.org</code>
+ * will return <br>
+ * <code> apache.org</code>
+ *
* @throws MalformedURLException
*/
public static String getDomainName(String url) throws MalformedURLException {
return getDomainName(new URL(url));
}
- /** Returns the top level domain name of the url. The top level domain name
- * of a url is the substring of the url's hostname, w/o subdomain names.
- * As an example <br><code>
+ /**
+ * Returns the top level domain name of the url. The top level domain name of
+ * a url is the substring of the url's hostname, w/o subdomain names. As an
+ * example <br>
+ * <code>
* getTopLevelDomainName(conf, new http://lucene.apache.org/)
* </code><br>
- * will return <br><code> org</code>
+ * will return <br>
+ * <code> org</code>
+ *
* @throws MalformedURLException
*/
- public static String getTopLevelDomainName(URL url) throws MalformedURLException {
+ public static String getTopLevelDomainName(URL url)
+ throws MalformedURLException {
String suffix = getDomainSuffix(url).toString();
int idx = suffix.lastIndexOf(".");
if (idx != -1) {
@@ -135,94 +151,110 @@ public class URLUtil {
}
}
- /** Returns the top level domain name of the url. The top level domain name
- * of a url is the substring of the url's hostname, w/o subdomain names.
- * As an example <br><code>
+ /**
+ * Returns the top level domain name of the url. The top level domain name of
+ * a url is the substring of the url's hostname, w/o subdomain names. As an
+ * example <br>
+ * <code>
* getTopLevelDomainName(conf, new http://lucene.apache.org/)
* </code><br>
- * will return <br><code> org</code>
+ * will return <br>
+ * <code> org</code>
+ *
* @throws MalformedURLException
*/
- public static String getTopLevelDomainName(String url) throws MalformedURLException {
+ public static String getTopLevelDomainName(String url)
+ throws MalformedURLException {
return getTopLevelDomainName(new URL(url));
}
- /** Returns whether the given urls have the same domain name.
- * As an example, <br>
+ /**
+ * Returns whether the given urls have the same domain name. As an example, <br>
* <code> isSameDomain(new URL("http://lucene.apache.org")
* , new URL("http://people.apache.org/"))
* <br> will return true. </code>
- *
+ *
* @return true if the domain names are equal
*/
public static boolean isSameDomainName(URL url1, URL url2) {
return getDomainName(url1).equalsIgnoreCase(getDomainName(url2));
}
- /**Returns whether the given urls have the same domain name.
- * As an example, <br>
- * <code> isSameDomain("http://lucene.apache.org"
- * ,"http://people.apache.org/")
- * <br> will return true. </code>
- * @return true if the domain names are equal
- * @throws MalformedURLException
- */
+ /**
+ * Returns whether the given urls have the same domain name. As an example, <br>
+ * <code> isSameDomain("http://lucene.apache.org"
+ * ,"http://people.apache.org/")
+ * <br> will return true. </code>
+ *
+ * @return true if the domain names are equal
+ * @throws MalformedURLException
+ */
public static boolean isSameDomainName(String url1, String url2)
- throws MalformedURLException {
+ throws MalformedURLException {
return isSameDomainName(new URL(url1), new URL(url2));
}
- /** Returns the {@link DomainSuffix} corresponding to the
- * last public part of the hostname
+ /**
+ * Returns the {@link DomainSuffix} corresponding to the last public part of
+ * the hostname
*/
public static DomainSuffix getDomainSuffix(URL url) {
DomainSuffixes tlds = DomainSuffixes.getInstance();
String host = url.getHost();
- if(IP_PATTERN.matcher(host).matches())
+ if (IP_PATTERN.matcher(host).matches())
return null;
-
+
int index = 0;
String candidate = host;
- for(;index >= 0;) {
+ for (; index >= 0;) {
index = candidate.indexOf('.');
- String subCandidate = candidate.substring(index+1);
+ String subCandidate = candidate.substring(index + 1);
DomainSuffix d = tlds.get(subCandidate);
- if(d != null) {
- return d;
+ if (d != null) {
+ return d;
}
candidate = subCandidate;
}
return null;
}
- /** Returns the {@link DomainSuffix} corresponding to the
- * last public part of the hostname
+ /**
+ * Returns the {@link DomainSuffix} corresponding to the last public part of
+ * the hostname
*/
- public static DomainSuffix getDomainSuffix(String url) throws MalformedURLException {
+ public static DomainSuffix getDomainSuffix(String url)
+ throws MalformedURLException {
return getDomainSuffix(new URL(url));
}
- /** Partitions of the hostname of the url by "." */
+ /** Partitions of the hostname of the url by "." */
public static String[] getHostSegments(URL url) {
String host = url.getHost();
- //return whole hostname, if it is an ipv4
- //TODO : handle ipv6
- if(IP_PATTERN.matcher(host).matches())
- return new String[] {host};
+ // return whole hostname, if it is an ipv4
+ // TODO : handle ipv6
+ if (IP_PATTERN.matcher(host).matches())
+ return new String[] { host };
return host.split("\\.");
}
- /** Partitions of the hostname of the url by "."
- * @throws MalformedURLException */
- public static String[] getHostSegments(String url) throws MalformedURLException {
- return getHostSegments(new URL(url));
+ /**
+ * Partitions of the hostname of the url by "."
+ *
+ * @throws MalformedURLException
+ */
+ public static String[] getHostSegments(String url)
+ throws MalformedURLException {
+ return getHostSegments(new URL(url));
}
/**
- * <p>Given two urls, a src and a destination of a redirect, it returns the
- * representative url.<p>
+ * <p>
+ * Given two urls, a src and a destination of a redirect, it returns the
+ * representative url.
+ * <p>
*
- * <p>This method implements an extended version of the algorithm used by the
+ * <p>
+ * This method implements an extended version of the algorithm used by the
* Yahoo! Slurp crawler described here:<br>
* <a href=
* "http://help.yahoo.com/l/nz/yahooxtra/search/webcrawler/slurp-11.html"> How
@@ -230,46 +262,63 @@ public class URLUtil {
* <br>
* <ol>
* <li>Choose target url if either url is malformed.</li>
- * <li>If different domains the keep the destination whether or not the
+ * <li>If different domains the keep the destination whether or not the
* redirect is temp or perm</li>
- * <ul><li>a.com -> b.com*</li></ul>
+ * <ul>
+ * <li>a.com -> b.com*</li>
+ * </ul>
* <li>If the redirect is permanent and the source is root, keep the source.</li>
- * <ul><li>*a.com -> a.com?y=1 || *a.com -> a.com/xyz/index.html</li></ul>
- * <li>If the redirect is permanent and the source is not root and the
+ * <ul>
+ * <li>*a.com -> a.com?y=1 || *a.com -> a.com/xyz/index.html</li>
+ * </ul>
+ * <li>If the redirect is permanent and the source is not root and the
* destination is root, keep the destination</li>
- * <ul><li>a.com/xyz/index.html -> a.com*</li></ul>
+ * <ul>
+ * <li>a.com/xyz/index.html -> a.com*</li>
+ * </ul>
* <li>If the redirect is permanent and neither the source nor the destination
* is root, then keep the destination</li>
- * <ul><li>a.com/xyz/index.html -> a.com/abc/page.html*</li></ul>
+ * <ul>
+ * <li>a.com/xyz/index.html -> a.com/abc/page.html*</li>
+ * </ul>
* <li>If the redirect is temporary and source is root and destination is not
* root, then keep the source</li>
- * <ul><li>*a.com -> a.com/xyz/index.html</li></ul>
+ * <ul>
+ * <li>*a.com -> a.com/xyz/index.html</li>
+ * </ul>
* <li>If the redirect is temporary and source is not root and destination is
* root, then keep the destination</li>
- * <ul><li>a.com/xyz/index.html -> a.com*</li></ul>
+ * <ul>
+ * <li>a.com/xyz/index.html -> a.com*</li>
+ * </ul>
* <li>If the redirect is temporary and neither the source or the destination
- * is root, then keep the shortest url. First check for the shortest host,
- * and if both are equal then check by path. Path is first by length then by
- * the number of / path separators.</li>
+ * is root, then keep the shortest url. First check for the shortest host, and
+ * if both are equal then check by path. Path is first by length then by the
+ * number of / path separators.</li>
* <ul>
* <li>a.com/xyz/index.html -> a.com/abc/page.html*</li>
* <li>*www.a.com/xyz/index.html -> www.news.a.com/xyz/index.html</li>
* </ul>
* <li>If the redirect is temporary and both the source and the destination
* are root, then keep the shortest sub-domain</li>
- * <ul><li>*www.a.com -> www.news.a.com</li></ul>
+ * <ul>
+ * <li>*www.a.com -> www.news.a.com</li>
+ * </ul>
* <br>
- * While not in this logic there is a further piece of representative url
- * logic that occurs during indexing and after scoring. During creation of
- * the basic fields before indexing, if a url has a representative url stored
- * we check both the url and its representative url (which should never be
- * the same) against their linkrank scores and the highest scoring one is
- * kept as the url and the lower scoring one is held as the orig url inside
- * of the index.
+ * While not in this logic there is a further piece of representative url
+ * logic that occurs during indexing and after scoring. During creation of the
+ * basic fields before indexing, if a url has a representative url stored we
+ * check both the url and its representative url (which should never be the
+ * same) against their linkrank scores and the highest scoring one is kept as
+ * the url and the lower scoring one is held as the orig url inside of the
+ * index.
*
- * @param src The source url.
- * @param dst The destination url.
- * @param temp Is the redirect a temporary redirect.
+ * @param src
+ * The source url.
+ * @param dst
+ * The destination url.
+ * @param temp
+ * Is the redirect a temporary redirect.
*
* @return String The representative url.
*/
@@ -281,8 +330,7 @@ public class URLUtil {
try {
srcUrl = new URL(src);
dstUrl = new URL(dst);
- }
- catch (MalformedURLException e) {
+ } catch (MalformedURLException e) {
return dst;
}
@@ -300,27 +348,27 @@ public class URLUtil {
// 1) different domain them keep dest, temp or perm
// a.com -> b.com*
- //
+ //
// 2) permanent and root, keep src
// *a.com -> a.com?y=1 || *a.com -> a.com/xyz/index.html
- //
+ //
// 3) permanent and not root and dest root, keep dest
// a.com/xyz/index.html -> a.com*
- //
+ //
// 4) permanent and neither root keep dest
// a.com/xyz/index.html -> a.com/abc/page.html*
- //
+ //
// 5) temp and root and dest not root keep src
// *a.com -> a.com/xyz/index.html
- //
+ //
// 7) temp and not root and dest root keep dest
// a.com/xyz/index.html -> a.com*
- //
+ //
// 8) temp and neither root, keep shortest, if hosts equal by path else by
// hosts. paths are first by length then by number of / separators
// a.com/xyz/index.html -> a.com/abc/page.html*
// *www.a.com/xyz/index.html -> www.news.a.com/xyz/index.html
- //
+ //
// 9) temp and both root keep shortest sub domain
// *www.a.com -> www.news.a.com
@@ -332,39 +380,33 @@ public class URLUtil {
// if it is a permanent redirect
if (!temp) {
-
+
// if source is root return source, otherwise destination
if (srcRoot) {
return src;
- }
- else {
+ } else {
return dst;
}
- }
- else { // temporary redirect
+ } else { // temporary redirect
// source root and destination not root
if (srcRoot && !destRoot) {
return src;
- }
- else if (!srcRoot && destRoot) { // destination root and source not
+ } else if (!srcRoot && destRoot) { // destination root and source not
return dst;
- }
- else if (!srcRoot && !destRoot && (srcHost.equals(dstHost))) {
+ } else if (!srcRoot && !destRoot && (srcHost.equals(dstHost))) {
// source and destination hosts are the same, check paths, host length
int numSrcPaths = srcFile.split("/").length;
int numDstPaths = dstFile.split("/").length;
if (numSrcPaths != numDstPaths) {
return (numDstPaths < numSrcPaths ? dst : src);
- }
- else {
+ } else {
int srcPathLength = srcFile.length();
int dstPathLength = dstFile.length();
return (dstPathLength < srcPathLength ? dst : src);
}
- }
- else {
+ } else {
// different host names and both root take the shortest
int numSrcSubs = srcHost.split("\\.").length;
@@ -378,24 +420,25 @@ public class URLUtil {
* Returns the lowercased hostname for the url or null if the url is not well
* formed.
*
- * @param url The url to check.
+ * @param url
+ * The url to check.
* @return String The hostname for the url.
*/
public static String getHost(String url) {
try {
return new URL(url).getHost().toLowerCase();
- }
- catch (MalformedURLException e) {
+ } catch (MalformedURLException e) {
return null;
}
}
/**
- * Returns the page for the url. The page consists of the protocol, host,
- * and path, but does not include the query string. The host is lowercased
- * but the path is not.
+ * Returns the page for the url. The page consists of the protocol, host, and
+ * path, but does not include the query string. The host is lowercased but the
+ * path is not.
*
- * @param url The url to check.
+ * @param url
+ * The url to check.
* @return String The page for the url.
*/
public static String getPage(String url) {
@@ -404,12 +447,11 @@ public class URLUtil {
url = url.toLowerCase();
String queryStr = new URL(url).getQuery();
return (queryStr != null) ? url.replace("?" + queryStr, "") : url;
- }
- catch (MalformedURLException e) {
+ } catch (MalformedURLException e) {
return null;
}
}
-
+
public static String getProtocol(String url) {
try {
return getProtocol(new URL(url));
@@ -417,7 +459,7 @@ public class URLUtil {
return null;
}
}
-
+
public static String getProtocol(URL url) {
return url.getProtocol();
}
@@ -431,17 +473,11 @@ public class URLUtil {
// also do not add additional slashes for file: URLs (NUTCH-1880)
return url;
}
- URI p = new URI(u.getProtocol(),
- u.getUserInfo(),
- IDN.toASCII(host),
- u.getPort(),
- u.getPath(),
- u.getQuery(),
- u.getRef());
+ URI p = new URI(u.getProtocol(), u.getUserInfo(), IDN.toASCII(host),
+ u.getPort(), u.getPath(), u.getQuery(), u.getRef());
return p.toString();
- }
- catch (Exception e) {
+ } catch (Exception e) {
return null;
}
}
@@ -474,26 +510,23 @@ public class URLUtil {
}
return sb.toString();
- }
- catch (Exception e) {
+ } catch (Exception e) {
return null;
}
}
-
/** For testing */
- public static void main(String[] args){
-
- if(args.length!=1) {
+ public static void main(String[] args) {
+
+ if (args.length != 1) {
System.err.println("Usage : URLUtil <url>");
- return ;
+ return;
}
-
+
String url = args[0];
try {
System.out.println(URLUtil.getDomainName(new URL(url)));
- }
- catch (MalformedURLException ex) {
+ } catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
diff --git a/src/java/org/apache/nutch/util/domain/DomainStatistics.java b/src/java/org/apache/nutch/util/domain/DomainStatistics.java
index d4afd8a3c..b9bd21ff4 100644
--- a/src/java/org/apache/nutch/util/domain/DomainStatistics.java
+++ b/src/java/org/apache/nutch/util/domain/DomainStatistics.java
@@ -48,12 +48,15 @@ import org.apache.nutch.util.URLUtil;
*/
public class DomainStatistics extends Configured implements Tool {
- private static final Logger LOG = LoggerFactory.getLogger(DomainStatistics.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DomainStatistics.class);
private static final Text FETCHED_TEXT = new Text("FETCHED");
private static final Text NOT_FETCHED_TEXT = new Text("NOT_FETCHED");
- public static enum MyCounter {FETCHED, NOT_FETCHED, EMPTY_RESULT};
+ public static enum MyCounter {
+ FETCHED, NOT_FETCHED, EMPTY_RESULT
+ };
private static final int MODE_HOST = 1;
private static final int MODE_DOMAIN = 2;
@@ -64,7 +67,8 @@ public class DomainStatistics extends Configured implements Tool {
public int run(String[] args) throws Exception {
if (args.length < 3) {
- System.out.println("usage: DomainStatistics inputDirs outDir host|domain|suffix|tld [numOfReducer]");
+ System.out
+ .println("usage: DomainStatistics inputDirs outDir host|domain|suffix|tld [numOfReducer]");
return 1;
}
String inputDir = args[0];
@@ -81,16 +85,16 @@ public class DomainStatistics extends Configured implements Tool {
int mode = 0;
String jobName = "DomainStatistics";
- if(args[2].equals("host")) {
+ if (args[2].equals("host")) {
jobName = "Host statistics";
mode = MODE_HOST;
- } else if(args[2].equals("domain")) {
- jobName = "Domain statistics";
+ } else if (args[2].equals("domain")) {
+ jobName = "Domain statistics";
mode = MODE_DOMAIN;
- } else if(args[2].equals("suffix")) {
+ } else if (args[2].equals("suffix")) {
jobName = "Suffix statistics";
mode = MODE_SUFFIX;
- } else if(args[2].equals("tld")) {
+ } else if (args[2].equals("tld")) {
jobName = "TLD statistics";
mode = MODE_TLD;
}
@@ -128,59 +132,65 @@ public class DomainStatistics extends Configured implements Tool {
}
long end = System.currentTimeMillis();
- LOG.info("DomainStatistics: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end));
+ LOG.info("DomainStatistics: finished at " + sdf.format(end) + ", elapsed: "
+ + TimingUtil.elapsedTime(start, end));
return 0;
}
- static class DomainStatisticsMapper extends Mapper<Text, CrawlDatum, Text, LongWritable> {
+ static class DomainStatisticsMapper extends
+ Mapper<Text, CrawlDatum, Text, LongWritable> {
int mode = 0;
public void setup(Context context) {
- mode = context.getConfiguration().getInt("domain.statistics.mode", MODE_DOMAIN);
+ mode = context.getConfiguration().getInt("domain.statistics.mode",
+ MODE_DOMAIN);
}
- public void map(Text urlText, CrawlDatum datum, Context context) throws IOException, InterruptedException {
+ public void map(Text urlText, CrawlDatum datum, Context context)
+ throws IOException, InterruptedException {
- if(datum.getStatus() == CrawlDatum.STATUS_DB_FETCHED
+ if (datum.getStatus() == CrawlDatum.STATUS_DB_FETCHED
|| datum.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
try {
URL url = new URL(urlText.toString());
String out = null;
switch (mode) {
- case MODE_HOST:
- out = url.getHost();
- break;
- case MODE_DOMAIN:
- out = URLUtil.getDomainName(url);
- break;
- case MODE_SUFFIX:
- out = URLUtil.getDomainSuffix(url).getDomain();
- break;
- case MODE_TLD:
- out = URLUtil.getTopLevelDomainName(url);
- break;
+ case MODE_HOST:
+ out = url.getHost();
+ break;
+ case MODE_DOMAIN:
+ out = URLUtil.getDomainName(url);
+ break;
+ case MODE_SUFFIX:
+ out = URLUtil.getDomainSuffix(url).getDomain();
+ break;
+ case MODE_TLD:
+ out = URLUtil.getTopLevelDomainName(url);
+ break;
}
- if(out.trim().equals("")) {
+ if (out.trim().equals("")) {
LOG.info("url : " + url);
context.getCounter(MyCounter.EMPTY_RESULT).increment(1);
}
context.write(new Text(out), new LongWritable(1));
- } catch (Exception ex) { }
+ } catch (Exception ex) {
+ }
context.getCounter(MyCounter.FETCHED).increment(1);
context.write(FETCHED_TEXT, new LongWritable(1));
- }
- else {
+ } else {
context.getCounter(MyCounter.NOT_FETCHED).increment(1);
context.write(NOT_FETCHED_TEXT, new LongWritable(1));
}
}
}
- static class DomainStatisticsReducer extends Reducer <Text, LongWritable, LongWritable, Text> {
- public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
+ static class DomainStatisticsReducer extends
+ Reducer<Text, LongWritable, LongWritable, Text> {
+ public void reduce(Text key, Iterable<LongWritable> values, Context context)
+ throws IOException, InterruptedException {
long total = 0;
for (LongWritable val : values) {
@@ -191,8 +201,10 @@ public class DomainStatistics extends Configured implements Tool {
}
}
- public static class DomainStatisticsCombiner extends Reducer <Text, LongWritable, Text, LongWritable> {
- public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
+ public static class DomainStatisticsCombiner extends
+ Reducer<Text, LongWritable, Text, LongWritable> {
+ public void reduce(Text key, Iterable<LongWritable> values, Context context)
+ throws IOException, InterruptedException {
long total = 0;
for (LongWritable val : values) {
diff --git a/src/java/org/apache/nutch/util/domain/DomainSuffix.java b/src/java/org/apache/nutch/util/domain/DomainSuffix.java
index 31295ded2..d40ebe941 100644
--- a/src/java/org/apache/nutch/util/domain/DomainSuffix.java
+++ b/src/java/org/apache/nutch/util/domain/DomainSuffix.java
@@ -18,29 +18,29 @@
package org.apache.nutch.util.domain;
/**
- * This class represents the last part of the host name,
- * which is operated by authoritives, not individuals. This information
- * is needed to find the domain name of a host. The domain name of a host
- * is defined to be the last part before the domain suffix, w/o subdomain
- * names. As an example the domain name of <br><code> http://lucene.apache.org/
- * </code><br> is <code> apache.org</code>
- * <br>
- * This class holds three fields,
- * <strong>domain</strong> field represents the suffix (such as "co.uk")
- * <strong>boost</strong> is a float for boosting score of url's with this suffix
- * <strong>status</strong> field represents domain's status
+ * This class represents the last part of the host name, which is operated by
+ * authoritives, not individuals. This information is needed to find the domain
+ * name of a host. The domain name of a host is defined to be the last part
+ * before the domain suffix, w/o subdomain names. As an example the domain name
+ * of <br>
+ * <code> http://lucene.apache.org/
+ * </code><br>
+ * is <code> apache.org</code> <br>
+ * This class holds three fields, <strong>domain</strong> field represents the
+ * suffix (such as "co.uk") <strong>boost</strong> is a float for boosting score
+ * of url's with this suffix <strong>status</strong> field represents domain's
+ * status
*
* @author Enis Soztutar &lt;[email protected]&gt;
- * @see TopLevelDomain
- * for info please see conf/domain-suffixes.xml
+ * @see TopLevelDomain for info please see conf/domain-suffixes.xml
*/
public class DomainSuffix {
/**
- * Enumeration of the status of the tld. Please see domain-suffixes.xml.
+ * Enumeration of the status of the tld. Please see domain-suffixes.xml.
*/
- public enum Status { INFRASTRUCTURE, SPONSORED, UNSPONSORED
- , STARTUP, PROPOSED, DELETED, PSEUDO_DOMAIN, DEPRECATED, IN_USE, NOT_IN_USE, REJECTED
+ public enum Status {
+ INFRASTRUCTURE, SPONSORED, UNSPONSORED, STARTUP, PROPOSED, DELETED, PSEUDO_DOMAIN, DEPRECATED, IN_USE, NOT_IN_USE, REJECTED
};
private String domain;
@@ -49,7 +49,7 @@ public class DomainSuffix {
public static final float DEFAULT_BOOST = 1.0f;
public static final Status DEFAULT_STATUS = Status.IN_USE;
-
+
public DomainSuffix(String domain, Status status, float boost) {
this.domain = domain;
this.status = status;
@@ -59,7 +59,7 @@ public class DomainSuffix {
public DomainSuffix(String domain) {
this(domain, DEFAULT_STATUS, DEFAULT_BOOST);
}
-
+
public String getDomain() {
return domain;
}
@@ -71,7 +71,7 @@ public class DomainSuffix {
public float getBoost() {
return boost;
}
-
+
@Override
public String toString() {
return domain;
diff --git a/src/java/org/apache/nutch/util/domain/DomainSuffixes.java b/src/java/org/apache/nutch/util/domain/DomainSuffixes.java
index 7c6c8e502..765457e90 100644
--- a/src/java/org/apache/nutch/util/domain/DomainSuffixes.java
+++ b/src/java/org/apache/nutch/util/domain/DomainSuffixes.java
@@ -25,57 +25,62 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.util.StringUtils;
/**
- * Storage class for <code>DomainSuffix</code> objects
- * Note: this class is singleton
+ * Storage class for <code>DomainSuffix</code> objects Note: this class is
+ * singleton
+ *
* @author Enis Soztutar &lt;[email protected]&gt;
*/
public class DomainSuffixes {
- private static final Logger LOG = LoggerFactory.getLogger(DomainSuffixes.class);
-
- private HashMap<String, DomainSuffix> domains = new HashMap<String, DomainSuffix>();
-
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DomainSuffixes.class);
+
+ private HashMap<String, DomainSuffix> domains = new HashMap<String, DomainSuffix>();
+
private static DomainSuffixes instance;
-
+
/** private ctor */
private DomainSuffixes() {
String file = "domain-suffixes.xml";
- InputStream input = this.getClass().getClassLoader().getResourceAsStream(file);
+ InputStream input = this.getClass().getClassLoader()
+ .getResourceAsStream(file);
try {
new DomainSuffixesReader().read(this, input);
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
LOG.warn(StringUtils.stringifyException(ex));
}
}
-
+
/**
* Singleton instance, lazy instantination
- * @return returns the domain suffix instance
+ *
+ * @return returns the domain suffix instance
*/
public static DomainSuffixes getInstance() {
- if(instance == null) {
+ if (instance == null) {
instance = new DomainSuffixes();
}
return instance;
}
-
+
void addDomainSuffix(DomainSuffix tld) {
domains.put(tld.getDomain(), tld);
}
/** return whether the extension is a registered domain entry */
public boolean isDomainSuffix(String extension) {
- return domains.containsKey(extension);
+ return domains.containsKey(extension);
}
-
+
/**
- * Return the {@link DomainSuffix} object for the extension, if
- * extension is a top level domain returned object will be an
- * instance of {@link TopLevelDomain}
- * @param extension of the domain
+ * Return the {@link DomainSuffix} object for the extension, if extension is a
+ * top level domain returned object will be an instance of
+ * {@link TopLevelDomain}
+ *
+ * @param extension
+ * of the domain
*/
public DomainSuffix get(String extension) {
return domains.get(extension);
}
-
+
}
diff --git a/src/java/org/apache/nutch/util/domain/DomainSuffixesReader.java b/src/java/org/apache/nutch/util/domain/DomainSuffixesReader.java
index ffe7a1a0f..a2a60e2b7 100644
--- a/src/java/org/apache/nutch/util/domain/DomainSuffixesReader.java
+++ b/src/java/org/apache/nutch/util/domain/DomainSuffixesReader.java
@@ -36,16 +36,17 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
- * For parsing xml files containing domain suffix definitions.
- * Parsed xml files should validate against
- * <code>domain-suffixes.xsd</code>
+ * For parsing xml files containing domain suffix definitions. Parsed xml files
+ * should validate against <code>domain-suffixes.xsd</code>
+ *
* @author Enis Soztutar &lt;[email protected]&gt;
*/
class DomainSuffixesReader {
- private static final Logger LOG = LoggerFactory.getLogger(DomainSuffixesReader.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DomainSuffixesReader.class);
- void read(DomainSuffixes tldEntries, InputStream input) throws IOException{
+ void read(DomainSuffixes tldEntries, InputStream input) throws IOException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
@@ -54,28 +55,29 @@ class DomainSuffixesReader {
Document document = builder.parse(new InputSource(input));
Element root = document.getDocumentElement();
-
- if(root != null && root.getTagName().equals("domains")) {
-
- Element tlds = (Element)root.getElementsByTagName("tlds").item(0);
- Element suffixes = (Element)root.getElementsByTagName("suffixes").item(0);
-
- //read tlds
- readITLDs(tldEntries, (Element)tlds.getElementsByTagName("itlds").item(0));
- readGTLDs(tldEntries, (Element)tlds.getElementsByTagName("gtlds").item(0));
- readCCTLDs(tldEntries, (Element)tlds.getElementsByTagName("cctlds").item(0));
-
+
+ if (root != null && root.getTagName().equals("domains")) {
+
+ Element tlds = (Element) root.getElementsByTagName("tlds").item(0);
+ Element suffixes = (Element) root.getElementsByTagName("suffixes")
+ .item(0);
+
+ // read tlds
+ readITLDs(tldEntries, (Element) tlds.getElementsByTagName("itlds")
+ .item(0));
+ readGTLDs(tldEntries, (Element) tlds.getElementsByTagName("gtlds")
+ .item(0));
+ readCCTLDs(tldEntries, (Element) tlds.getElementsByTagName("cctlds")
+ .item(0));
+
readSuffixes(tldEntries, suffixes);
- }
- else {
+ } else {
throw new IOException("xml file is not valid");
}
- }
- catch (ParserConfigurationException ex) {
+ } catch (ParserConfigurationException ex) {
LOG.warn(StringUtils.stringifyException(ex));
throw new IOException(ex.getMessage());
- }
- catch (SAXException ex) {
+ } catch (SAXException ex) {
LOG.warn(StringUtils.stringifyException(ex));
throw new IOException(ex.getMessage());
}
@@ -83,22 +85,24 @@ class DomainSuffixesReader {
void readITLDs(DomainSuffixes tldEntries, Element el) {
NodeList children = el.getElementsByTagName("tld");
- for(int i=0;i<children.getLength();i++) {
- tldEntries.addDomainSuffix(readGTLD((Element)children.item(i), Type.INFRASTRUCTURE));
+ for (int i = 0; i < children.getLength(); i++) {
+ tldEntries.addDomainSuffix(readGTLD((Element) children.item(i),
+ Type.INFRASTRUCTURE));
}
}
-
+
void readGTLDs(DomainSuffixes tldEntries, Element el) {
NodeList children = el.getElementsByTagName("tld");
- for(int i=0;i<children.getLength();i++) {
- tldEntries.addDomainSuffix(readGTLD((Element)children.item(i), Type.GENERIC));
+ for (int i = 0; i < children.getLength(); i++) {
+ tldEntries.addDomainSuffix(readGTLD((Element) children.item(i),
+ Type.GENERIC));
}
}
void readCCTLDs(DomainSuffixes tldEntries, Element el) throws IOException {
NodeList children = el.getElementsByTagName("tld");
- for(int i=0;i<children.getLength();i++) {
- tldEntries.addDomainSuffix(readCCTLD((Element)children.item(i)));
+ for (int i = 0; i < children.getLength(); i++) {
+ tldEntries.addDomainSuffix(readCCTLD((Element) children.item(i)));
}
}
@@ -113,39 +117,40 @@ class DomainSuffixesReader {
String domain = el.getAttribute("domain");
Status status = readStatus(el);
float boost = readBoost(el);
- String countryName = readCountryName(el);
- return new TopLevelDomain(domain, status, boost, countryName);
+ String countryName = readCountryName(el);
+ return new TopLevelDomain(domain, status, boost, countryName);
}
-
+
/** read optional field status */
Status readStatus(Element el) {
NodeList list = el.getElementsByTagName("status");
- if(list == null || list.getLength() == 0)
+ if (list == null || list.getLength() == 0)
return DomainSuffix.DEFAULT_STATUS;
return Status.valueOf(list.item(0).getFirstChild().getNodeValue());
}
-
+
/** read optional field boost */
float readBoost(Element el) {
NodeList list = el.getElementsByTagName("boost");
- if(list == null || list.getLength() == 0)
+ if (list == null || list.getLength() == 0)
return DomainSuffix.DEFAULT_BOOST;
return Float.parseFloat(list.item(0).getFirstChild().getNodeValue());
}
-
- /** read field countryname
- */
+
+ /**
+ * read field countryname
+ */
String readCountryName(Element el) throws IOException {
NodeList list = el.getElementsByTagName("country");
- if(list == null || list.getLength() == 0)
+ if (list == null || list.getLength() == 0)
throw new IOException("Country name should be given");
return list.item(0).getNodeValue();
}
-
+
void readSuffixes(DomainSuffixes tldEntries, Element el) {
NodeList children = el.getElementsByTagName("suffix");
- for(int i=0;i<children.getLength();i++) {
- tldEntries.addDomainSuffix(readSuffix((Element)children.item(i)));
+ for (int i = 0; i < children.getLength(); i++) {
+ tldEntries.addDomainSuffix(readSuffix((Element) children.item(i)));
}
}
@@ -155,5 +160,5 @@ class DomainSuffixesReader {
float boost = readBoost(el);
return new DomainSuffix(domain, status, boost);
}
-
+
}
diff --git a/src/java/org/apache/nutch/util/domain/TopLevelDomain.java b/src/java/org/apache/nutch/util/domain/TopLevelDomain.java
index fdaf40349..f442d1f21 100644
--- a/src/java/org/apache/nutch/util/domain/TopLevelDomain.java
+++ b/src/java/org/apache/nutch/util/domain/TopLevelDomain.java
@@ -18,44 +18,50 @@
package org.apache.nutch.util.domain;
/**
- * (From wikipedia) A top-level domain (TLD) is the last part of an
- * Internet domain name; that is, the letters which follow the final
- * dot of any domain name. For example, in the domain name
- * <code>www.website.com</code>, the top-level domain is <code>com</code>.
- *
+ * (From wikipedia) A top-level domain (TLD) is the last part of an Internet
+ * domain name; that is, the letters which follow the final dot of any domain
+ * name. For example, in the domain name <code>www.website.com</code>, the
+ * top-level domain is <code>com</code>.
+ *
* @author Enis Soztutar &lt;[email protected]&gt;
*
* @see <a href="http://www.iana.org/"> iana.org</a>
*
- * @see <a href="http://en.wikipedia.org/wiki/Top-level_domain"> Top-level_domain</a>
+ * @see <a href="http://en.wikipedia.org/wiki/Top-level_domain">
+ * Top-level_domain</a>
*/
public class TopLevelDomain extends DomainSuffix {
- public enum Type { INFRASTRUCTURE, GENERIC, COUNTRY };
-
+ public enum Type {
+ INFRASTRUCTURE, GENERIC, COUNTRY
+ };
+
private Type type;
private String countryName = null;
-
- public TopLevelDomain(String domain, Type type, Status status, float boost){
+
+ public TopLevelDomain(String domain, Type type, Status status, float boost) {
super(domain, status, boost);
this.type = type;
}
- public TopLevelDomain(String domain, Status status, float boost, String countryName){
+ public TopLevelDomain(String domain, Status status, float boost,
+ String countryName) {
super(domain, status, boost);
this.type = Type.COUNTRY;
this.countryName = countryName;
}
-
+
public Type getType() {
return type;
}
- /** Returns the country name if TLD is Country Code TLD
+ /**
+ * Returns the country name if TLD is Country Code TLD
+ *
* @return country name or null
- */
- public String getCountryName(){
+ */
+ public String getCountryName() {
return countryName;
}
-
+
}
diff --git a/src/java/org/apache/nutch/util/package-info.java b/src/java/org/apache/nutch/util/package-info.java
index a10390437..053dbc192 100644
--- a/src/java/org/apache/nutch/util/package-info.java
+++ b/src/java/org/apache/nutch/util/package-info.java
@@ -19,3 +19,4 @@
* Miscellaneous utility classes.
*/
package org.apache.nutch.util;
+
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 d9337355a..e7c55c4fd 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
@@ -41,16 +41,17 @@ import java.net.MalformedURLException;
/** Adds basic searchable fields to a document. */
public class CCIndexingFilter implements IndexingFilter {
- public static final Logger LOG = LoggerFactory.getLogger(CCIndexingFilter.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(CCIndexingFilter.class);
/** The name of the document field we use. */
public static String FIELD = "cc";
private Configuration conf;
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks)
- throws IndexingException {
-
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
+
Metadata metadata = parse.getData().getParseMeta();
// index the license
String licenseUrl = metadata.get(CreativeCommons.LICENSE_URL);
@@ -81,9 +82,11 @@ public class CCIndexingFilter implements IndexingFilter {
return doc;
}
- /** Add the features represented by a license URL. Urls are of the form
+ /**
+ * Add the features represented by a license URL. Urls are of the form
* "http://creativecommons.org/licenses/xx-xx/xx/xx", where "xx" names a
- * license feature. */
+ * license feature.
+ */
public void addUrlFeatures(NutchDocument doc, String urlString) {
try {
URL url = new URL(urlString);
@@ -92,7 +95,7 @@ public class CCIndexingFilter implements IndexingFilter {
StringTokenizer names = new StringTokenizer(url.getPath(), "/-");
if (names.hasMoreTokens())
- names.nextToken(); // throw away "licenses"
+ names.nextToken(); // throw away "licenses"
// add a feature per component after "licenses"
while (names.hasMoreTokens()) {
@@ -105,7 +108,7 @@ public class CCIndexingFilter implements IndexingFilter {
}
}
}
-
+
private void addFeature(NutchDocument doc, String feature) {
doc.add(FIELD, feature);
}
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 0b2141512..1fa951e54 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
@@ -33,27 +33,25 @@ import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
-
/** Adds metadata identifying the Creative Commons license used, if any. */
public class CCParseFilter implements HtmlParseFilter {
public static final Logger LOG = LoggerFactory.getLogger(CCParseFilter.class);
-
- /** Walks DOM tree, looking for RDF in comments and licenses in anchors.*/
+ /** Walks DOM tree, looking for RDF in comments and licenses in anchors. */
public static class Walker {
- private URL base; // base url of page
- private String rdfLicense; // subject url found, if any
- private URL relLicense; // license url found, if any
- private URL anchorLicense; // anchor url found, if any
- private String workType; // work type URI
+ private URL base; // base url of page
+ private String rdfLicense; // subject url found, if any
+ private URL relLicense; // license url found, if any
+ private URL anchorLicense; // anchor url found, if any
+ private String workType; // work type URI
private Walker(URL base) {
this.base = base;
}
- /** Scan the document adding attributes to metadata.*/
- public static void walk(Node doc, URL base, Metadata metadata, Configuration conf)
- throws ParseException {
+ /** Scan the document adding attributes to metadata. */
+ public static void walk(Node doc, URL base, Metadata metadata,
+ Configuration conf) throws ParseException {
// walk the DOM tree, scanning for license data
Walker walker = new Walker(base);
@@ -62,13 +60,13 @@ public class CCParseFilter implements HtmlParseFilter {
// interpret results of walk
String licenseUrl = null;
String licenseLocation = null;
- if (walker.rdfLicense != null) { // 1st choice: subject in RDF
+ if (walker.rdfLicense != null) { // 1st choice: subject in RDF
licenseLocation = "rdf";
licenseUrl = walker.rdfLicense;
- } else if (walker.relLicense != null) { // 2nd: anchor w/ rel=license
+ } else if (walker.relLicense != null) { // 2nd: anchor w/ rel=license
licenseLocation = "rel";
licenseUrl = walker.relLicense.toString();
- } else if (walker.anchorLicense != null) { // 3rd: anchor w/ CC license
+ } else if (walker.anchorLicense != null) { // 3rd: anchor w/ CC license
licenseLocation = "a";
licenseUrl = walker.anchorLicense.toString();
} else if (conf.getBoolean("creativecommons.exclude.unlicensed", false)) {
@@ -78,7 +76,8 @@ public class CCParseFilter implements HtmlParseFilter {
// add license to metadata
if (licenseUrl != null) {
if (LOG.isInfoEnabled()) {
- LOG.info("CC: found "+licenseUrl+" in "+licenseLocation+" of "+base);
+ LOG.info("CC: found " + licenseUrl + " in " + licenseLocation
+ + " of " + base);
}
metadata.add(CreativeCommons.LICENSE_URL, licenseUrl);
metadata.add(CreativeCommons.LICENSE_LOCATION, licenseLocation);
@@ -86,36 +85,38 @@ public class CCParseFilter implements HtmlParseFilter {
if (walker.workType != null) {
if (LOG.isInfoEnabled()) {
- LOG.info("CC: found "+walker.workType+" in "+base);
+ LOG.info("CC: found " + walker.workType + " in " + base);
}
metadata.add(CreativeCommons.WORK_TYPE, walker.workType);
}
}
- /** Scan the document looking for RDF in comments and license elements.*/
+ /** Scan the document looking for RDF in comments and license elements. */
private void walk(Node node) {
-
+
// check element nodes for license URL
if (node instanceof Element) {
- findLicenseUrl((Element)node);
+ findLicenseUrl((Element) node);
}
// check comment nodes for license RDF
if (node instanceof Comment) {
- findRdf(((Comment)node).getData());
+ findRdf(((Comment) node).getData());
}
// recursively walk child nodes
NodeList children = node.getChildNodes();
- for (int i = 0; children != null && i < children.getLength(); i++ ) {
+ for (int i = 0; children != null && i < children.getLength(); i++) {
walk(children.item(i));
}
}
- /** Extract license url from element, if any. Thse are the href attribute
- * of anchor elements with rel="license". These must also point to
- * http://creativecommons.org/licenses/. */
+ /**
+ * Extract license url from element, if any. Thse are the href attribute of
+ * anchor elements with rel="license". These must also point to
+ * http://creativecommons.org/licenses/.
+ */
private void findLicenseUrl(Element element) {
// only look in Anchor elements
if (!"a".equalsIgnoreCase(element.getTagName()))
@@ -125,54 +126,52 @@ public class CCParseFilter implements HtmlParseFilter {
String href = element.getAttribute("href");
if (href == null)
return;
-
+
try {
- URL url = new URL(base, href); // resolve the url
+ URL url = new URL(base, href); // resolve the url
// check that it's a CC license URL
- if ("http".equalsIgnoreCase(url.getProtocol()) &&
- "creativecommons.org".equalsIgnoreCase(url.getHost()) &&
- url.getPath() != null &&
- url.getPath().startsWith("/licenses/") &&
- url.getPath().length() > "/licenses/".length()) {
+ if ("http".equalsIgnoreCase(url.getProtocol())
+ && "creativecommons.org".equalsIgnoreCase(url.getHost())
+ && url.getPath() != null && url.getPath().startsWith("/licenses/")
+ && url.getPath().length() > "/licenses/".length()) {
// check rel="license"
String rel = element.getAttribute("rel");
if (rel != null && "license".equals(rel) && this.relLicense == null) {
- this.relLicense = url; // found rel license
+ this.relLicense = url; // found rel license
} else if (this.anchorLicense == null) {
- this.anchorLicense = url; // found anchor license
+ this.anchorLicense = url; // found anchor license
}
}
- } catch (MalformedURLException e) { // ignore malformed urls
+ } catch (MalformedURLException e) { // ignore malformed urls
}
}
- /** Configure a namespace aware XML parser. */
- private static final DocumentBuilderFactory FACTORY
- = DocumentBuilderFactory.newInstance();
+ /** Configure a namespace aware XML parser. */
+ private static final DocumentBuilderFactory FACTORY = DocumentBuilderFactory
+ .newInstance();
static {
FACTORY.setNamespaceAware(true);
}
/** Creative Commons' namespace URI. */
private static final String CC_NS = "http://web.resource.org/cc/";
-
+
/** Dublin Core namespace URI. */
private static final String DC_NS = "http://purl.org/dc/elements/1.1/";
-
+
/** RDF syntax namespace URI. */
- private static final String RDF_NS
- = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+ private static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
private void findRdf(String comment) {
// first check for likely RDF in comment
int rdfPosition = comment.indexOf("RDF");
if (rdfPosition < 0)
- return; // no RDF, abort
+ return; // no RDF, abort
int nsPosition = comment.indexOf(CC_NS);
if (nsPosition < 0)
- return; // no RDF, abort
+ return; // no RDF, abort
// try to parse the XML
Document doc;
@@ -181,28 +180,30 @@ public class CCParseFilter implements HtmlParseFilter {
doc = parser.parse(new InputSource(new StringReader(comment)));
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("CC: Failed to parse RDF in "+base+": "+e);
+ LOG.warn("CC: Failed to parse RDF in " + base + ": " + e);
}
- //e.printStackTrace();
+ // e.printStackTrace();
return;
}
// check that root is rdf:RDF
NodeList roots = doc.getElementsByTagNameNS(RDF_NS, "RDF");
if (roots.getLength() != 1) {
- if (LOG.isWarnEnabled()) { LOG.warn("CC: No RDF root in "+base); }
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("CC: No RDF root in " + base);
+ }
return;
}
- Element rdf = (Element)roots.item(0);
+ Element rdf = (Element) roots.item(0);
// get cc:License nodes inside rdf:RDF
NodeList licenses = rdf.getElementsByTagNameNS(CC_NS, "License");
for (int i = 0; i < licenses.getLength(); i++) {
- Element l = (Element)licenses.item(i);
+ Element l = (Element) licenses.item(i);
// license is rdf:about= attribute from cc:License
- this.rdfLicense = l.getAttributeNodeNS(RDF_NS,"about").getValue();
+ this.rdfLicense = l.getAttributeNodeNS(RDF_NS, "about").getValue();
// walk predicates of cc:License
NodeList predicates = l.getChildNodes();
@@ -210,17 +211,17 @@ public class CCParseFilter implements HtmlParseFilter {
Node predicateNode = predicates.item(j);
if (!(predicateNode instanceof Element))
continue;
- Element predicateElement = (Element)predicateNode;
+ Element predicateElement = (Element) predicateNode;
// extract predicates of cc:xxx predicates
if (!CC_NS.equals(predicateElement.getNamespaceURI())) {
continue;
}
-
+
// add object and predicate to metadata
// metadata.put(object, predicate);
// if (LOG.isInfoEnabled()) {
- // LOG.info("CC: found: "+predicate+"="+object);
+ // LOG.info("CC: found: "+predicate+"="+object);
// }
}
}
@@ -230,10 +231,11 @@ public class CCParseFilter implements HtmlParseFilter {
for (int i = 0; i < works.getLength(); i++) {
// get dc:type nodes from cc:Work
NodeList types = rdf.getElementsByTagNameNS(DC_NS, "type");
-
+
for (int j = 0; j < types.getLength(); j++) {
- Element type = (Element)types.item(j);
- String workUri = type.getAttributeNodeNS(RDF_NS, "resource").getValue();
+ Element type = (Element) types.item(j);
+ String workUri = type.getAttributeNodeNS(RDF_NS, "resource")
+ .getValue();
this.workType = WORK_TYPE_NAMES.get(workUri);
}
}
@@ -246,16 +248,20 @@ public class CCParseFilter implements HtmlParseFilter {
WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/StillImage", "image");
WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Sound", "audio");
WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Text", "text");
- WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Interactive", "interactive");
+ WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Interactive",
+ "interactive");
WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Software", "software");
WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Image", "image");
}
private Configuration conf;
- /** Adds metadata or otherwise modifies a parse of an HTML document, given
- * the DOM tree of a page. */
- public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) {
+ /**
+ * Adds metadata or otherwise modifies a parse of an HTML document, given the
+ * DOM tree of a page.
+ */
+ public ParseResult filter(Content content, ParseResult parseResult,
+ HTMLMetaTags metaTags, DocumentFragment doc) {
// get parse obj
Parse parse = parseResult.get(content.getUrl());
@@ -266,9 +272,8 @@ public class CCParseFilter implements HtmlParseFilter {
base = new URL(content.getBaseUrl());
} catch (MalformedURLException e) {
Parse emptyParse = new ParseStatus(e).getEmptyParse(getConf());
- parseResult.put(content.getUrl(),
- new ParseText(emptyParse.getText()),
- emptyParse.getData());
+ parseResult.put(content.getUrl(), new ParseText(emptyParse.getText()),
+ emptyParse.getData());
return parseResult;
}
@@ -277,9 +282,8 @@ public class CCParseFilter implements HtmlParseFilter {
Walker.walk(doc, base, parse.getData().getParseMeta(), getConf());
} catch (ParseException e) {
Parse emptyParse = new ParseStatus(e).getEmptyParse(getConf());
- parseResult.put(content.getUrl(),
- new ParseText(emptyParse.getText()),
- emptyParse.getData());
+ parseResult.put(content.getUrl(), new ParseText(emptyParse.getText()),
+ emptyParse.getData());
return parseResult;
}
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 253f6e8e9..41be9edba 100755
--- a/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java
+++ b/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java
@@ -30,30 +30,28 @@ import java.io.*;
public class TestCCParseFilter {
- private static final File testDir =
- new File(System.getProperty("test.input"));
+ private static final File testDir = new File(System.getProperty("test.input"));
@Test
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);
+ "http://creativecommons.org/licenses/by-nc-sa/1.0", "a", null);
// Tika returns <a> whereas parse-html returns <rel>
// check later
pageTest(new File(testDir, "rel.html"), "http://foo.com/",
- "http://creativecommons.org/licenses/by-nc/2.0", "rel", null);
+ "http://creativecommons.org/licenses/by-nc/2.0", "rel", null);
// Tika returns <a> whereas parse-html returns <rdf>
// check later
pageTest(new File(testDir, "rdf.html"), "http://foo.com/",
- "http://creativecommons.org/licenses/by-nc/1.0", "rdf", "text");
+ "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 {
+ 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());
+ ByteArrayOutputStream out = new ByteArrayOutputStream((int) file.length());
byte[] buffer = new byte[1024];
int i;
while ((i = in.read(buffer)) != -1) {
@@ -63,14 +61,13 @@ public class TestCCParseFilter {
byte[] bytes = out.toByteArray();
Configuration conf = NutchConfiguration.create();
- Content content =
- new Content(url, url, bytes, contentType, new Metadata(), conf);
- Parse parse = new ParseUtil(conf).parse(content).get(content.getUrl());
-
+ Content content = new Content(url, url, bytes, contentType, new Metadata(),
+ conf);
+ Parse parse = new ParseUtil(conf).parse(content).get(content.getUrl());
+
Metadata metadata = parse.getData().getParseMeta();
Assert.assertEquals(license, metadata.get("License-Url"));
Assert.assertEquals(location, metadata.get("License-Location"));
Assert.assertEquals(type, metadata.get("Work-Type"));
}
}
-
diff --git a/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/FeedIndexingFilter.java b/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/FeedIndexingFilter.java
index 613562a47..94b440a89 100644
--- a/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/FeedIndexingFilter.java
+++ b/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/FeedIndexingFilter.java
@@ -38,78 +38,77 @@ import org.apache.nutch.parse.ParseData;
* @author mattmann
* @since NUTCH-444
*
- * An {@link IndexingFilter} implementation to pull out the
- * relevant extracted {@link Metadata} fields from the RSS feeds
- * and into the index.
- *
+ * An {@link IndexingFilter} implementation to pull out the relevant
+ * extracted {@link Metadata} fields from the RSS feeds and into the
+ * index.
+ *
*/
public class FeedIndexingFilter implements IndexingFilter {
-
+
public static final String dateFormatStr = "yyyyMMddHHmm";
-
+
private Configuration conf;
-
+
private final static String PUBLISHED_DATE = "publishedDate";
-
+
private final static String UPDATED_DATE = "updatedDate";
-
+
/**
* Extracts out the relevant fields:
*
* <ul>
- * <li>FEED_AUTHOR</li>
- * <li>FEED_TAGS</li>
- * <li>FEED_PUBLISHED</li>
- * <li>FEED_UPDATED</li>
- * <li>FEED</li>
+ * <li>FEED_AUTHOR</li>
+ * <li>FEED_TAGS</li>
+ * <li>FEED_PUBLISHED</li>
+ * <li>FEED_UPDATED</li>
+ * <li>FEED</li>
* </ul>
*
- * And sends them to the {@link Indexer} for indexing within the Nutch
- * index.
- *
+ * And sends them to the {@link Indexer} for indexing within the Nutch index.
+ *
*/
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum,
- Inlinks inlinks) throws IndexingException {
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
ParseData parseData = parse.getData();
Metadata parseMeta = parseData.getParseMeta();
-
+
String[] authors = parseMeta.getValues(Feed.FEED_AUTHOR);
String[] tags = parseMeta.getValues(Feed.FEED_TAGS);
String published = parseMeta.get(Feed.FEED_PUBLISHED);
String updated = parseMeta.get(Feed.FEED_UPDATED);
String feed = parseMeta.get(Feed.FEED);
-
+
if (authors != null) {
for (String author : authors) {
doc.add(Feed.FEED_AUTHOR, author);
}
}
-
+
if (tags != null) {
for (String tag : tags) {
doc.add(Feed.FEED_TAGS, tag);
}
}
-
+
if (feed != null)
doc.add(Feed.FEED, feed);
-
+
if (published != null) {
Date date = new Date(Long.parseLong(published));
doc.add(PUBLISHED_DATE, date);
}
-
+
if (updated != null) {
Date date = new Date(Long.parseLong(updated));
doc.add(UPDATED_DATE, date);
}
-
+
return doc;
}
/**
- * @return the {@link Configuration} object used to configure
- * this {@link IndexingFilter}.
+ * @return the {@link Configuration} object used to configure this
+ * {@link IndexingFilter}.
*/
public Configuration getConf() {
return conf;
@@ -119,8 +118,9 @@ public class FeedIndexingFilter implements IndexingFilter {
* Sets the {@link Configuration} object used to configure this
* {@link IndexingFilter}.
*
- * @param conf The {@link Configuration} object used to configure
- * this {@link IndexingFilter}.
+ * @param conf
+ * The {@link Configuration} object used to configure this
+ * {@link IndexingFilter}.
*/
public void setConf(Configuration conf) {
this.conf = conf;
diff --git a/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/package-info.java b/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/package-info.java
index f72340a6a..8f526288a 100644
--- a/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/package-info.java
+++ b/src/plugin/feed/src/java/org/apache/nutch/indexer/feed/package-info.java
@@ -19,3 +19,4 @@
* Indexing filter to index meta data from RSS feeds.
*/
package org.apache.nutch.indexer.feed;
+
diff --git a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
index 6d31b6d2c..936c8855d 100644
--- a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
+++ b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
@@ -66,10 +66,10 @@ import com.sun.syndication.io.SyndFeedInput;
* @author mattmann
* @since NUTCH-444
*
- * <p>
- * A new RSS/ATOM Feed{@link Parser} that rapidly parses all referenced links
- * and content present in the feed.
- * </p>
+ * <p>
+ * A new RSS/ATOM Feed{@link Parser} that rapidly parses all referenced
+ * links and content present in the feed.
+ * </p>
*
*/
public class FeedParser implements Parser {
@@ -99,8 +99,8 @@ public class FeedParser implements Parser {
* A {@link Content} object representing the feed that is being
* parsed by this {@link Parser}.
*
- * @return A {@link ParseResult} containing all {@link Parse}d feeds that
- * were present in the feed file that this {@link Parser} dealt with.
+ * @return A {@link ParseResult} containing all {@link Parse}d feeds that were
+ * present in the feed file that this {@link Parser} dealt with.
*
*/
public ParseResult getParse(Content content) {
@@ -111,8 +111,8 @@ public class FeedParser implements Parser {
detector.autoDetectClues(content, true);
String encoding = detector.guessEncoding(content, defaultEncoding);
try {
- InputSource input = new InputSource(new ByteArrayInputStream(content
- .getContent()));
+ InputSource input = new InputSource(new ByteArrayInputStream(
+ content.getContent()));
input.setEncoding(encoding);
SyndFeedInput feedInput = new SyndFeedInput();
feed = feedInput.build(input);
@@ -134,8 +134,8 @@ public class FeedParser implements Parser {
}
List<?> entries = feed.getEntries();
- for(Object entry: entries) {
- addToMap(parseResult, feed, feedLink, (SyndEntry)entry, content);
+ for (Object entry : entries) {
+ addToMap(parseResult, feed, feedLink, (SyndEntry) entry, content);
}
String feedDesc = stripTags(feed.getDescriptionEx());
@@ -170,8 +170,8 @@ public class FeedParser implements Parser {
this.parserFactory = new ParserFactory(conf);
this.normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_OUTLINK);
this.filters = new URLFilters(conf);
- this.defaultEncoding =
- conf.get("parser.character.encoding.default", "windows-1252");
+ this.defaultEncoding = conf.get("parser.character.encoding.default",
+ "windows-1252");
}
/**
@@ -255,8 +255,8 @@ public class FeedParser implements Parser {
if (text == null) {
List<?> contents = entry.getContents();
StringBuilder buf = new StringBuilder();
- for (Object syndContent: contents) {
- buf.append(((SyndContent)syndContent).getValue());
+ for (Object syndContent : contents) {
+ buf.append(((SyndContent) syndContent).getValue());
}
text = buf.toString();
}
@@ -273,9 +273,9 @@ public class FeedParser implements Parser {
ParseData data = parse.getData();
data.getContentMeta().remove(Response.CONTENT_TYPE);
mergeMetadata(data.getParseMeta(), parseMeta);
- parseResult.put(link, new ParseText(parse.getText()), new ParseData(
- ParseStatus.STATUS_SUCCESS, title, data.getOutlinks(), data
- .getContentMeta(), data.getParseMeta()));
+ parseResult.put(link, new ParseText(parse.getText()),
+ new ParseData(ParseStatus.STATUS_SUCCESS, title, data.getOutlinks(),
+ data.getContentMeta(), data.getParseMeta()));
} else {
contentMeta.remove(Response.CONTENT_TYPE);
parseResult.put(link, new ParseText(text), new ParseData(
@@ -323,7 +323,7 @@ public class FeedParser implements Parser {
}
}
- for (Object i: categories) {
+ for (Object i : categories) {
parseMeta.add(Feed.FEED_TAGS, ((SyndCategory) i).getName());
}
diff --git a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/package-info.java b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/package-info.java
index a9b360369..3b1596855 100644
--- a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/package-info.java
+++ b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/package-info.java
@@ -19,3 +19,4 @@
* Parse RSS feeds.
*/
package org.apache.nutch.parse.feed;
+
diff --git a/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java b/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java
index ee3048777..36c87394b 100644
--- a/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java
+++ b/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java
@@ -43,7 +43,7 @@ import org.apache.nutch.util.NutchConfiguration;
*
* @author mattmann
*
- * Test Suite for the {@link FeedParser}.
+ * Test Suite for the {@link FeedParser}.
*
*/
public class TestFeedParser {
@@ -96,18 +96,17 @@ public class TestFeedParser {
Assert.assertEquals(3, parseResult.size());
- boolean hasLink1 = false, hasLink2 = false, hasLink3=false;
+ boolean hasLink1 = false, hasLink2 = false, hasLink3 = false;
for (Iterator<Map.Entry<Text, Parse>> j = parseResult.iterator(); j
.hasNext();) {
Map.Entry<Text, Parse> entry = j.next();
- if (entry.getKey().toString().equals(
- "http://www-scf.usc.edu/~mattmann/")) {
+ if (entry.getKey().toString()
+ .equals("http://www-scf.usc.edu/~mattmann/")) {
hasLink1 = true;
} else if (entry.getKey().toString().equals("http://www.nutch.org/")) {
hasLink2 = true;
- }
- else if(entry.getKey().toString().equals(urlString)){
+ } else if (entry.getKey().toString().equals(urlString)) {
hasLink3 = true;
}
diff --git a/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java b/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java
index 6edfb2d66..657f26064 100644
--- a/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java
+++ b/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java
@@ -38,15 +38,16 @@ public class HeadingsParseFilter implements HtmlParseFilter {
* Pattern used to strip surpluss whitespace
*/
protected static Pattern whitespacePattern = Pattern.compile("\\s+");
-
+
private Configuration conf;
private String[] headings;
private boolean multiValued = false;
- public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) {
+ public ParseResult filter(Content content, ParseResult parseResult,
+ HTMLMetaTags metaTags, DocumentFragment doc) {
Parse parse = parseResult.get(content.getUrl());
- for (int i = 0 ; headings != null && i < headings.length ; i++ ) {
+ for (int i = 0; headings != null && i < headings.length; i++) {
List<String> discoveredHeadings = getElement(doc, headings[i]);
if (discoveredHeadings.size() > 0) {
@@ -89,7 +90,7 @@ public class HeadingsParseFilter implements HtmlParseFilter {
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
if (element.equalsIgnoreCase(currentNode.getNodeName())) {
headings.add(getNodeValue(currentNode));
-
+
// Check for multiValued here, if disabled we don't need
// to discover more headings.
if (!multiValued) {
diff --git a/src/plugin/headings/src/java/org/apache/nutch/parse/headings/package-info.java b/src/plugin/headings/src/java/org/apache/nutch/parse/headings/package-info.java
index 4c073dc9e..363e0b291 100644
--- a/src/plugin/headings/src/java/org/apache/nutch/parse/headings/package-info.java
+++ b/src/plugin/headings/src/java/org/apache/nutch/parse/headings/package-info.java
@@ -19,3 +19,4 @@
* Parse filter to extract headings (h1, h2, etc.) from DOM parse tree.
*/
package org.apache.nutch.parse.headings;
+
diff --git a/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java b/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
index 65c85e9fe..6c9b8343d 100644
--- a/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
+++ b/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
@@ -30,13 +30,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Indexing filter that offers an option to either index all inbound anchor text for
- * a document or deduplicate anchors. Deduplication does have it's con's,
+ * Indexing filter that offers an option to either index all inbound anchor text
+ * for a document or deduplicate anchors. Deduplication does have it's con's,
+ *
* @see {@code anchorIndexingFilter.deduplicate} in nutch-default.xml.
*/
public class AnchorIndexingFilter implements IndexingFilter {
- public static final Logger LOG = LoggerFactory.getLogger(AnchorIndexingFilter.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(AnchorIndexingFilter.class);
private Configuration conf;
private boolean deduplicate = false;
@@ -49,6 +51,7 @@ public class AnchorIndexingFilter implements IndexingFilter {
deduplicate = conf.getBoolean("anchorIndexingFilter.deduplicate", false);
LOG.info("Anchor deduplication is: " + (deduplicate ? "on" : "off"));
}
+
/**
* Get the {@link Configuration} object
*/
@@ -57,28 +60,33 @@ public class AnchorIndexingFilter implements IndexingFilter {
}
/**
- * The {@link AnchorIndexingFilter} filter object which supports boolean
- * configuration settings for the deduplication of anchors.
- * See {@code anchorIndexingFilter.deduplicate} in nutch-default.xml.
- *
- * @param doc The {@link NutchDocument} object
- * @param parse The relevant {@link Parse} object passing through the filter
- * @param url URL to be filtered for anchor text
- * @param datum The {@link CrawlDatum} entry
- * @param inlinks The {@link Inlinks} containing anchor text
+ * The {@link AnchorIndexingFilter} filter object which supports boolean
+ * configuration settings for the deduplication of anchors. See
+ * {@code anchorIndexingFilter.deduplicate} in nutch-default.xml.
+ *
+ * @param doc
+ * The {@link NutchDocument} object
+ * @param parse
+ * The relevant {@link Parse} object passing through the filter
+ * @param url
+ * URL to be filtered for anchor text
+ * @param datum
+ * The {@link CrawlDatum} entry
+ * @param inlinks
+ * The {@link Inlinks} containing anchor text
* @return filtered NutchDocument
*/
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum,
- Inlinks inlinks) throws IndexingException {
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
- String[] anchors = (inlinks != null ? inlinks.getAnchors()
- : new String[0]);
+ String[] anchors = (inlinks != null ? inlinks.getAnchors() : new String[0]);
HashSet<String> set = null;
for (int i = 0; i < anchors.length; i++) {
if (deduplicate) {
- if (set == null) set = new HashSet<String>();
+ if (set == null)
+ set = new HashSet<String>();
String lcAnchor = anchors[i].toLowerCase();
// Check if already processed the current anchor
diff --git a/src/plugin/index-anchor/src/test/org/apache/nutch/indexer/anchor/TestAnchorIndexingFilter.java b/src/plugin/index-anchor/src/test/org/apache/nutch/indexer/anchor/TestAnchorIndexingFilter.java
index b9d7d43c7..08a42f30b 100644
--- a/src/plugin/index-anchor/src/test/org/apache/nutch/indexer/anchor/TestAnchorIndexingFilter.java
+++ b/src/plugin/index-anchor/src/test/org/apache/nutch/indexer/anchor/TestAnchorIndexingFilter.java
@@ -29,12 +29,11 @@ import org.junit.Assert;
import org.junit.Test;
/**
- * JUnit test case which tests
- * 1. that anchor text is obtained
- * 2. that anchor deduplication functionality is working
+ * JUnit test case which tests 1. that anchor text is obtained 2. that anchor
+ * deduplication functionality is working
*
* @author lewismc
- *
+ *
*/
public class TestAnchorIndexingFilter {
@@ -52,14 +51,17 @@ public class TestAnchorIndexingFilter {
inlinks.add(new Inlink("http://test2.com/", "text2"));
inlinks.add(new Inlink("http://test3.com/", "text2"));
try {
- filter.filter(doc, parse, new Text("http://nutch.apache.org/index.html"), new CrawlDatum(), inlinks);
- } catch(Exception e){
+ filter.filter(doc, parse, new Text("http://nutch.apache.org/index.html"),
+ new CrawlDatum(), inlinks);
+ } catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
Assert.assertNotNull(doc);
- Assert.assertTrue("test if there is an anchor at all", doc.getFieldNames().contains("anchor"));
- Assert.assertEquals("test dedup, we expect 2", 2, doc.getField("anchor").getValues().size());
+ Assert.assertTrue("test if there is an anchor at all", doc.getFieldNames()
+ .contains("anchor"));
+ Assert.assertEquals("test dedup, we expect 2", 2, doc.getField("anchor")
+ .getValues().size());
}
}
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 32150b211..8584fa84c 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
@@ -39,42 +39,48 @@ import java.util.Date;
import org.apache.hadoop.conf.Configuration;
-/**
- * Adds basic searchable fields to a document.
- * The fields added are : domain, host, url, content, title, cache, tstamp
- * domain is included depending on {@code indexer.add.domain} in nutch-default.xml.
- * title is truncated as per {@code indexer.max.title.length} in nutch-default.xml.
- * (As per NUTCH-1004, a zero-length title is not added)
- * content is truncated as per {@code indexer.max.content.length} in nutch-default.xml.
+/**
+ * Adds basic searchable fields to a document. The fields added are : domain,
+ * host, url, content, title, cache, tstamp domain is included depending on
+ * {@code indexer.add.domain} in nutch-default.xml. title is truncated as per
+ * {@code indexer.max.title.length} in nutch-default.xml. (As per NUTCH-1004, a
+ * zero-length title is not added) content is truncated as per
+ * {@code indexer.max.content.length} in nutch-default.xml.
*/
public class BasicIndexingFilter implements IndexingFilter {
- public static final Logger LOG = LoggerFactory.getLogger(BasicIndexingFilter.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(BasicIndexingFilter.class);
private int MAX_TITLE_LENGTH;
private int MAX_CONTENT_LENGTH;
private boolean addDomain = false;
private Configuration conf;
- /**
- * The {@link BasicIndexingFilter} filter object which supports few
- * configuration settings for adding basic searchable fields.
- * See {@code indexer.add.domain}, {@code indexer.max.title.length},
- * {@code indexer.max.content.length} in nutch-default.xml.
- *
- * @param doc The {@link NutchDocument} object
- * @param parse The relevant {@link Parse} object passing through the filter
- * @param url URL to be filtered for anchor text
- * @param datum The {@link CrawlDatum} entry
- * @param inlinks The {@link Inlinks} containing anchor text
- * @return filtered NutchDocument
- */
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks)
- throws IndexingException {
+ /**
+ * The {@link BasicIndexingFilter} filter object which supports few
+ * configuration settings for adding basic searchable fields. See
+ * {@code indexer.add.domain}, {@code indexer.max.title.length},
+ * {@code indexer.max.content.length} in nutch-default.xml.
+ *
+ * @param doc
+ * The {@link NutchDocument} object
+ * @param parse
+ * The relevant {@link Parse} object passing through the filter
+ * @param url
+ * URL to be filtered for anchor text
+ * @param datum
+ * The {@link CrawlDatum} entry
+ * @param inlinks
+ * The {@link Inlinks} containing anchor text
+ * @return filtered NutchDocument
+ */
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
Text reprUrl = (Text) datum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY);
String reprUrlString = reprUrl != null ? reprUrl.toString() : null;
String urlString = url.toString();
-
+
String host = null;
try {
URL u;
@@ -83,11 +89,11 @@ public class BasicIndexingFilter implements IndexingFilter {
} else {
u = new URL(urlString);
}
-
+
if (addDomain) {
doc.add("domain", URLUtil.getDomainName(u));
}
-
+
host = u.getHost();
} catch (MalformedURLException e) {
throw new IndexingException(e);
@@ -108,7 +114,10 @@ public class BasicIndexingFilter implements IndexingFilter {
// title
String title = parse.getData().getTitle();
- if (MAX_TITLE_LENGTH > -1 && title.length() > MAX_TITLE_LENGTH) { // truncate title if needed
+ if (MAX_TITLE_LENGTH > -1 && title.length() > MAX_TITLE_LENGTH) { // truncate
+ // title
+ // if
+ // needed
title = title.substring(0, MAX_TITLE_LENGTH);
}
diff --git a/src/plugin/index-basic/src/test/org/apache/nutch/indexer/basic/TestBasicIndexingFilter.java b/src/plugin/index-basic/src/test/org/apache/nutch/indexer/basic/TestBasicIndexingFilter.java
index 1208522a9..4bc317e6f 100644
--- a/src/plugin/index-basic/src/test/org/apache/nutch/indexer/basic/TestBasicIndexingFilter.java
+++ b/src/plugin/index-basic/src/test/org/apache/nutch/indexer/basic/TestBasicIndexingFilter.java
@@ -34,20 +34,20 @@ import org.junit.Test;
import java.util.Date;
/**
- * JUnit test case which tests
- * 1. that basic searchable fields are added to a document
- * 2. that domain is added as per {@code indexer.add.domain} in nutch-default.xml.
- * 3. that title is truncated as per {@code indexer.max.title.length} in nutch-default.xml.
- * 4. that content is truncated as per {@code indexer.max.content.length} in nutch-default.xml.
+ * JUnit test case which tests 1. that basic searchable fields are added to a
+ * document 2. that domain is added as per {@code indexer.add.domain} in
+ * nutch-default.xml. 3. that title is truncated as per
+ * {@code indexer.max.title.length} in nutch-default.xml. 4. that content is
+ * truncated as per {@code indexer.max.content.length} in nutch-default.xml.
*
* @author tejasp
- *
+ *
*/
public class TestBasicIndexingFilter {
@Test
- public void testBasicIndexingFilter() throws Exception {
+ public void testBasicIndexingFilter() throws Exception {
Configuration conf = NutchConfiguration.create();
conf.setInt("indexer.max.title.length", 10);
conf.setBoolean("indexer.add.domain", true);
@@ -63,8 +63,10 @@ public class TestBasicIndexingFilter {
Outlink[] outlinks = new Outlink[] { new Outlink("http://foo.com/", "Foo") };
Metadata metaData = new Metadata();
metaData.add("Language", "en/us");
- ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);
- ParseImpl parse = new ParseImpl("this is a sample foo bar page. hope you enjoy it.", parseData);
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title,
+ outlinks, metaData);
+ ParseImpl parse = new ParseImpl(
+ "this is a sample foo bar page. hope you enjoy it.", parseData);
CrawlDatum crawlDatum = new CrawlDatum();
crawlDatum.setFetchTime(100L);
@@ -72,18 +74,26 @@ public class TestBasicIndexingFilter {
Inlinks inlinks = new Inlinks();
try {
- filter.filter(doc, parse, new Text("http://nutch.apache.org/index.html"), crawlDatum, inlinks);
- } catch(Exception e){
+ filter.filter(doc, parse, new Text("http://nutch.apache.org/index.html"),
+ crawlDatum, inlinks);
+ } catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
Assert.assertNotNull(doc);
- Assert.assertEquals("test title, expect \"The Foo Pa\"", "The Foo Pa", doc.getField("title").getValues().get(0));
- Assert.assertEquals("test domain, expect \"apache.org\"", "apache.org", doc.getField("domain").getValues().get(0));
- Assert.assertEquals("test host, expect \"nutch.apache.org\"", "nutch.apache.org", doc.getField("host").getValues().get(0));
- Assert.assertEquals("test url, expect \"http://nutch.apache.org/index.html\"", "http://nutch.apache.org/index.html",
- doc.getField("url").getValues().get(0));
- Assert.assertEquals("test content", "this is a sample foo", doc.getField("content").getValues().get(0));
- Assert.assertEquals("test fetch time", new Date(100L), (Date)doc.getField("tstamp").getValues().get(0));
+ Assert.assertEquals("test title, expect \"The Foo Pa\"", "The Foo Pa", doc
+ .getField("title").getValues().get(0));
+ Assert.assertEquals("test domain, expect \"apache.org\"", "apache.org", doc
+ .getField("domain").getValues().get(0));
+ Assert.assertEquals("test host, expect \"nutch.apache.org\"",
+ "nutch.apache.org", doc.getField("host").getValues().get(0));
+ Assert.assertEquals(
+ "test url, expect \"http://nutch.apache.org/index.html\"",
+ "http://nutch.apache.org/index.html", doc.getField("url").getValues()
+ .get(0));
+ Assert.assertEquals("test content", "this is a sample foo",
+ doc.getField("content").getValues().get(0));
+ Assert.assertEquals("test fetch time", new Date(100L),
+ (Date) doc.getField("tstamp").getValues().get(0));
}
}
diff --git a/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPDocumentCreator.java b/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPDocumentCreator.java
index 6b091e031..88d78ef37 100644
--- a/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPDocumentCreator.java
+++ b/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPDocumentCreator.java
@@ -41,13 +41,16 @@ import com.maxmind.geoip2.record.Subdivision;
import com.maxmind.geoip2.record.Traits;
/**
- * <p>Simple utility class which enables efficient, structured
- * {@link org.apache.nutch.indexer.NutchDocument} building based on input
- * from {@link GeoIPIndexingFilter}, where configuration is also read.</p>
- * <p>Based on the nature of the input, this class wraps factory type
- * implementations for populating {@link org.apache.nutch.indexer.NutchDocument}'s
- * with the correct {@link org.apache.nutch.indexer.NutchField} information.
- *
+ * <p>
+ * Simple utility class which enables efficient, structured
+ * {@link org.apache.nutch.indexer.NutchDocument} building based on input from
+ * {@link GeoIPIndexingFilter}, where configuration is also read.
+ * </p>
+ * <p>
+ * Based on the nature of the input, this class wraps factory type
+ * implementations for populating {@link org.apache.nutch.indexer.NutchDocument}
+ * 's with the correct {@link org.apache.nutch.indexer.NutchField} information.
+ *
*/
public class GeoIPDocumentCreator {
@@ -58,13 +61,15 @@ public class GeoIPDocumentCreator {
}
public static NutchDocument createDocFromInsightsService(String serverIp,
- NutchDocument doc, WebServiceClient client) throws UnknownHostException, IOException, GeoIp2Exception {
+ NutchDocument doc, WebServiceClient client) throws UnknownHostException,
+ IOException, GeoIp2Exception {
doc.add("ip", serverIp);
- InsightsResponse response = client.insights(InetAddress.getByName(serverIp));
- //CityResponse response = client.city(InetAddress.getByName(serverIp));
-
+ InsightsResponse response = client
+ .insights(InetAddress.getByName(serverIp));
+ // CityResponse response = client.city(InetAddress.getByName(serverIp));
+
City city = response.getCity();
- doc.add("cityName", city.getName()); // 'Minneapolis'
+ doc.add("cityName", city.getName()); // 'Minneapolis'
doc.add("cityConfidence", city.getConfidence()); // 50
doc.add("cityGeoNameId", city.getGeoNameId());
@@ -74,31 +79,32 @@ public class GeoIPDocumentCreator {
doc.add("continentName", continent.getName());
Country country = response.getCountry();
- doc.add("countryIsoCode", country.getIsoCode()); // 'US'
- doc.add("countryName", country.getName()); // 'United States'
- doc.add("countryConfidence", country.getConfidence()); // 99
+ doc.add("countryIsoCode", country.getIsoCode()); // 'US'
+ doc.add("countryName", country.getName()); // 'United States'
+ doc.add("countryConfidence", country.getConfidence()); // 99
doc.add("countryGeoName", country.getGeoNameId());
Location location = response.getLocation();
- doc.add("latLon", location.getLatitude() + "," + location.getLongitude()); // 44.9733, -93.2323
- doc.add("accRadius", location.getAccuracyRadius()); // 3
- doc.add("timeZone", location.getTimeZone()); // 'America/Chicago'
+ doc.add("latLon", location.getLatitude() + "," + location.getLongitude()); // 44.9733,
+ // -93.2323
+ doc.add("accRadius", location.getAccuracyRadius()); // 3
+ doc.add("timeZone", location.getTimeZone()); // 'America/Chicago'
doc.add("metroCode", location.getMetroCode());
Postal postal = response.getPostal();
- doc.add("postalCode", postal.getCode()); // '55455'
+ doc.add("postalCode", postal.getCode()); // '55455'
doc.add("postalConfidence", postal.getConfidence()); // 40
RepresentedCountry rCountry = response.getRepresentedCountry();
doc.add("countryType", rCountry.getType());
Subdivision subdivision = response.getMostSpecificSubdivision();
- doc.add("subDivName", subdivision.getName()); // 'Minnesota'
- doc.add("subDivIdoCode", subdivision.getIsoCode()); // 'MN'
+ doc.add("subDivName", subdivision.getName()); // 'Minnesota'
+ doc.add("subDivIdoCode", subdivision.getIsoCode()); // 'MN'
doc.add("subDivConfidence", subdivision.getConfidence()); // 90
doc.add("subDivGeoNameId", subdivision.getGeoNameId());
- Traits traits = response.getTraits();
+ Traits traits = response.getTraits();
doc.add("autonSystemNum", traits.getAutonomousSystemNumber());
doc.add("autonSystemOrg", traits.getAutonomousSystemOrganization());
doc.add("domain", traits.getDomain());
@@ -112,20 +118,23 @@ public class GeoIPDocumentCreator {
@SuppressWarnings("unused")
public static NutchDocument createDocFromCityService(String serverIp,
- NutchDocument doc, WebServiceClient client) throws UnknownHostException, IOException, GeoIp2Exception {
+ NutchDocument doc, WebServiceClient client) throws UnknownHostException,
+ IOException, GeoIp2Exception {
CityResponse response = client.city(InetAddress.getByName(serverIp));
return doc;
}
@SuppressWarnings("unused")
public static NutchDocument createDocFromCountryService(String serverIp,
- NutchDocument doc, WebServiceClient client) throws UnknownHostException, IOException, GeoIp2Exception {
- CountryResponse response = client.country(InetAddress.getByName(serverIp));
+ NutchDocument doc, WebServiceClient client) throws UnknownHostException,
+ IOException, GeoIp2Exception {
+ CountryResponse response = client.country(InetAddress.getByName(serverIp));
return doc;
}
- public static NutchDocument createDocFromIspDb(String serverIp, NutchDocument doc,
- DatabaseReader reader) throws UnknownHostException, IOException, GeoIp2Exception {
+ public static NutchDocument createDocFromIspDb(String serverIp,
+ NutchDocument doc, DatabaseReader reader) throws UnknownHostException,
+ IOException, GeoIp2Exception {
IspResponse response = reader.isp(InetAddress.getByName(serverIp));
doc.add("ip", serverIp);
doc.add("autonSystemNum", response.getAutonomousSystemNumber());
@@ -135,8 +144,9 @@ public class GeoIPDocumentCreator {
return doc;
}
- public static NutchDocument createDocFromDomainDb(String serverIp, NutchDocument doc,
- DatabaseReader reader) throws UnknownHostException, IOException, GeoIp2Exception {
+ public static NutchDocument createDocFromDomainDb(String serverIp,
+ NutchDocument doc, DatabaseReader reader) throws UnknownHostException,
+ IOException, GeoIp2Exception {
DomainResponse response = reader.domain(InetAddress.getByName(serverIp));
doc.add("ip", serverIp);
doc.add("domain", response.getDomain());
@@ -144,20 +154,23 @@ public class GeoIPDocumentCreator {
}
public static NutchDocument createDocFromConnectionDb(String serverIp,
- NutchDocument doc, DatabaseReader reader) throws UnknownHostException, IOException, GeoIp2Exception {
- ConnectionTypeResponse response = reader.connectionType(InetAddress.getByName(serverIp));
+ NutchDocument doc, DatabaseReader reader) throws UnknownHostException,
+ IOException, GeoIp2Exception {
+ ConnectionTypeResponse response = reader.connectionType(InetAddress
+ .getByName(serverIp));
doc.add("ip", serverIp);
doc.add("connType", response.getConnectionType().toString());
return doc;
}
- public static NutchDocument createDocFromCityDb(String serverIp, NutchDocument doc,
- DatabaseReader reader) throws UnknownHostException, IOException, GeoIp2Exception {
+ public static NutchDocument createDocFromCityDb(String serverIp,
+ NutchDocument doc, DatabaseReader reader) throws UnknownHostException,
+ IOException, GeoIp2Exception {
doc.add("ip", serverIp);
CityResponse response = reader.city(InetAddress.getByName(serverIp));
City city = response.getCity();
- doc.add("cityName", city.getName()); // 'Minneapolis'
+ doc.add("cityName", city.getName()); // 'Minneapolis'
doc.add("cityConfidence", city.getConfidence()); // 50
doc.add("cityGeoNameId", city.getGeoNameId());
@@ -167,27 +180,28 @@ public class GeoIPDocumentCreator {
doc.add("continentName", continent.getName());
Country country = response.getCountry();
- doc.add("countryIsoCode", country.getIsoCode()); // 'US'
- doc.add("countryName", country.getName()); // 'United States'
- doc.add("countryConfidence", country.getConfidence()); // 99
+ doc.add("countryIsoCode", country.getIsoCode()); // 'US'
+ doc.add("countryName", country.getName()); // 'United States'
+ doc.add("countryConfidence", country.getConfidence()); // 99
doc.add("countryGeoName", country.getGeoNameId());
Location location = response.getLocation();
- doc.add("latLon", location.getLatitude() + "," + location.getLongitude()); // 44.9733, -93.2323
- doc.add("accRadius", location.getAccuracyRadius()); // 3
- doc.add("timeZone", location.getTimeZone()); // 'America/Chicago'
+ doc.add("latLon", location.getLatitude() + "," + location.getLongitude()); // 44.9733,
+ // -93.2323
+ doc.add("accRadius", location.getAccuracyRadius()); // 3
+ doc.add("timeZone", location.getTimeZone()); // 'America/Chicago'
doc.add("metroCode", location.getMetroCode());
Postal postal = response.getPostal();
- doc.add("postalCode", postal.getCode()); // '55455'
+ doc.add("postalCode", postal.getCode()); // '55455'
doc.add("postalConfidence", postal.getConfidence()); // 40
RepresentedCountry rCountry = response.getRepresentedCountry();
doc.add("countryType", rCountry.getType());
Subdivision subdivision = response.getMostSpecificSubdivision();
- doc.add("subDivName", subdivision.getName()); // 'Minnesota'
- doc.add("subDivIdoCode", subdivision.getIsoCode()); // 'MN'
+ doc.add("subDivName", subdivision.getName()); // 'Minnesota'
+ doc.add("subDivIdoCode", subdivision.getIsoCode()); // 'MN'
doc.add("subDivConfidence", subdivision.getConfidence()); // 90
doc.add("subDivGeoNameId", subdivision.getGeoNameId());
return doc;
diff --git a/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPIndexingFilter.java b/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPIndexingFilter.java
index cba3364ba..f515f1f4f 100644
--- a/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPIndexingFilter.java
+++ b/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/GeoIPIndexingFilter.java
@@ -34,16 +34,22 @@ import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.WebServiceClient;
/**
- * <p>This plugin implements an indexing filter which takes
- * advantage of the
- * <a href="https://github.com/maxmind/GeoIP2-java">GeoIP2-java API</a>.</p>
- * <p>The third party library distribution provides an API for the GeoIP2
- * <a href="http://dev.maxmind.com/geoip/geoip2/web-services">Precision web services</a>
- * and <a href="http://dev.maxmind.com/geoip/geoip2/downloadable">databases</a>.
- * The API also works with the free
- * <a href="http://dev.maxmind.com/geoip/geoip2/geolite2/">GeoLite2 databases</a>.</p>
- * <p>Depending on the service level agreement, you have with the GeoIP service provider,
- * the plugin can add a number of the following fields to the index data model:
+ * <p>
+ * This plugin implements an indexing filter which takes advantage of the <a
+ * href="https://github.com/maxmind/GeoIP2-java">GeoIP2-java API</a>.
+ * </p>
+ * <p>
+ * The third party library distribution provides an API for the GeoIP2 <a
+ * href="http://dev.maxmind.com/geoip/geoip2/web-services">Precision web
+ * services</a> and <a
+ * href="http://dev.maxmind.com/geoip/geoip2/downloadable">databases</a>. The
+ * API also works with the free <a
+ * href="http://dev.maxmind.com/geoip/geoip2/geolite2/">GeoLite2 databases</a>.
+ * </p>
+ * <p>
+ * Depending on the service level agreement, you have with the GeoIP service
+ * provider, the plugin can add a number of the following fields to the index
+ * data model:
* <ol>
* <li>Continent</li>
* <li>Country</li>
@@ -56,51 +62,59 @@ import com.maxmind.geoip2.WebServiceClient;
* <li>Confidence Factors</li>
* <li>Radius</li>
* <li>User Type</li>
- * </ol></p>
+ * </ol>
+ * </p>
*
- * <p>Some of the services are documented at the
- * <a href="https://www.maxmind.com/en/geoip2-precision-services">GeoIP2 Precision Services</a>
- * webpage where more information can be obtained.</p>
+ * <p>
+ * Some of the services are documented at the <a
+ * href="https://www.maxmind.com/en/geoip2-precision-services">GeoIP2 Precision
+ * Services</a> webpage where more information can be obtained.
+ * </p>
+ *
+ * <p>
+ * You should also consult the following three properties in
+ * <code>nutch-site.xml</code>
+ * </p>
*
- * <p>You should also consult the following three properties in <code>nutch-site.xml</code></p>
* <pre>
- * {@code
- *<!-- index-geoip plugin properties -->
-<property>
- <name>index.geoip.usage</name>
- <value>insightsService</value>
- <description>
- A string representing the information source to be used for GeoIP information
- association. Either enter 'cityDatabase', 'connectionTypeDatabase',
- 'domainDatabase', 'ispDatabase' or 'insightsService'. If you wish to use any one of the
- Database options, you should make one of GeoIP2-City.mmdb, GeoIP2-Connection-Type.mmdb,
- GeoIP2-Domain.mmdb or GeoIP2-ISP.mmdb files respectively available on the Hadoop classpath
- and available at runtime. This can be achieved by adding it to $NUTCH_HOME/conf
- </description>
-</property>
-
-<property>
- <name>index.geoip.userid</name>
- <value></value>
- <description>
- The userId associated with the GeoIP2 Precision Services account.
- </description>
-</property>
-
-<property>
- <name>index.geoip.licensekey</name>
- <value></value>
- <description>
- The license key associated with the GeoIP2 Precision Services account.
- </description>
-</property>
-}
+ * {@code
+ * <!-- index-geoip plugin properties -->
+ * <property>
+ * <name>index.geoip.usage</name>
+ * <value>insightsService</value>
+ * <description>
+ * A string representing the information source to be used for GeoIP information
+ * association. Either enter 'cityDatabase', 'connectionTypeDatabase',
+ * 'domainDatabase', 'ispDatabase' or 'insightsService'. If you wish to use any one of the
+ * Database options, you should make one of GeoIP2-City.mmdb, GeoIP2-Connection-Type.mmdb,
+ * GeoIP2-Domain.mmdb or GeoIP2-ISP.mmdb files respectively available on the Hadoop classpath
+ * and available at runtime. This can be achieved by adding it to $NUTCH_HOME/conf
+ * </description>
+ * </property>
+ *
+ * <property>
+ * <name>index.geoip.userid</name>
+ * <value></value>
+ * <description>
+ * The userId associated with the GeoIP2 Precision Services account.
+ * </description>
+ * </property>
+ *
+ * <property>
+ * <name>index.geoip.licensekey</name>
+ * <value></value>
+ * <description>
+ * The license key associated with the GeoIP2 Precision Services account.
+ * </description>
+ * </property>
+ * }
* </pre>
*
*/
public class GeoIPIndexingFilter implements IndexingFilter {
- private static final Logger LOG = LoggerFactory.getLogger(GeoIPIndexingFilter.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(GeoIPIndexingFilter.class);
private Configuration conf;
@@ -112,7 +126,7 @@ public class GeoIPIndexingFilter implements IndexingFilter {
DatabaseReader reader = null;
- //private AbstractResponse response = null;
+ // private AbstractResponse response = null;
/**
* Default constructor for this plugin
@@ -145,7 +159,8 @@ public class GeoIPIndexingFilter implements IndexingFilter {
}
} else if (use.equalsIgnoreCase("connectionTypeDatabase")) {
try {
- geoDb = new File(conf.getResource("GeoIP2-Connection-Type.mmdb").getFile());
+ geoDb = new File(conf.getResource("GeoIP2-Connection-Type.mmdb")
+ .getFile());
buildDb();
} catch (Exception e) {
LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e));
@@ -165,8 +180,8 @@ public class GeoIPIndexingFilter implements IndexingFilter {
LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e));
}
} else if (use.equalsIgnoreCase("insightsService")) {
- client = new WebServiceClient.Builder(
- conf.getInt("index.geoip.userid", 12345), conf.get("index.geoip.licensekey")).build();
+ client = new WebServiceClient.Builder(conf.getInt("index.geoip.userid",
+ 12345), conf.get("index.geoip.licensekey")).build();
}
usage = use;
}
@@ -181,7 +196,9 @@ public class GeoIPIndexingFilter implements IndexingFilter {
/**
*
- * @see org.apache.nutch.indexer.IndexingFilter#filter(org.apache.nutch.indexer.NutchDocument, org.apache.nutch.parse.Parse, org.apache.hadoop.io.Text, org.apache.nutch.crawl.CrawlDatum, org.apache.nutch.crawl.Inlinks)
+ * @see org.apache.nutch.indexer.IndexingFilter#filter(org.apache.nutch.indexer.NutchDocument,
+ * org.apache.nutch.parse.Parse, org.apache.hadoop.io.Text,
+ * org.apache.nutch.crawl.CrawlDatum, org.apache.nutch.crawl.Inlinks)
*/
@Override
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
@@ -189,22 +206,28 @@ public class GeoIPIndexingFilter implements IndexingFilter {
return addServerGeo(doc, parse.getData(), url.toString());
}
- private NutchDocument addServerGeo(NutchDocument doc, ParseData data, String url) {
+ private NutchDocument addServerGeo(NutchDocument doc, ParseData data,
+ String url) {
if (conf.getBoolean("store.ip.address", false) == true) {
try {
String serverIp = data.getContentMeta().get("_ip_");
if (serverIp != null) {
if (usage.equalsIgnoreCase("cityDatabase")) {
- doc = GeoIPDocumentCreator.createDocFromCityDb(serverIp, doc, reader);
+ doc = GeoIPDocumentCreator.createDocFromCityDb(serverIp, doc,
+ reader);
} else if (usage.equalsIgnoreCase("connectionTypeDatabase")) {
- doc = GeoIPDocumentCreator.createDocFromConnectionDb(serverIp, doc, reader);
+ doc = GeoIPDocumentCreator.createDocFromConnectionDb(serverIp, doc,
+ reader);
} else if (usage.equalsIgnoreCase("domainDatabase")) {
- doc = GeoIPDocumentCreator.createDocFromDomainDb(serverIp, doc, reader);
+ doc = GeoIPDocumentCreator.createDocFromDomainDb(serverIp, doc,
+ reader);
} else if (usage.equalsIgnoreCase("ispDatabase")) {
- doc = GeoIPDocumentCreator.createDocFromIspDb(serverIp, doc, reader);
+ doc = GeoIPDocumentCreator
+ .createDocFromIspDb(serverIp, doc, reader);
} else if (usage.equalsIgnoreCase("insightsService")) {
- doc = GeoIPDocumentCreator.createDocFromInsightsService(serverIp, doc, client);
+ doc = GeoIPDocumentCreator.createDocFromInsightsService(serverIp,
+ doc, client);
}
}
} catch (Exception e) {
diff --git a/src/plugin/index-metadata/src/java/org/apache/nutch/indexer/metadata/package-info.java b/src/plugin/index-metadata/src/java/org/apache/nutch/indexer/metadata/package-info.java
index d17700180..8f2bee5ce 100644
--- a/src/plugin/index-metadata/src/java/org/apache/nutch/indexer/metadata/package-info.java
+++ b/src/plugin/index-metadata/src/java/org/apache/nutch/indexer/metadata/package-info.java
@@ -20,3 +20,4 @@
* Metadata may come from CrawlDb, parse or content metadata.
*/
package org.apache.nutch.indexer.metadata;
+
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 c0ec4cbf4..773887d25 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
@@ -55,25 +55,28 @@ import org.apache.commons.lang.time.DateUtils;
* Add (or reset) a few metaData properties as respective fields (if they are
* available), so that they can be accurately used within the search index.
*
- * 'lastModifed' is indexed to support query by date, 'contentLength' obtains content length from the HTTP
- * header, 'type' field is indexed to support query by type and finally the 'title' field is an attempt
- * to reset the title if a content-disposition hint exists. The logic is that such a presence is indicative
- * that the content provider wants the filename therein to be used as the title.
- *
+ * 'lastModifed' is indexed to support query by date, 'contentLength' obtains
+ * content length from the HTTP header, 'type' field is indexed to support query
+ * by type and finally the 'title' field is an attempt to reset the title if a
+ * content-disposition hint exists. The logic is that such a presence is
+ * indicative that the content provider wants the filename therein to be used as
+ * the title.
+ *
* Still need to make content-length searchable!
- *
+ *
* @author John Xing
*/
public class MoreIndexingFilter implements IndexingFilter {
- public static final Logger LOG = LoggerFactory.getLogger(MoreIndexingFilter.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(MoreIndexingFilter.class);
/** Get the MimeTypes resolver instance. */
private MimeUtil MIME;
private Tika tika = new Tika();
/** Map for mime-type substitution */
- private HashMap<String,String> mimeMap = null;
+ private HashMap<String, String> mimeMap = null;
private boolean mapMimes = false;
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
@@ -89,23 +92,24 @@ public class MoreIndexingFilter implements IndexingFilter {
return doc;
}
- // Add time related meta info. Add last-modified if present. Index date as
+ // Add time related meta info. Add last-modified if present. Index date as
// last-modified, or, if that's not present, use fetch time.
- private NutchDocument addTime(NutchDocument doc, ParseData data,
- String url, CrawlDatum datum) {
+ private NutchDocument addTime(NutchDocument doc, ParseData data, String url,
+ CrawlDatum datum) {
long time = -1;
String lastModified = data.getMeta(Metadata.LAST_MODIFIED);
- if (lastModified != null) { // try parse last-modified
- time = getTime(lastModified,url); // use as time
- // store as string
+ if (lastModified != null) { // try parse last-modified
+ time = getTime(lastModified, url); // use as time
+ // store as string
doc.add("lastModified", new Date(time));
}
- if (time == -1) { // if no last-modified specified in HTTP header
- time = datum.getModifiedTime(); // use value in CrawlDatum
- if (time <= 0) { // if also unset
- time = datum.getFetchTime(); // use time the fetch took place (fetchTime of fetchDatum)
+ if (time == -1) { // if no last-modified specified in HTTP header
+ time = datum.getModifiedTime(); // use value in CrawlDatum
+ if (time <= 0) { // if also unset
+ time = datum.getFetchTime(); // use time the fetch took place (fetchTime
+ // of fetchDatum)
}
}
@@ -119,43 +123,29 @@ public class MoreIndexingFilter implements IndexingFilter {
try {
time = HttpDateFormat.toLong(date);
} catch (ParseException e) {
- // try to parse it as date in alternative format
- try {
- Date parsedDate = DateUtils.parseDate(date,
- new String [] {
- "EEE MMM dd HH:mm:ss yyyy",
- "EEE MMM dd HH:mm:ss yyyy zzz",
- "EEE MMM dd HH:mm:ss zzz yyyy",
- "EEE, MMM dd HH:mm:ss yyyy zzz",
- "EEE, dd MMM yyyy HH:mm:ss zzz",
- "EEE,dd MMM yyyy HH:mm:ss zzz",
- "EEE, dd MMM yyyy HH:mm:sszzz",
- "EEE, dd MMM yyyy HH:mm:ss",
- "EEE, dd-MMM-yy HH:mm:ss zzz",
- "yyyy/MM/dd HH:mm:ss.SSS zzz",
- "yyyy/MM/dd HH:mm:ss.SSS",
- "yyyy/MM/dd HH:mm:ss zzz",
- "yyyy/MM/dd",
- "yyyy.MM.dd HH:mm:ss",
- "yyyy-MM-dd HH:mm",
- "MMM dd yyyy HH:mm:ss. zzz",
- "MMM dd yyyy HH:mm:ss zzz",
- "dd.MM.yyyy HH:mm:ss zzz",
- "dd MM yyyy HH:mm:ss zzz",
- "dd.MM.yyyy; HH:mm:ss",
- "dd.MM.yyyy HH:mm:ss",
- "dd.MM.yyyy zzz",
- "yyyy-MM-dd'T'HH:mm:ss'Z'"
- });
- time = parsedDate.getTime();
- // if (LOG.isWarnEnabled()) {
- // LOG.warn(url + ": parsed date: " + date +" to:"+time);
- // }
- } catch (Exception e2) {
- if (LOG.isWarnEnabled()) {
- LOG.warn(url + ": can't parse erroneous date: " + date);
- }
- }
+ // try to parse it as date in alternative format
+ try {
+ Date parsedDate = DateUtils.parseDate(date, new String[] {
+ "EEE MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz",
+ "EEE MMM dd HH:mm:ss zzz yyyy", "EEE, MMM dd HH:mm:ss yyyy zzz",
+ "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE,dd MMM yyyy HH:mm:ss zzz",
+ "EEE, dd MMM yyyy HH:mm:sszzz", "EEE, dd MMM yyyy HH:mm:ss",
+ "EEE, dd-MMM-yy HH:mm:ss zzz", "yyyy/MM/dd HH:mm:ss.SSS zzz",
+ "yyyy/MM/dd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss zzz", "yyyy/MM/dd",
+ "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm",
+ "MMM dd yyyy HH:mm:ss. zzz", "MMM dd yyyy HH:mm:ss zzz",
+ "dd.MM.yyyy HH:mm:ss zzz", "dd MM yyyy HH:mm:ss zzz",
+ "dd.MM.yyyy; HH:mm:ss", "dd.MM.yyyy HH:mm:ss", "dd.MM.yyyy zzz",
+ "yyyy-MM-dd'T'HH:mm:ss'Z'" });
+ time = parsedDate.getTime();
+ // if (LOG.isWarnEnabled()) {
+ // LOG.warn(url + ": parsed date: " + date +" to:"+time);
+ // }
+ } catch (Exception e2) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn(url + ": can't parse erroneous date: " + date);
+ }
+ }
}
return time;
}
@@ -187,7 +177,7 @@ public class MoreIndexingFilter implements IndexingFilter {
* all case insensitive. The query filter is implemented in
* {@link TypeQueryFilter}.
* </p>
- *
+ *
* @param doc
* @param data
* @param url
@@ -212,9 +202,9 @@ public class MoreIndexingFilter implements IndexingFilter {
// (using MimeTypes.getMimeType(byte[], String), but I don't know
// which field it is?
// if (MAGIC) {
- // contentType = MIME.getMimeType(url, content);
+ // contentType = MIME.getMimeType(url, content);
// } else {
- // contentType = MIME.getMimeType(url);
+ // contentType = MIME.getMimeType(url);
// }
mimeType = tika.detect(url);
@@ -243,20 +233,20 @@ public class MoreIndexingFilter implements IndexingFilter {
if (conf.getBoolean("moreIndexingFilter.indexMimeTypeParts", true)) {
String[] parts = getParts(contentType);
- for(String part: parts) {
+ for (String part : parts) {
doc.add("type", part);
}
}
// leave this for future improvement
- //MimeTypeParameterList parameterList = mimeType.getParameters()
+ // MimeTypeParameterList parameterList = mimeType.getParameters()
return doc;
}
-
/**
* Utility method for splitting mime type into type and subtype.
+ *
* @param mimeType
* @return
*/
@@ -273,15 +263,13 @@ public class MoreIndexingFilter implements IndexingFilter {
// Content-Disposition: inline; filename="foo.ppt"
private Configuration conf;
- static Pattern patterns[] = {null, null};
+ static Pattern patterns[] = { null, null };
static {
try {
// order here is important
- patterns[0] =
- Pattern.compile("\\bfilename=['\"](.+)['\"]");
- patterns[1] =
- Pattern.compile("\\bfilename=(\\S+)\\b");
+ patterns[0] = Pattern.compile("\\bfilename=['\"](.+)['\"]");
+ patterns[1] = Pattern.compile("\\bfilename=(\\S+)\\b");
} catch (PatternSyntaxException e) {
// just ignore
}
@@ -292,7 +280,7 @@ public class MoreIndexingFilter implements IndexingFilter {
if (contentDisposition == null || doc.getFieldValue("title") != null)
return doc;
- for (int i=0; i<patterns.length; i++) {
+ for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(contentDisposition);
if (matcher.find()) {
doc.add("title", matcher.group(1));
@@ -324,11 +312,12 @@ public class MoreIndexingFilter implements IndexingFilter {
}
private void readConfiguration() throws IOException {
- BufferedReader reader = new BufferedReader(conf.getConfResourceAsReader("contenttype-mapping.txt"));
+ BufferedReader reader = new BufferedReader(
+ conf.getConfResourceAsReader("contenttype-mapping.txt"));
String line;
String parts[];
- mimeMap = new HashMap<String,String>();
+ mimeMap = new HashMap<String, String>();
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
diff --git a/src/plugin/index-more/src/test/org/apache/nutch/indexer/more/TestMoreIndexingFilter.java b/src/plugin/index-more/src/test/org/apache/nutch/indexer/more/TestMoreIndexingFilter.java
index 202e4cb69..f918dde97 100644
--- a/src/plugin/index-more/src/test/org/apache/nutch/indexer/more/TestMoreIndexingFilter.java
+++ b/src/plugin/index-more/src/test/org/apache/nutch/indexer/more/TestMoreIndexingFilter.java
@@ -40,7 +40,7 @@ public class TestMoreIndexingFilter {
assertContentType(conf, "text/html", "text/html");
assertContentType(conf, "text/html; charset=UTF-8", "text/html");
}
-
+
@Test
public void testGetParts() {
String[] parts = MoreIndexingFilter.getParts("text/html");
@@ -51,7 +51,7 @@ public class TestMoreIndexingFilter {
* @since NUTCH-901
*/
@Test
- public void testNoParts(){
+ public void testNoParts() {
Configuration conf = NutchConfiguration.create();
conf.setBoolean("moreIndexingFilter.indexMimeTypeParts", false);
MoreIndexingFilter filter = new MoreIndexingFilter();
@@ -59,18 +59,18 @@ public class TestMoreIndexingFilter {
Assert.assertNotNull(filter);
NutchDocument doc = new NutchDocument();
ParseImpl parse = new ParseImpl("foo bar", new ParseData());
-
- try{
- filter.filter(doc, parse, new Text("http://nutch.apache.org/index.html"), new CrawlDatum(), new Inlinks());
- }
- catch(Exception e){
- e.printStackTrace();
- Assert.fail(e.getMessage());
+
+ try {
+ filter.filter(doc, parse, new Text("http://nutch.apache.org/index.html"),
+ new CrawlDatum(), new Inlinks());
+ } catch (Exception e) {
+ e.printStackTrace();
+ Assert.fail(e.getMessage());
}
Assert.assertNotNull(doc);
Assert.assertTrue(doc.getFieldNames().contains("type"));
Assert.assertEquals(1, doc.getField("type").getValues().size());
- Assert.assertEquals("text/html", doc.getFieldValue("type"));
+ Assert.assertEquals("text/html", doc.getFieldValue("type"));
}
@Test
@@ -89,8 +89,9 @@ public class TestMoreIndexingFilter {
NutchDocument doc = new NutchDocument();
doc = filter.filter(doc, parseImpl, url, new CrawlDatum(), new Inlinks());
- Assert.assertEquals("content-disposition not detected", "filename.ext", doc.getFieldValue("title"));
-
+ Assert.assertEquals("content-disposition not detected", "filename.ext",
+ doc.getFieldValue("title"));
+
/* NUTCH-1140: do not add second title to avoid a multi-valued title field */
doc = new NutchDocument();
doc.add("title", "title");
@@ -105,15 +106,18 @@ public class TestMoreIndexingFilter {
Assert.assertEquals(expected[i], parts[i]);
}
}
-
- private void assertContentType(Configuration conf, String source, String expected) throws IndexingException {
+
+ private void assertContentType(Configuration conf, String source,
+ String expected) throws IndexingException {
Metadata metadata = new Metadata();
metadata.add(Response.CONTENT_TYPE, source);
MoreIndexingFilter filter = new MoreIndexingFilter();
filter.setConf(conf);
- NutchDocument doc = filter.filter(new NutchDocument(), new ParseImpl("text", new ParseData(
- new ParseStatus(), "title", new Outlink[0], metadata)), new Text(
- "http://www.example.com/"), new CrawlDatum(), new Inlinks());
- Assert.assertEquals("mime type not detected", expected, doc.getFieldValue("type"));
+ NutchDocument doc = filter.filter(new NutchDocument(), new ParseImpl(
+ "text", new ParseData(new ParseStatus(), "title", new Outlink[0],
+ metadata)), new Text("http://www.example.com/"), new CrawlDatum(),
+ new Inlinks());
+ Assert.assertEquals("mime type not detected", expected,
+ doc.getFieldValue("type"));
}
}
diff --git a/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.java b/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.java
index 6d106047d..f5d31eda0 100644
--- a/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.java
+++ b/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.java
@@ -45,11 +45,16 @@ public class StaticFieldIndexer implements IndexingFilter {
* The {@link StaticFieldIndexer} filter object which adds fields as per
* configuration setting. See {@code index.static} in nutch-default.xml.
*
- * @param doc The {@link NutchDocument} object
- * @param parse The relevant {@link Parse} object passing through the filter
- * @param url URL to be filtered for anchor text
- * @param datum The {@link CrawlDatum} entry
- * @param inlinks The {@link Inlinks} containing anchor text
+ * @param doc
+ * The {@link NutchDocument} object
+ * @param parse
+ * The relevant {@link Parse} object passing through the filter
+ * @param url
+ * URL to be filtered for anchor text
+ * @param datum
+ * The {@link CrawlDatum} entry
+ * @param inlinks
+ * The {@link Inlinks} containing anchor text
* @return filtered NutchDocument
*/
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
@@ -66,17 +71,19 @@ public class StaticFieldIndexer implements IndexingFilter {
}
/**
- * Populate a HashMap from a list of fieldname:fieldcontent.
- * See {@index.static} in nutch-default.xml.
+ * Populate a HashMap from a list of fieldname:fieldcontent. See
+ * {@index.static} in nutch-default.xml.
*
- * @param fieldsString string containing field:value pairs
+ * @param fieldsString
+ * string containing field:value pairs
* @return HashMap of fields and their corresponding values
*/
private HashMap<String, String[]> parseFields(String fieldsString) {
HashMap<String, String[]> fields = new HashMap<String, String[]>();
- /* The format is very easy, it's a comma-separated list of fields in the
- form <name>:<value>
+ /*
+ * The format is very easy, it's a comma-separated list of fields in the
+ * form <name>:<value>
*/
for (String field : fieldsString.split(",")) {
String[] entry = field.split(":");
diff --git a/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.java b/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.java
index 52773e736..c0cc7b181 100644
--- a/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.java
+++ b/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.java
@@ -28,11 +28,10 @@ import org.junit.Before;
import org.junit.Test;
/**
- * JUnit test case which tests
- * 1. that static data fields are added to a document
- * 2. that empty {@code index.static} does not add anything to the document
- * 3. that valid field:value pairs are added to the document
- * 4. that fields and values added to the document are trimmed
+ * JUnit test case which tests 1. that static data fields are added to a
+ * document 2. that empty {@code index.static} does not add anything to the
+ * document 3. that valid field:value pairs are added to the document 4. that
+ * fields and values added to the document are trimmed
*
* @author tejasp
*/
@@ -59,7 +58,8 @@ public class TestStaticFieldIndexerTest {
/**
* Test that empty {@code index.static} does not add anything to the document
- * @throws Exception
+ *
+ * @throws Exception
*/
@Test
public void testEmptyIndexStatic() throws Exception {
@@ -77,12 +77,14 @@ public class TestStaticFieldIndexerTest {
}
Assert.assertNotNull(doc);
- Assert.assertTrue("tests if no field is set for empty index.static", doc.getFieldNames().isEmpty());
+ Assert.assertTrue("tests if no field is set for empty index.static", doc
+ .getFieldNames().isEmpty());
}
/**
* Test that valid field:value pairs are added to the document
- * @throws Exception
+ *
+ * @throws Exception
*/
@Test
public void testNormalScenario() throws Exception {
@@ -102,13 +104,15 @@ public class TestStaticFieldIndexerTest {
}
Assert.assertNotNull(doc);
- Assert.assertFalse("test if doc is not empty", doc.getFieldNames().isEmpty());
- Assert.assertEquals("test if doc has 3 fields", 3, doc.getFieldNames().size());
- Assert.assertTrue("test if doc has field1", doc.getField("field1").getValues()
- .contains("val1"));
- Assert.assertTrue("test if doc has field2", doc.getField("field2").getValues()
- .contains("val2"));
- Assert.assertTrue("test if doc has field4", doc.getField("field4").getValues()
- .contains("val4"));
+ Assert.assertFalse("test if doc is not empty", doc.getFieldNames()
+ .isEmpty());
+ Assert.assertEquals("test if doc has 3 fields", 3, doc.getFieldNames()
+ .size());
+ Assert.assertTrue("test if doc has field1", doc.getField("field1")
+ .getValues().contains("val1"));
+ Assert.assertTrue("test if doc has field2", doc.getField("field2")
+ .getValues().contains("val2"));
+ Assert.assertTrue("test if doc has field4", doc.getField("field4")
+ .getValues().contains("val4"));
}
}
diff --git a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
index 9d9b8f4eb..b27ba14f0 100644
--- a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
+++ b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
@@ -35,12 +35,13 @@ import org.slf4j.LoggerFactory;
* and add.
*/
public class DummyIndexWriter implements IndexWriter {
- public static final Logger LOG = LoggerFactory.getLogger(DummyIndexWriter.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(DummyIndexWriter.class);
private Configuration config;
private Writer writer;
private boolean delete = false;
- public void open(JobConf job, String name) throws IOException {
+ public void open(JobConf job, String name) throws IOException {
delete = job.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
}
@@ -82,19 +83,21 @@ public class DummyIndexWriter implements IndexWriter {
String path = conf.get("dummy.path");
if (path == null) {
String message = "Missing path. Should be set via -Ddummy.path";
- message+="\n"+describe();
+ message += "\n" + describe();
LOG.error(message);
throw new RuntimeException(message);
}
try {
writer = new BufferedWriter(new FileWriter(conf.get("dummy.path")));
- } catch (IOException e) {}
+ } catch (IOException e) {
+ }
}
- public String describe(){
+ public String describe() {
StringBuffer sb = new StringBuffer("DummyIndexWriter\n");
- sb.append("\t").append("dummy.path : Path of the file to write to (mandatory)\n");
+ sb.append("\t").append(
+ "dummy.path : Path of the file to write to (mandatory)\n");
return sb.toString();
}
}
diff --git a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/package-info.java b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/package-info.java
index 181b1861c..8cc00c498 100644
--- a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/package-info.java
+++ b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/package-info.java
@@ -20,3 +20,4 @@
* text file, action is one of "add", "update", or "delete".
*/
package org.apache.nutch.indexwriter.dummy;
+
diff --git a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/package-info.java b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/package-info.java
index c86c2f1e8..f70833436 100644
--- a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/package-info.java
+++ b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/package-info.java
@@ -19,3 +19,4 @@
* Index writer plugin for <a href="http://www.elasticsearch.org/">Elasticsearch</a>.
*/
package org.apache.nutch.indexwriter.elastic;
+
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.java
index e24b68611..bae5e97c7 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.java
@@ -30,10 +30,10 @@ public interface SolrConstants {
public static final String USERNAME = SOLR_PREFIX + "auth.username";
public static final String PASSWORD = SOLR_PREFIX + "auth.password";
-
+
@Deprecated
public static final String COMMIT_INDEX = SOLR_PREFIX + "commit.index";
-
+
@Deprecated
public static final String PARAMS = SOLR_PREFIX + "params";
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
index 3f1a12129..a0c9d3010 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
@@ -39,169 +39,175 @@ import org.slf4j.LoggerFactory;
public class SolrIndexWriter implements IndexWriter {
- public static final Logger LOG = LoggerFactory
- .getLogger(SolrIndexWriter.class);
-
- private SolrServer solr;
- private SolrMappingReader solrMapping;
- private ModifiableSolrParams params;
-
- private Configuration config;
-
- private final List<SolrInputDocument> inputDocs = new ArrayList<SolrInputDocument>();
-
- private int batchSize;
- private int numDeletes = 0;
- private boolean delete = false;
-
- public void open(JobConf job, String name) throws IOException {
- SolrServer server = SolrUtils.getCommonsHttpSolrServer(job);
- init(server, job);
- }
-
- // package protected for tests
- void init(SolrServer server, JobConf job) throws IOException {
- solr = server;
- batchSize = job.getInt(SolrConstants.COMMIT_SIZE, 1000);
- solrMapping = SolrMappingReader.getInstance(job);
- delete = job.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
- // parse optional params
- params = new ModifiableSolrParams();
- String paramString = job.get(IndexerMapReduce.INDEXER_PARAMS);
- if (paramString != null) {
- String[] values = paramString.split("&");
- for (String v : values) {
- String[] kv = v.split("=");
- if (kv.length < 2) {
- continue;
- }
- params.add(kv[0], kv[1]);
- }
- }
- }
-
- public void delete(String key) throws IOException {
- if (delete) {
- try {
- solr.deleteById(key);
- numDeletes++;
- } catch (final SolrServerException e) {
- throw makeIOException(e);
- }
+ public static final Logger LOG = LoggerFactory
+ .getLogger(SolrIndexWriter.class);
+
+ private SolrServer solr;
+ private SolrMappingReader solrMapping;
+ private ModifiableSolrParams params;
+
+ private Configuration config;
+
+ private final List<SolrInputDocument> inputDocs = new ArrayList<SolrInputDocument>();
+
+ private int batchSize;
+ private int numDeletes = 0;
+ private boolean delete = false;
+
+ public void open(JobConf job, String name) throws IOException {
+ SolrServer server = SolrUtils.getCommonsHttpSolrServer(job);
+ init(server, job);
+ }
+
+ // package protected for tests
+ void init(SolrServer server, JobConf job) throws IOException {
+ solr = server;
+ batchSize = job.getInt(SolrConstants.COMMIT_SIZE, 1000);
+ solrMapping = SolrMappingReader.getInstance(job);
+ delete = job.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
+ // parse optional params
+ params = new ModifiableSolrParams();
+ String paramString = job.get(IndexerMapReduce.INDEXER_PARAMS);
+ if (paramString != null) {
+ String[] values = paramString.split("&");
+ for (String v : values) {
+ String[] kv = v.split("=");
+ if (kv.length < 2) {
+ continue;
}
+ params.add(kv[0], kv[1]);
+ }
}
-
- @Override
- public void update(NutchDocument doc) throws IOException {
- write(doc);
+ }
+
+ public void delete(String key) throws IOException {
+ if (delete) {
+ try {
+ solr.deleteById(key);
+ numDeletes++;
+ } catch (final SolrServerException e) {
+ throw makeIOException(e);
+ }
}
-
- public void write(NutchDocument doc) throws IOException {
- final SolrInputDocument inputDoc = new SolrInputDocument();
- for (final Entry<String, NutchField> e : doc) {
- for (final Object val : e.getValue().getValues()) {
- // normalise the string representation for a Date
- Object val2 = val;
-
- if (val instanceof Date) {
- val2 = DateUtil.getThreadLocalDateFormat().format(val);
- }
-
- if (e.getKey().equals("content") || e.getKey().equals("title")) {
- val2 = SolrUtils.stripNonCharCodepoints((String) val);
- }
-
- inputDoc.addField(solrMapping.mapKey(e.getKey()), val2, e
- .getValue().getWeight());
- String sCopy = solrMapping.mapCopyKey(e.getKey());
- if (sCopy != e.getKey()) {
- inputDoc.addField(sCopy, val);
- }
- }
+ }
+
+ @Override
+ public void update(NutchDocument doc) throws IOException {
+ write(doc);
+ }
+
+ public void write(NutchDocument doc) throws IOException {
+ final SolrInputDocument inputDoc = new SolrInputDocument();
+ for (final Entry<String, NutchField> e : doc) {
+ for (final Object val : e.getValue().getValues()) {
+ // normalise the string representation for a Date
+ Object val2 = val;
+
+ if (val instanceof Date) {
+ val2 = DateUtil.getThreadLocalDateFormat().format(val);
}
- inputDoc.setDocumentBoost(doc.getWeight());
- inputDocs.add(inputDoc);
- if (inputDocs.size() + numDeletes >= batchSize) {
- try {
- LOG.info("Indexing " + Integer.toString(inputDocs.size())
- + " documents");
- LOG.info("Deleting " + Integer.toString(numDeletes)
- + " documents");
- numDeletes = 0;
- UpdateRequest req = new UpdateRequest();
- req.add(inputDocs);
- req.setParams(params);
- req.process(solr);
- } catch (final SolrServerException e) {
- throw makeIOException(e);
- }
- inputDocs.clear();
+ if (e.getKey().equals("content") || e.getKey().equals("title")) {
+ val2 = SolrUtils.stripNonCharCodepoints((String) val);
}
- }
- public void close() throws IOException {
- try {
- if (!inputDocs.isEmpty()) {
- LOG.info("Indexing " + Integer.toString(inputDocs.size())
- + " documents");
- if (numDeletes > 0) {
- LOG.info("Deleting " + Integer.toString(numDeletes)
- + " documents");
- }
- UpdateRequest req = new UpdateRequest();
- req.add(inputDocs);
- req.setParams(params);
- req.process(solr);
- inputDocs.clear();
- }
- } catch (final SolrServerException e) {
- throw makeIOException(e);
+ inputDoc.addField(solrMapping.mapKey(e.getKey()), val2, e.getValue()
+ .getWeight());
+ String sCopy = solrMapping.mapCopyKey(e.getKey());
+ if (sCopy != e.getKey()) {
+ inputDoc.addField(sCopy, val);
}
+ }
}
- @Override
- public void commit() throws IOException {
- try {
- solr.commit();
- } catch (SolrServerException e) {
- throw makeIOException(e);
- }
+ inputDoc.setDocumentBoost(doc.getWeight());
+ inputDocs.add(inputDoc);
+ if (inputDocs.size() + numDeletes >= batchSize) {
+ try {
+ LOG.info("Indexing " + Integer.toString(inputDocs.size())
+ + " documents");
+ LOG.info("Deleting " + Integer.toString(numDeletes) + " documents");
+ numDeletes = 0;
+ UpdateRequest req = new UpdateRequest();
+ req.add(inputDocs);
+ req.setParams(params);
+ req.process(solr);
+ } catch (final SolrServerException e) {
+ throw makeIOException(e);
+ }
+ inputDocs.clear();
}
-
- public static IOException makeIOException(SolrServerException e) {
- final IOException ioe = new IOException();
- ioe.initCause(e);
- return ioe;
+ }
+
+ public void close() throws IOException {
+ try {
+ if (!inputDocs.isEmpty()) {
+ LOG.info("Indexing " + Integer.toString(inputDocs.size())
+ + " documents");
+ if (numDeletes > 0) {
+ LOG.info("Deleting " + Integer.toString(numDeletes) + " documents");
+ }
+ UpdateRequest req = new UpdateRequest();
+ req.add(inputDocs);
+ req.setParams(params);
+ req.process(solr);
+ inputDocs.clear();
+ }
+ } catch (final SolrServerException e) {
+ throw makeIOException(e);
}
-
- @Override
- public Configuration getConf() {
- return config;
+ }
+
+ @Override
+ public void commit() throws IOException {
+ try {
+ solr.commit();
+ } catch (SolrServerException e) {
+ throw makeIOException(e);
}
-
- @Override
- public void setConf(Configuration conf) {
- config = conf;
- String serverURL = conf.get(SolrConstants.SERVER_URL);
- if (serverURL == null) {
- String message = "Missing SOLR URL. Should be set via -D "
- + SolrConstants.SERVER_URL;
- message+="\n"+describe();
- LOG.error(message);
- throw new RuntimeException(message);
- }
+ }
+
+ public static IOException makeIOException(SolrServerException e) {
+ final IOException ioe = new IOException();
+ ioe.initCause(e);
+ return ioe;
+ }
+
+ @Override
+ public Configuration getConf() {
+ return config;
+ }
+
+ @Override
+ public void setConf(Configuration conf) {
+ config = conf;
+ String serverURL = conf.get(SolrConstants.SERVER_URL);
+ if (serverURL == null) {
+ String message = "Missing SOLR URL. Should be set via -D "
+ + SolrConstants.SERVER_URL;
+ message += "\n" + describe();
+ LOG.error(message);
+ throw new RuntimeException(message);
}
+ }
+
+ public String describe() {
+ StringBuffer sb = new StringBuffer("SOLRIndexWriter\n");
+ sb.append("\t").append(SolrConstants.SERVER_URL)
+ .append(" : URL of the SOLR instance (mandatory)\n");
+ sb.append("\t").append(SolrConstants.COMMIT_SIZE)
+ .append(" : buffer size when sending to SOLR (default 1000)\n");
+ sb.append("\t")
+ .append(SolrConstants.MAPPING_FILE)
+ .append(
+ " : name of the mapping file for fields (default solrindex-mapping.xml)\n");
+ sb.append("\t").append(SolrConstants.USE_AUTH)
+ .append(" : use authentication (default false)\n");
+ sb.append("\t").append(SolrConstants.USERNAME)
+ .append(" : username for authentication\n");
+ sb.append("\t").append(SolrConstants.PASSWORD)
+ .append(" : password for authentication\n");
+ return sb.toString();
+ }
- public String describe(){
- StringBuffer sb = new StringBuffer("SOLRIndexWriter\n");
- sb.append("\t").append(SolrConstants.SERVER_URL).append(" : URL of the SOLR instance (mandatory)\n");
- sb.append("\t").append(SolrConstants.COMMIT_SIZE).append(" : buffer size when sending to SOLR (default 1000)\n");
- sb.append("\t").append(SolrConstants.MAPPING_FILE).append(" : name of the mapping file for fields (default solrindex-mapping.xml)\n");
- sb.append("\t").append(SolrConstants.USE_AUTH).append(" : use authentication (default false)\n");
- sb.append("\t").append(SolrConstants.USERNAME).append(" : username for authentication\n");
- sb.append("\t").append(SolrConstants.PASSWORD).append(" : password for authentication\n");
- return sb.toString();
- }
-
}
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrMappingReader.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrMappingReader.java
index 720d13111..19ffa6f69 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrMappingReader.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrMappingReader.java
@@ -38,16 +38,17 @@ import org.xml.sax.SAXException;
public class SolrMappingReader {
public static Logger LOG = LoggerFactory.getLogger(SolrMappingReader.class);
-
+
private Configuration conf;
-
+
private Map<String, String> keyMap = new HashMap<String, String>();
private Map<String, String> copyMap = new HashMap<String, String>();
private String uniqueKey = "id";
-
+
public static synchronized SolrMappingReader getInstance(Configuration conf) {
ObjectCache cache = ObjectCache.get(conf);
- SolrMappingReader instance = (SolrMappingReader)cache.getObject(SolrMappingReader.class.getName());
+ SolrMappingReader instance = (SolrMappingReader) cache
+ .getObject(SolrMappingReader.class.getName());
if (instance == null) {
instance = new SolrMappingReader(conf);
cache.setObject(SolrMappingReader.class.getName(), instance);
@@ -60,9 +61,10 @@ public class SolrMappingReader {
parseMapping();
}
- private void parseMapping() {
+ private void parseMapping() {
InputStream ssInputStream = null;
- ssInputStream = conf.getConfResourceAsInputStream(conf.get(SolrConstants.MAPPING_FILE, "solrindex-mapping.xml"));
+ ssInputStream = conf.getConfResourceAsInputStream(conf.get(
+ SolrConstants.MAPPING_FILE, "solrindex-mapping.xml"));
InputSource inputSource = new InputSource(ssInputStream);
try {
@@ -74,48 +76,50 @@ public class SolrMappingReader {
if (fieldList.getLength() > 0) {
for (int i = 0; i < fieldList.getLength(); i++) {
Element element = (Element) fieldList.item(i);
- LOG.info("source: " + element.getAttribute("source") + " dest: " + element.getAttribute("dest"));
- keyMap.put(element.getAttribute("source"), element.getAttribute("dest"));
+ LOG.info("source: " + element.getAttribute("source") + " dest: "
+ + element.getAttribute("dest"));
+ keyMap.put(element.getAttribute("source"),
+ element.getAttribute("dest"));
}
}
NodeList copyFieldList = rootElement.getElementsByTagName("copyField");
if (copyFieldList.getLength() > 0) {
for (int i = 0; i < copyFieldList.getLength(); i++) {
Element element = (Element) copyFieldList.item(i);
- LOG.info("source: " + element.getAttribute("source") + " dest: " + element.getAttribute("dest"));
- copyMap.put(element.getAttribute("source"), element.getAttribute("dest"));
+ LOG.info("source: " + element.getAttribute("source") + " dest: "
+ + element.getAttribute("dest"));
+ copyMap.put(element.getAttribute("source"),
+ element.getAttribute("dest"));
}
}
NodeList uniqueKeyItem = rootElement.getElementsByTagName("uniqueKey");
if (uniqueKeyItem.getLength() > 1) {
LOG.warn("More than one unique key definitions found in solr index mapping, using default 'id'");
uniqueKey = "id";
- }
- else if (uniqueKeyItem.getLength() == 0) {
+ } else if (uniqueKeyItem.getLength() == 0) {
LOG.warn("No unique key definition found in solr index mapping using, default 'id'");
- }
- else{
- uniqueKey = uniqueKeyItem.item(0).getFirstChild().getNodeValue();
+ } else {
+ uniqueKey = uniqueKeyItem.item(0).getFirstChild().getNodeValue();
}
} catch (MalformedURLException e) {
- LOG.warn(e.toString());
+ LOG.warn(e.toString());
} catch (SAXException e) {
- LOG.warn(e.toString());
+ LOG.warn(e.toString());
} catch (IOException e) {
- LOG.warn(e.toString());
+ LOG.warn(e.toString());
} catch (ParserConfigurationException e) {
- LOG.warn(e.toString());
- }
+ LOG.warn(e.toString());
+ }
}
-
+
public Map<String, String> getKeyMap() {
return keyMap;
}
-
+
public Map<String, String> getCopyMap() {
return copyMap;
}
-
+
public String getUniqueKey() {
return uniqueKey;
}
@@ -128,14 +132,14 @@ public class SolrMappingReader {
}
public String mapKey(String key) throws IOException {
- if(keyMap.containsKey(key)) {
+ if (keyMap.containsKey(key)) {
key = (String) keyMap.get(key);
}
return key;
}
public String mapCopyKey(String key) throws IOException {
- if(copyMap.containsKey(key)) {
+ if (copyMap.containsKey(key)) {
key = (String) copyMap.get(key);
}
return key;
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
index 353af10b5..170688f23 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
@@ -31,8 +31,9 @@ public class SolrUtils {
public static Logger LOG = LoggerFactory.getLogger(SolrUtils.class);
- public static CommonsHttpSolrServer getCommonsHttpSolrServer(JobConf job) throws MalformedURLException {
- HttpClient client=new HttpClient();
+ public static CommonsHttpSolrServer getCommonsHttpSolrServer(JobConf job)
+ throws MalformedURLException {
+ HttpClient client = new HttpClient();
// Check for username/password
if (job.getBoolean(SolrConstants.USE_AUTH, false)) {
@@ -40,9 +41,13 @@ public class SolrUtils {
LOG.info("Authenticating as: " + username);
- AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
+ AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
+ AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
- client.getState().setCredentials(scope, new UsernamePasswordCredentials(username, job.get(SolrConstants.PASSWORD)));
+ client.getState().setCredentials(
+ scope,
+ new UsernamePasswordCredentials(username, job
+ .get(SolrConstants.PASSWORD)));
HttpClientParams params = client.getParams();
params.setAuthenticationPreemptive(true);
@@ -51,7 +56,7 @@ public class SolrUtils {
}
String serverURL = job.get(SolrConstants.SERVER_URL);
-
+
return new CommonsHttpSolrServer(serverURL, client);
}
@@ -62,8 +67,10 @@ public class SolrUtils {
for (int i = 0; i < input.length(); i++) {
ch = input.charAt(i);
- // Strip all non-characters http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Noncharacter_Code_Point=True:]
- // and non-printable control characters except tabulator, new line and carriage return
+ // Strip all non-characters
+ // http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Noncharacter_Code_Point=True:]
+ // and non-printable control characters except tabulator, new line and
+ // carriage return
if (ch % 0x10000 != 0xffff && // 0xffff - 0x10ffff range step 0x10000
ch % 0x10000 != 0xfffe && // 0xfffe - 0x10fffe range
(ch <= 0xfdd0 || ch >= 0xfdef) && // 0xfdd0 - 0xfdef
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/package-info.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/package-info.java
index 2cebf7cd5..af5f50c39 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/package-info.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/package-info.java
@@ -19,3 +19,4 @@
* Index writer plugin for <a href="http://lucene.apache.org/solr/">Apache Solr</a>.
*/
package org.apache.nutch.indexwriter.solr;
+
diff --git a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
index 8e08846c6..cb8f8c10a 100644
--- a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
+++ b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
@@ -41,289 +41,280 @@ import org.w3c.dom.Node;
public class HTMLLanguageParser implements HtmlParseFilter {
- public static final Logger LOG = LoggerFactory
- .getLogger(HTMLLanguageParser.class);
-
- private int detect = -1, identify = -1;
-
- private int contentMaxlength = -1;
-
- private boolean onlyCertain = false;
-
- /* A static Map of ISO-639 language codes */
- private static Map<String, String> LANGUAGES_MAP = new HashMap<String, String>();
- static {
- try {
- Properties p = new Properties();
- p.load(HTMLLanguageParser.class
- .getResourceAsStream("langmappings.properties"));
- Enumeration<?> keys = p.keys();
- while (keys.hasMoreElements()) {
- String key = (String) keys.nextElement();
- String[] values = p.getProperty(key).split(",", -1);
- LANGUAGES_MAP.put(key, key);
- for (int i = 0; i < values.length; i++) {
- LANGUAGES_MAP.put(values[i].trim().toLowerCase(), key);
- }
- }
- } catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.toString());
- }
+ public static final Logger LOG = LoggerFactory
+ .getLogger(HTMLLanguageParser.class);
+
+ private int detect = -1, identify = -1;
+
+ private int contentMaxlength = -1;
+
+ private boolean onlyCertain = false;
+
+ /* A static Map of ISO-639 language codes */
+ private static Map<String, String> LANGUAGES_MAP = new HashMap<String, String>();
+ static {
+ try {
+ Properties p = new Properties();
+ p.load(HTMLLanguageParser.class
+ .getResourceAsStream("langmappings.properties"));
+ Enumeration<?> keys = p.keys();
+ while (keys.hasMoreElements()) {
+ String key = (String) keys.nextElement();
+ String[] values = p.getProperty(key).split(",", -1);
+ LANGUAGES_MAP.put(key, key);
+ for (int i = 0; i < values.length; i++) {
+ LANGUAGES_MAP.put(values[i].trim().toLowerCase(), key);
}
+ }
+ } catch (Exception e) {
+ if (LOG.isErrorEnabled()) {
+ LOG.error(e.toString());
+ }
+ }
+ }
+
+ private Configuration conf;
+
+ /**
+ * Scan the HTML document looking at possible indications of content language<br>
+ * <li>1. html lang attribute
+ * (http://www.w3.org/TR/REC-html40/struct/dirlang.html#h-8.1) <li>2. meta
+ * dc.language
+ * (http://dublincore.org/documents/2000/07/16/usageguide/qualified
+ * -html.shtml#language) <li>3. meta http-equiv (content-language)
+ * (http://www.w3.org/TR/REC-html40/struct/global.html#h-7.4.4.2) <br>
+ */
+ public ParseResult filter(Content content, ParseResult parseResult,
+ HTMLMetaTags metaTags, DocumentFragment doc) {
+ String lang = null;
+
+ Parse parse = parseResult.get(content.getUrl());
+
+ if (detect >= 0 && identify < 0) {
+ lang = detectLanguage(parse, doc);
+ } else if (detect < 0 && identify >= 0) {
+ lang = identifyLanguage(parse);
+ } else if (detect < identify) {
+ lang = detectLanguage(parse, doc);
+ if (lang == null) {
+ lang = identifyLanguage(parse);
+ }
+ } else if (identify < detect) {
+ lang = identifyLanguage(parse);
+ if (lang == null) {
+ lang = detectLanguage(parse, doc);
+ }
+ } else {
+ LOG.warn("No configuration for language extraction policy is provided");
+ return parseResult;
}
- private Configuration conf;
+ if (lang != null) {
+ parse.getData().getParseMeta().set(Metadata.LANGUAGE, lang);
+ return parseResult;
+ }
- /**
- * Scan the HTML document looking at possible indications of content
- * language<br>
- * <li>1. html lang attribute
- * (http://www.w3.org/TR/REC-html40/struct/dirlang.html#h-8.1) <li>2. meta
- * dc.language
- * (http://dublincore.org/documents/2000/07/16/usageguide/qualified
- * -html.shtml#language) <li>3. meta http-equiv (content-language)
- * (http://www.w3.org/TR/REC-html40/struct/global.html#h-7.4.4.2) <br>
- */
- public ParseResult filter(Content content, ParseResult parseResult,
- HTMLMetaTags metaTags, DocumentFragment doc) {
- String lang = null;
-
- Parse parse = parseResult.get(content.getUrl());
-
- if (detect >= 0 && identify < 0) {
- lang = detectLanguage(parse, doc);
- } else if (detect < 0 && identify >= 0) {
- lang = identifyLanguage(parse);
- } else if (detect < identify) {
- lang = detectLanguage(parse, doc);
- if (lang == null) {
- lang = identifyLanguage(parse);
- }
- } else if (identify < detect) {
- lang = identifyLanguage(parse);
- if (lang == null) {
- lang = detectLanguage(parse, doc);
- }
- } else {
- LOG.warn("No configuration for language extraction policy is provided");
- return parseResult;
- }
+ return parseResult;
+ }
- if (lang != null) {
- parse.getData().getParseMeta().set(Metadata.LANGUAGE, lang);
- return parseResult;
- }
+ /** Try to find the document's language from page headers and metadata */
+ private String detectLanguage(Parse page, DocumentFragment doc) {
+ String lang = getLanguageFromMetadata(page.getData().getParseMeta());
+ if (lang == null) {
+ LanguageParser parser = new LanguageParser(doc);
+ lang = parser.getLanguage();
+ }
- return parseResult;
+ if (lang != null) {
+ return lang;
}
- /** Try to find the document's language from page headers and metadata */
- private String detectLanguage(Parse page, DocumentFragment doc) {
- String lang = getLanguageFromMetadata(page.getData().getParseMeta());
- if (lang == null) {
- LanguageParser parser = new LanguageParser(doc);
- lang = parser.getLanguage();
- }
+ lang = page.getData().getContentMeta().get(Response.CONTENT_LANGUAGE);
- if (lang != null) {
- return lang;
- }
+ return lang;
+ }
- lang = page.getData().getContentMeta().get(Response.CONTENT_LANGUAGE);
+ /** Use statistical language identification to extract page language */
+ private String identifyLanguage(Parse parse) {
+ StringBuilder text = new StringBuilder();
+ if (parse == null)
+ return null;
- return lang;
+ String title = parse.getData().getTitle();
+ if (title != null) {
+ text.append(title.toString());
}
- /** Use statistical language identification to extract page language */
- private String identifyLanguage(Parse parse) {
- StringBuilder text = new StringBuilder();
- if (parse == null)
- return null;
-
- String title = parse.getData().getTitle();
- if (title != null) {
- text.append(title.toString());
- }
-
- String content = parse.getText();
- if (content != null) {
- text.append(" ").append(content.toString());
- }
+ String content = parse.getText();
+ if (content != null) {
+ text.append(" ").append(content.toString());
+ }
- // trim content?
- String titleandcontent = text.toString();
+ // trim content?
+ String titleandcontent = text.toString();
- if (this.contentMaxlength != -1
- && titleandcontent.length() > this.contentMaxlength)
- titleandcontent = titleandcontent.substring(0, contentMaxlength);
+ if (this.contentMaxlength != -1
+ && titleandcontent.length() > this.contentMaxlength)
+ titleandcontent = titleandcontent.substring(0, contentMaxlength);
- LanguageIdentifier identifier = new LanguageIdentifier(titleandcontent);
+ LanguageIdentifier identifier = new LanguageIdentifier(titleandcontent);
- if (onlyCertain) {
- if (identifier.isReasonablyCertain())
- return identifier.getLanguage();
- else
- return null;
- }
+ if (onlyCertain) {
+ if (identifier.isReasonablyCertain())
return identifier.getLanguage();
+ else
+ return null;
}
-
- // Check in the metadata whether the language has already been stored there
- // by Tika
- private static String getLanguageFromMetadata(Metadata meta) {
- if (meta == null)
- return null;
- // dublin core
- String lang = meta.get("dc.language");
- if (lang != null)
- return lang;
- // meta content-language
- lang = meta.get("content-language");
- if (lang != null)
- return lang;
- // lang attribute
- return meta.get("lang");
+ return identifier.getLanguage();
+ }
+
+ // Check in the metadata whether the language has already been stored there
+ // by Tika
+ private static String getLanguageFromMetadata(Metadata meta) {
+ if (meta == null)
+ return null;
+ // dublin core
+ String lang = meta.get("dc.language");
+ if (lang != null)
+ return lang;
+ // meta content-language
+ lang = meta.get("content-language");
+ if (lang != null)
+ return lang;
+ // lang attribute
+ return meta.get("lang");
+ }
+
+ static class LanguageParser {
+
+ private String dublinCore = null;
+ private String htmlAttribute = null;
+ private String httpEquiv = null;
+ private String language = null;
+
+ LanguageParser(Node node) {
+ parse(node);
+ if (htmlAttribute != null) {
+ language = htmlAttribute;
+ } else if (dublinCore != null) {
+ language = dublinCore;
+ } else {
+ language = httpEquiv;
+ }
}
- static class LanguageParser {
-
- private String dublinCore = null;
- private String htmlAttribute = null;
- private String httpEquiv = null;
- private String language = null;
-
- LanguageParser(Node node) {
- parse(node);
- if (htmlAttribute != null) {
- language = htmlAttribute;
- } else if (dublinCore != null) {
- language = dublinCore;
- } else {
- language = httpEquiv;
- }
- }
+ String getLanguage() {
+ return language;
+ }
- String getLanguage() {
- return language;
- }
+ void parse(Node node) {
- void parse(Node node) {
+ NodeWalker walker = new NodeWalker(node);
+ while (walker.hasNext()) {
- NodeWalker walker = new NodeWalker(node);
- while (walker.hasNext()) {
+ Node currentNode = walker.nextNode();
+ String nodeName = currentNode.getNodeName();
+ short nodeType = currentNode.getNodeType();
- Node currentNode = walker.nextNode();
- String nodeName = currentNode.getNodeName();
- short nodeType = currentNode.getNodeType();
+ if (nodeType == Node.ELEMENT_NODE) {
- if (nodeType == Node.ELEMENT_NODE) {
+ // Check for the lang HTML attribute
+ if (htmlAttribute == null) {
+ htmlAttribute = parseLanguage(((Element) currentNode)
+ .getAttribute("lang"));
+ }
- // Check for the lang HTML attribute
- if (htmlAttribute == null) {
- htmlAttribute = parseLanguage(((Element) currentNode)
- .getAttribute("lang"));
- }
+ // Check for Meta
+ if ("meta".equalsIgnoreCase(nodeName)) {
+ NamedNodeMap attrs = currentNode.getAttributes();
- // Check for Meta
- if ("meta".equalsIgnoreCase(nodeName)) {
- NamedNodeMap attrs = currentNode.getAttributes();
-
- // Check for the dc.language Meta
- if (dublinCore == null) {
- for (int i = 0; i < attrs.getLength(); i++) {
- Node attrnode = attrs.item(i);
- if ("name".equalsIgnoreCase(attrnode
- .getNodeName())) {
- if ("dc.language".equalsIgnoreCase(attrnode
- .getNodeValue())) {
- Node valueattr = attrs
- .getNamedItem("content");
- if (valueattr != null) {
- dublinCore = parseLanguage(valueattr
- .getNodeValue());
- }
- }
- }
- }
- }
-
- // Check for the http-equiv content-language
- if (httpEquiv == null) {
- for (int i = 0; i < attrs.getLength(); i++) {
- Node attrnode = attrs.item(i);
- if ("http-equiv".equalsIgnoreCase(attrnode
- .getNodeName())) {
- if ("content-language".equals(attrnode
- .getNodeValue().toLowerCase())) {
- Node valueattr = attrs
- .getNamedItem("content");
- if (valueattr != null) {
- httpEquiv = parseLanguage(valueattr
- .getNodeValue());
- }
- }
- }
- }
- }
+ // Check for the dc.language Meta
+ if (dublinCore == null) {
+ for (int i = 0; i < attrs.getLength(); i++) {
+ Node attrnode = attrs.item(i);
+ if ("name".equalsIgnoreCase(attrnode.getNodeName())) {
+ if ("dc.language".equalsIgnoreCase(attrnode.getNodeValue())) {
+ Node valueattr = attrs.getNamedItem("content");
+ if (valueattr != null) {
+ dublinCore = parseLanguage(valueattr.getNodeValue());
}
+ }
}
+ }
+ }
- if ((dublinCore != null) && (htmlAttribute != null)
- && (httpEquiv != null)) {
- return;
+ // Check for the http-equiv content-language
+ if (httpEquiv == null) {
+ for (int i = 0; i < attrs.getLength(); i++) {
+ Node attrnode = attrs.item(i);
+ if ("http-equiv".equalsIgnoreCase(attrnode.getNodeName())) {
+ if ("content-language".equals(attrnode.getNodeValue()
+ .toLowerCase())) {
+ Node valueattr = attrs.getNamedItem("content");
+ if (valueattr != null) {
+ httpEquiv = parseLanguage(valueattr.getNodeValue());
+ }
+ }
}
+ }
}
+ }
}
- /**
- * Parse a language string and return an ISO 639 primary code, or
- * <code>null</code> if something wrong occurs, or if no language is
- * found.
- */
- final static String parseLanguage(String lang) {
+ if ((dublinCore != null) && (htmlAttribute != null)
+ && (httpEquiv != null)) {
+ return;
+ }
+ }
+ }
- if (lang == null) {
- return null;
- }
+ /**
+ * Parse a language string and return an ISO 639 primary code, or
+ * <code>null</code> if something wrong occurs, or if no language is found.
+ */
+ final static String parseLanguage(String lang) {
- String code = null;
- String language = null;
+ if (lang == null) {
+ return null;
+ }
- // First, split multi-valued values
- String langs[] = lang.split(",| |;|\\.|\\(|\\)|=", -1);
+ String code = null;
+ String language = null;
- int i = 0;
- while ((language == null) && (i < langs.length)) {
- // Then, get the primary code
- code = langs[i].split("-")[0];
- code = code.split("_")[0];
- // Find the ISO 639 code
- language = (String) LANGUAGES_MAP.get(code.toLowerCase());
- i++;
- }
+ // First, split multi-valued values
+ String langs[] = lang.split(",| |;|\\.|\\(|\\)|=", -1);
- return language;
- }
+ int i = 0;
+ while ((language == null) && (i < langs.length)) {
+ // Then, get the primary code
+ code = langs[i].split("-")[0];
+ code = code.split("_")[0];
+ // Find the ISO 639 code
+ language = (String) LANGUAGES_MAP.get(code.toLowerCase());
+ i++;
+ }
+ return language;
}
- public void setConf(Configuration conf) {
- this.conf = conf;
- contentMaxlength = conf.getInt("lang.analyze.max.length", -1);
- onlyCertain = conf.getBoolean("lang.identification.only.certain", false);
- String[] policy = conf.getStrings("lang.extraction.policy");
- for (int i = 0; i < policy.length; i++) {
- if (policy[i].equals("detect")) {
- detect = i;
- } else if (policy[i].equals("identify")) {
- identify = i;
- }
- }
+ }
+
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ contentMaxlength = conf.getInt("lang.analyze.max.length", -1);
+ onlyCertain = conf.getBoolean("lang.identification.only.certain", false);
+ String[] policy = conf.getStrings("lang.extraction.policy");
+ for (int i = 0; i < policy.length; i++) {
+ if (policy[i].equals("detect")) {
+ detect = i;
+ } else if (policy[i].equals("identify")) {
+ identify = i;
+ }
}
+ }
- public Configuration getConf() {
- return this.conf;
- }
+ public Configuration getConf() {
+ return this.conf;
+ }
}
\ No newline at end of file
diff --git a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
index 2bc4db436..fbfe8f978 100644
--- a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
+++ b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
@@ -16,7 +16,6 @@
*/
package org.apache.nutch.analysis.lang;
-
// Nutch imports
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
@@ -31,29 +30,27 @@ import org.apache.nutch.net.protocols.Response;
// Hadoop imports
import org.apache.hadoop.conf.Configuration;
-
/**
- * An {@link org.apache.nutch.indexer.IndexingFilter} that
- * add a <code>lang</code> (language) field to the document.
- *
+ * An {@link org.apache.nutch.indexer.IndexingFilter} that add a
+ * <code>lang</code> (language) field to the document.
+ *
* It tries to find the language of the document by:
* <ul>
- * <li>First, checking if {@link HTMLLanguageParser} add some language
- * information</li>
- * <li>Then, checking if a <code>Content-Language</code> HTTP header can be
- * found</li>
- * <li>Finaly by analyzing the document content</li>
+ * <li>First, checking if {@link HTMLLanguageParser} add some language
+ * information</li>
+ * <li>Then, checking if a <code>Content-Language</code> HTTP header can be
+ * found</li>
+ * <li>Finaly by analyzing the document content</li>
* </ul>
- *
+ *
* @author Sami Siren
* @author Jerome Charron
*/
public class LanguageIndexingFilter implements IndexingFilter {
-
private Configuration conf;
-/**
+ /**
* Constructs a new Language Indexing Filter.
*/
public LanguageIndexingFilter() {
@@ -61,15 +58,15 @@ public class LanguageIndexingFilter implements IndexingFilter {
}
// Inherited JavaDoc
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks)
- throws IndexingException {
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
// check if LANGUAGE found, possibly put there by HTMLLanguageParser
String lang = parse.getData().getParseMeta().get(Metadata.LANGUAGE);
// check if HTTP-header tels us the language
if (lang == null) {
- lang = parse.getData().getContentMeta().get(Response.CONTENT_LANGUAGE);
+ lang = parse.getData().getContentMeta().get(Response.CONTENT_LANGUAGE);
}
if (lang == null || lang.length() == 0) {
diff --git a/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java b/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
index 13ef33f49..8245151ae 100644
--- a/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
+++ b/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
@@ -19,8 +19,6 @@ package org.apache.nutch.analysis.lang;
import java.io.BufferedReader;
import java.io.InputStreamReader;
-
-
// Nutch imports
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.parse.Parse;
@@ -31,7 +29,6 @@ import org.apache.tika.language.LanguageIdentifier;
import org.junit.Assert;
import org.junit.Test;
-
public class TestHTMLLanguageParser {
private static String URL = "http://foo.bar/";
@@ -47,7 +44,7 @@ public class TestHTMLLanguageParser {
String metalanguages[] = { "fi", "en", "en" };
/**
- * Test parsing of language identifiers from html
+ * Test parsing of language identifiers from html
**/
@Test
public void testMetaHTMLParsing() {
@@ -58,7 +55,8 @@ public class TestHTMLLanguageParser {
for (int t = 0; t < docs.length; t++) {
Content content = getContent(docs[t]);
Parse parse = parser.parse(content).get(content.getUrl());
- Assert.assertEquals(metalanguages[t], (String) parse.getData().getParseMeta().get(Metadata.LANGUAGE));
+ Assert.assertEquals(metalanguages[t], (String) parse.getData()
+ .getParseMeta().get(Metadata.LANGUAGE));
}
} catch (Exception e) {
e.printStackTrace(System.out);
@@ -70,65 +68,38 @@ public class TestHTMLLanguageParser {
/** Test of <code>LanguageParser.parseLanguage(String)</code> method. */
@Test
public void testParseLanguage() {
- String tests[][] = {
- { "(SCHEME=ISO.639-1) sv", "sv" },
- { "(SCHEME=RFC1766) sv-FI", "sv" },
- { "(SCHEME=Z39.53) SWE", "sv" },
- { "EN_US, SV, EN, EN_UK", "en" },
- { "English Swedish", "en" },
- { "English, swedish", "en" },
- { "English,Swedish", "en" },
- { "Other (Svenska)", "sv" },
- { "SE", "se" },
- { "SV", "sv" },
- { "SV charset=iso-8859-1", "sv" },
- { "SV-FI", "sv" },
- { "SV; charset=iso-8859-1", "sv" },
- { "SVE", "sv" },
- { "SW", "sw" },
- { "SWE", "sv" },
- { "SWEDISH", "sv" },
- { "Sv", "sv" },
- { "Sve", "sv" },
- { "Svenska", "sv" },
- { "Swedish", "sv" },
- { "Swedish, svenska", "sv" },
- { "en, sv", "en" },
- { "sv", "sv" },
- { "sv, be, dk, de, fr, no, pt, ch, fi, en", "sv" },
- { "sv,en", "sv" },
- { "sv-FI", "sv" },
- { "sv-SE", "sv" },
- { "sv-en", "sv" },
- { "sv-fi", "sv" },
- { "sv-se", "sv" },
- { "sv; Content-Language: sv", "sv" },
- { "sv_SE", "sv" },
- { "sve", "sv" },
- { "svenska, swedish, engelska, english", "sv" },
- { "sw", "sw" },
- { "swe", "sv" },
- { "swe.SPR.", "sv" },
- { "sweden", "sv" },
- { "swedish", "sv" },
- { "swedish,", "sv" },
- { "text/html; charset=sv-SE", "sv" },
- { "text/html; sv", "sv" },
- { "torp, stuga, uthyres, bed & breakfast", null }
- };
-
- for (int i=0; i<44; i++) {
- Assert.assertEquals(tests[i][1], HTMLLanguageParser.LanguageParser.parseLanguage(tests[i][0]));
+ String tests[][] = { { "(SCHEME=ISO.639-1) sv", "sv" },
+ { "(SCHEME=RFC1766) sv-FI", "sv" }, { "(SCHEME=Z39.53) SWE", "sv" },
+ { "EN_US, SV, EN, EN_UK", "en" }, { "English Swedish", "en" },
+ { "English, swedish", "en" }, { "English,Swedish", "en" },
+ { "Other (Svenska)", "sv" }, { "SE", "se" }, { "SV", "sv" },
+ { "SV charset=iso-8859-1", "sv" }, { "SV-FI", "sv" },
+ { "SV; charset=iso-8859-1", "sv" }, { "SVE", "sv" }, { "SW", "sw" },
+ { "SWE", "sv" }, { "SWEDISH", "sv" }, { "Sv", "sv" }, { "Sve", "sv" },
+ { "Svenska", "sv" }, { "Swedish", "sv" }, { "Swedish, svenska", "sv" },
+ { "en, sv", "en" }, { "sv", "sv" },
+ { "sv, be, dk, de, fr, no, pt, ch, fi, en", "sv" }, { "sv,en", "sv" },
+ { "sv-FI", "sv" }, { "sv-SE", "sv" }, { "sv-en", "sv" },
+ { "sv-fi", "sv" }, { "sv-se", "sv" },
+ { "sv; Content-Language: sv", "sv" }, { "sv_SE", "sv" },
+ { "sve", "sv" }, { "svenska, swedish, engelska, english", "sv" },
+ { "sw", "sw" }, { "swe", "sv" }, { "swe.SPR.", "sv" },
+ { "sweden", "sv" }, { "swedish", "sv" }, { "swedish,", "sv" },
+ { "text/html; charset=sv-SE", "sv" }, { "text/html; sv", "sv" },
+ { "torp, stuga, uthyres, bed & breakfast", null } };
+
+ for (int i = 0; i < 44; i++) {
+ Assert.assertEquals(tests[i][1],
+ HTMLLanguageParser.LanguageParser.parseLanguage(tests[i][0]));
}
}
-
-
+
private Content getContent(String text) {
Metadata meta = new Metadata();
meta.add("Content-Type", "text/html");
- return new Content(URL, BASE, text.getBytes(), "text/html", meta, NutchConfiguration.create());
+ return new Content(URL, BASE, text.getBytes(), "text/html", meta,
+ NutchConfiguration.create());
}
-
@Test
public void testLanguageIndentifier() {
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java
index 6ef07254f..b1103f81f 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/BlockedException.java
@@ -18,7 +18,7 @@
package org.apache.nutch.protocol.http.api;
public class BlockedException extends HttpException {
-
+
public BlockedException(String msg) {
super(msg);
}
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 0a56a30a7..557ed79f0 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
@@ -47,20 +47,20 @@ import org.apache.hadoop.io.Text;
import crawlercommons.robots.BaseRobotRules;
public abstract class HttpBase implements Protocol {
-
+
public static final Text RESPONSE_TIME = new Text("_rs_");
public static final int BUFFER_SIZE = 8 * 1024;
-
+
private static final byte[] EMPTY_CONTENT = new byte[0];
private HttpRobotRulesParser robots = null;
-
- /** The proxy hostname. */
+
+ /** The proxy hostname. */
protected String proxyHost = null;
/** The proxy port. */
- protected int proxyPort = 8080;
+ protected int proxyPort = 8080;
/** Indicates if a proxy is used */
protected boolean useProxy = false;
@@ -69,29 +69,27 @@ public abstract class HttpBase implements Protocol {
protected int timeout = 10000;
/** The length limit for downloaded content, in bytes. */
- protected int maxContent = 64 * 1024;
+ protected int maxContent = 64 * 1024;
/** The Nutch 'User-Agent' request header */
- protected String userAgent = getAgentString(
- "NutchCVS", null, "Nutch",
- "http://nutch.apache.org/bot.html",
+ protected String userAgent = getAgentString("NutchCVS", null, "Nutch",
+ "http://nutch.apache.org/bot.html", "[email protected]");
/** The "Accept-Language" request header value. */
protected String acceptLanguage = "en-us,en-gb,en;q=0.7,*;q=0.3";
/** The "Accept" request header value. */
protected String accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
-
+
/** The default logger */
private final static Logger LOGGER = LoggerFactory.getLogger(HttpBase.class);
/** The specified logger */
private Logger logger = LOGGER;
-
+
/** The nutch configuration */
private Configuration conf = null;
-
+
/** Do we use HTTP/1.1? */
protected boolean useHttp11 = false;
@@ -99,14 +97,14 @@ public abstract class HttpBase implements Protocol {
* Record response time in CrawlDatum's meta data, see property
* http.store.responsetime.
*/
- protected boolean responseTime = true;
-
+ protected boolean responseTime = true;
+
/** Skip page if Crawl-Delay longer than this value. */
protected long maxCrawlDelay = -1L;
-
+
/** Which TLS/SSL protocols to support */
protected Set<String> tlsPreferredProtocols;
-
+
/** Which TLS/SSL cipher suites to support */
protected Set<String> tlsPreferredCipherSuites;
@@ -114,7 +112,7 @@ public abstract class HttpBase implements Protocol {
public HttpBase() {
this(null);
}
-
+
/** Creates a new instance of HttpBase */
public HttpBase(Logger logger) {
if (logger != null) {
@@ -122,134 +120,168 @@ public abstract class HttpBase implements Protocol {
}
robots = new HttpRobotRulesParser();
}
-
+
// Inherited Javadoc
public void setConf(Configuration 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.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.acceptLanguage = conf.get("http.accept.language", acceptLanguage);
- this.accept = conf.get("http.accept", accept);
- // backward-compatible default setting
- this.useHttp11 = conf.getBoolean("http.useHttp11", false);
- this.responseTime = conf.getBoolean("http.store.responsetime", true);
- this.robots.setConf(conf);
-
- String[] protocols = conf.getStrings("http.tls.supported.protocols", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3");
- String[] ciphers = conf.getStrings("http.tls.supported.cipher.suites",
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
- "TLS_RSA_WITH_AES_256_CBC_SHA256","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",
- "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_DHE_DSS_WITH_AES_256_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
- "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256","TLS_RSA_WITH_AES_128_CBC_SHA256",
- "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
- "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
- "TLS_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
- "TLS_DHE_RSA_WITH_AES_128_CBC_SHA","TLS_DHE_DSS_WITH_AES_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
- "TLS_ECDHE_RSA_WITH_RC4_128_SHA","SSL_RSA_WITH_RC4_128_SHA","TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
- "TLS_ECDH_RSA_WITH_RC4_128_SHA","TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
- "SSL_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
- "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA","SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA","SSL_RSA_WITH_RC4_128_MD5",
- "TLS_EMPTY_RENEGOTIATION_INFO_SCSV","TLS_RSA_WITH_NULL_SHA256","TLS_ECDHE_ECDSA_WITH_NULL_SHA",
- "TLS_ECDHE_RSA_WITH_NULL_SHA","SSL_RSA_WITH_NULL_SHA","TLS_ECDH_ECDSA_WITH_NULL_SHA","TLS_ECDH_RSA_WITH_NULL_SHA",
- "SSL_RSA_WITH_NULL_MD5","SSL_RSA_WITH_DES_CBC_SHA","SSL_DHE_RSA_WITH_DES_CBC_SHA","SSL_DHE_DSS_WITH_DES_CBC_SHA",
- "TLS_KRB5_WITH_RC4_128_SHA","TLS_KRB5_WITH_RC4_128_MD5","TLS_KRB5_WITH_3DES_EDE_CBC_SHA","TLS_KRB5_WITH_3DES_EDE_CBC_MD5",
- "TLS_KRB5_WITH_DES_CBC_SHA","TLS_KRB5_WITH_DES_CBC_MD5");
-
- tlsPreferredProtocols = new HashSet<String>(Arrays.asList(protocols));
- tlsPreferredCipherSuites = new HashSet<String>(Arrays.asList(ciphers));
-
- logConf();
+ 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.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.acceptLanguage = conf.get("http.accept.language", acceptLanguage);
+ this.accept = conf.get("http.accept", accept);
+ // backward-compatible default setting
+ this.useHttp11 = conf.getBoolean("http.useHttp11", false);
+ this.responseTime = conf.getBoolean("http.store.responsetime", true);
+ this.robots.setConf(conf);
+
+ String[] protocols = conf.getStrings("http.tls.supported.protocols",
+ "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3");
+ String[] ciphers = conf.getStrings("http.tls.supported.cipher.suites",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
+ "TLS_RSA_WITH_AES_256_CBC_SHA256",
+ "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",
+ "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",
+ "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
+ "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA",
+ "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
+ "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
+ "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
+ "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
+ "TLS_RSA_WITH_AES_128_CBC_SHA256",
+ "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
+ "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",
+ "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
+ "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
+ "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
+ "SSL_RSA_WITH_RC4_128_SHA", "TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
+ "TLS_ECDH_RSA_WITH_RC4_128_SHA",
+ "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", "SSL_RSA_WITH_3DES_EDE_CBC_SHA",
+ "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",
+ "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
+ "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
+ "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA", "SSL_RSA_WITH_RC4_128_MD5",
+ "TLS_EMPTY_RENEGOTIATION_INFO_SCSV", "TLS_RSA_WITH_NULL_SHA256",
+ "TLS_ECDHE_ECDSA_WITH_NULL_SHA", "TLS_ECDHE_RSA_WITH_NULL_SHA",
+ "SSL_RSA_WITH_NULL_SHA", "TLS_ECDH_ECDSA_WITH_NULL_SHA",
+ "TLS_ECDH_RSA_WITH_NULL_SHA", "SSL_RSA_WITH_NULL_MD5",
+ "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA",
+ "SSL_DHE_DSS_WITH_DES_CBC_SHA", "TLS_KRB5_WITH_RC4_128_SHA",
+ "TLS_KRB5_WITH_RC4_128_MD5", "TLS_KRB5_WITH_3DES_EDE_CBC_SHA",
+ "TLS_KRB5_WITH_3DES_EDE_CBC_MD5", "TLS_KRB5_WITH_DES_CBC_SHA",
+ "TLS_KRB5_WITH_DES_CBC_MD5");
+
+ tlsPreferredProtocols = new HashSet<String>(Arrays.asList(protocols));
+ tlsPreferredCipherSuites = new HashSet<String>(Arrays.asList(ciphers));
+
+ logConf();
}
// Inherited Javadoc
public Configuration getConf() {
return this.conf;
}
-
+
public ProtocolOutput getProtocolOutput(Text url, CrawlDatum datum) {
-
+
String urlString = url.toString();
try {
URL u = new URL(urlString);
-
+
long startTime = System.currentTimeMillis();
Response response = getResponse(u, datum, false); // make a request
-
- if(this.responseTime) {
+
+ if (this.responseTime) {
int elapsedTime = (int) (System.currentTimeMillis() - startTime);
datum.getMetaData().put(RESPONSE_TIME, new IntWritable(elapsedTime));
}
-
+
int code = response.getCode();
byte[] content = response.getContent();
Content c = new Content(u.toString(), u.toString(),
- (content == null ? EMPTY_CONTENT : content),
- response.getHeader("Content-Type"),
- response.getHeaders(), this.conf);
-
+ (content == null ? EMPTY_CONTENT : content),
+ response.getHeader("Content-Type"), response.getHeaders(), this.conf);
+
if (code == 200) { // got a good response
return new ProtocolOutput(c); // return it
-
+
} else if (code >= 300 && code < 400) { // handle redirect
String location = response.getHeader("Location");
// some broken servers, such as MS IIS, use lowercase header name...
- if (location == null) location = response.getHeader("location");
- if (location == null) location = "";
+ if (location == null)
+ location = response.getHeader("location");
+ if (location == null)
+ location = "";
u = new URL(u, location);
int protocolStatusCode;
switch (code) {
- case 300: // multiple choices, preferred value in Location
- protocolStatusCode = ProtocolStatus.MOVED;
- break;
- case 301: // moved permanently
- case 305: // use proxy (Location is URL of proxy)
- protocolStatusCode = ProtocolStatus.MOVED;
- break;
- case 302: // found (temporarily moved)
- case 303: // see other (redirect after POST)
- case 307: // temporary redirect
- protocolStatusCode = ProtocolStatus.TEMP_MOVED;
- break;
- case 304: // not modified
- protocolStatusCode = ProtocolStatus.NOTMODIFIED;
- break;
- default:
- protocolStatusCode = ProtocolStatus.MOVED;
+ case 300: // multiple choices, preferred value in Location
+ protocolStatusCode = ProtocolStatus.MOVED;
+ break;
+ case 301: // moved permanently
+ case 305: // use proxy (Location is URL of proxy)
+ protocolStatusCode = ProtocolStatus.MOVED;
+ break;
+ case 302: // found (temporarily moved)
+ case 303: // see other (redirect after POST)
+ case 307: // temporary redirect
+ protocolStatusCode = ProtocolStatus.TEMP_MOVED;
+ break;
+ case 304: // not modified
+ protocolStatusCode = ProtocolStatus.NOTMODIFIED;
+ break;
+ default:
+ protocolStatusCode = ProtocolStatus.MOVED;
}
// handle this in the higher layer.
return new ProtocolOutput(c, new ProtocolStatus(protocolStatusCode, u));
} else if (code == 400) { // bad request, mark as GONE
- if (logger.isTraceEnabled()) { logger.trace("400 Bad request: " + u); }
+ if (logger.isTraceEnabled()) {
+ logger.trace("400 Bad request: " + u);
+ }
return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, u));
- } else if (code == 401) { // requires authorization, but no valid auth provided.
- if (logger.isTraceEnabled()) { logger.trace("401 Authentication Required"); }
- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.ACCESS_DENIED, "Authentication required: "
+ } else if (code == 401) { // requires authorization, but no valid auth
+ // provided.
+ if (logger.isTraceEnabled()) {
+ logger.trace("401 Authentication Required");
+ }
+ return new ProtocolOutput(c, new ProtocolStatus(
+ ProtocolStatus.ACCESS_DENIED, "Authentication required: "
+ urlString));
} else if (code == 404) {
- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.NOTFOUND, u));
+ return new ProtocolOutput(c, new ProtocolStatus(
+ ProtocolStatus.NOTFOUND, u));
} else if (code == 410) { // permanently GONE
- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, "Http: " + code + " url=" + u));
+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE,
+ "Http: " + code + " url=" + u));
} else {
- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.EXCEPTION, "Http code=" + code + ", url="
- + u));
+ return new ProtocolOutput(c, new ProtocolStatus(
+ ProtocolStatus.EXCEPTION, "Http code=" + code + ", url=" + u));
}
} catch (Throwable e) {
logger.error("Failed to get protocol output", e);
return new ProtocolOutput(null, new ProtocolStatus(e));
}
}
-
- /* -------------------------- *
- * </implementation:Protocol> *
- * -------------------------- */
+ /*
+ * -------------------------- * </implementation:Protocol> *
+ * --------------------------
+ */
public String getProxyHost() {
return proxyHost;
@@ -274,70 +306,69 @@ public abstract class HttpBase implements Protocol {
public String getUserAgent() {
return userAgent;
}
-
- /** Value of "Accept-Language" request header sent by Nutch.
+
+ /**
+ * Value of "Accept-Language" request header sent by Nutch.
+ *
* @return The value of the header "Accept-Language" header.
*/
public String getAcceptLanguage() {
- return acceptLanguage;
+ return acceptLanguage;
}
public String getAccept() {
- return accept;
+ return accept;
}
public boolean getUseHttp11() {
return useHttp11;
}
-
+
public Set<String> getTlsPreferredCipherSuites() {
return tlsPreferredCipherSuites;
}
-
+
public Set<String> getTlsPreferredProtocols() {
return tlsPreferredProtocols;
}
- private static String getAgentString(String agentName,
- String agentVersion,
- String agentDesc,
- String agentURL,
- String agentEmail) {
-
- if ( (agentName == null) || (agentName.trim().length() == 0) ) {
+ private static String getAgentString(String agentName, String agentVersion,
+ String agentDesc, String agentURL, String agentEmail) {
+
+ if ((agentName == null) || (agentName.trim().length() == 0)) {
// TODO : NUTCH-258
if (LOGGER.isErrorEnabled()) {
LOGGER.error("No User-Agent string set (http.agent.name)!");
}
}
-
- StringBuffer buf= new StringBuffer();
-
+
+ StringBuffer buf = new StringBuffer();
+
buf.append(agentName);
if (agentVersion != null) {
buf.append("/");
buf.append(agentVersion);
}
- if ( ((agentDesc != null) && (agentDesc.length() != 0))
- || ((agentEmail != null) && (agentEmail.length() != 0))
- || ((agentURL != null) && (agentURL.length() != 0)) ) {
+ if (((agentDesc != null) && (agentDesc.length() != 0))
+ || ((agentEmail != null) && (agentEmail.length() != 0))
+ || ((agentURL != null) && (agentURL.length() != 0))) {
buf.append(" (");
-
+
if ((agentDesc != null) && (agentDesc.length() != 0)) {
buf.append(agentDesc);
- if ( (agentURL != null) || (agentEmail != null) )
+ if ((agentURL != null) || (agentEmail != null))
buf.append("; ");
}
-
+
if ((agentURL != null) && (agentURL.length() != 0)) {
buf.append(agentURL);
if (agentEmail != null)
buf.append("; ");
}
-
+
if ((agentEmail != null) && (agentEmail.length() != 0))
buf.append(agentEmail);
-
+
buf.append(")");
}
return buf.toString();
@@ -354,52 +385,59 @@ public abstract class HttpBase implements Protocol {
logger.info("http.accept = " + accept);
}
}
-
- public byte[] processGzipEncoded(byte[] compressed, URL url) throws IOException {
- if (LOGGER.isTraceEnabled()) { LOGGER.trace("uncompressing...."); }
+ public byte[] processGzipEncoded(byte[] compressed, URL url)
+ throws IOException {
+
+ if (LOGGER.isTraceEnabled()) {
+ LOGGER.trace("uncompressing....");
+ }
// content can be empty (i.e. redirection) in which case
// there is nothing to unzip
if (compressed.length == 0)
return compressed;
-
+
byte[] content;
if (getMaxContent() >= 0) {
- content = GZIPUtils.unzipBestEffort(compressed, getMaxContent());
+ content = GZIPUtils.unzipBestEffort(compressed, getMaxContent());
} else {
- content = GZIPUtils.unzipBestEffort(compressed);
- }
+ content = GZIPUtils.unzipBestEffort(compressed);
+ }
if (content == null)
throw new IOException("unzipBestEffort returned null");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("fetched " + compressed.length
- + " bytes of compressed content (expanded to "
- + content.length + " bytes) from " + url);
+ + " bytes of compressed content (expanded to " + content.length
+ + " bytes) from " + url);
}
return content;
}
- public byte[] processDeflateEncoded(byte[] compressed, URL url) throws IOException {
+ public byte[] processDeflateEncoded(byte[] compressed, URL url)
+ throws IOException {
// content can be empty (i.e. redirection) in which case
// there is nothing to deflate
if (compressed.length == 0)
return compressed;
-
- if (LOGGER.isTraceEnabled()) { LOGGER.trace("inflating...."); }
- byte[] content = DeflateUtils.inflateBestEffort(compressed, getMaxContent());
+ if (LOGGER.isTraceEnabled()) {
+ LOGGER.trace("inflating....");
+ }
+
+ byte[] content = DeflateUtils
+ .inflateBestEffort(compressed, getMaxContent());
if (content == null)
throw new IOException("inflateBestEffort returned null");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("fetched " + compressed.length
- + " bytes of compressed content (expanded to "
- + content.length + " bytes) from " + url);
+ + " bytes of compressed content (expanded to " + content.length
+ + " bytes) from " + url);
}
return content;
}
@@ -407,14 +445,14 @@ public abstract class HttpBase implements Protocol {
protected static void main(HttpBase http, String[] args) throws Exception {
boolean verbose = false;
String url = null;
-
+
String usage = "Usage: Http [-verbose] [-timeout N] url";
-
+
if (args.length == 0) {
System.err.println(usage);
System.exit(-1);
}
-
+
for (int i = 0; i < args.length; i++) { // parse command line
if (args[i].equals("-timeout")) { // found -timeout option
http.timeout = Integer.parseInt(args[++i]) * 1000;
@@ -423,35 +461,34 @@ public abstract class HttpBase implements Protocol {
} else if (i != args.length - 1) {
System.err.println(usage);
System.exit(-1);
- } else // root is required parameter
+ } else
+ // root is required parameter
url = args[i];
}
-
-// if (verbose) {
-// LOGGER.setLevel(Level.FINE);
-// }
-
- ProtocolOutput out = http.getProtocolOutput(new Text(url), new CrawlDatum());
+
+ // if (verbose) {
+ // LOGGER.setLevel(Level.FINE);
+ // }
+
+ ProtocolOutput out = http
+ .getProtocolOutput(new Text(url), new CrawlDatum());
Content content = out.getContent();
-
+
System.out.println("Status: " + out.getStatus());
if (content != null) {
System.out.println("Content Type: " + content.getContentType());
- System.out.println("Content Length: " +
- content.getMetadata().get(Response.CONTENT_LENGTH));
+ System.out.println("Content Length: "
+ + content.getMetadata().get(Response.CONTENT_LENGTH));
System.out.println("Content:");
String text = new String(content.getContent());
System.out.println(text);
- }
+ }
}
-
- protected abstract Response getResponse(URL url,
- CrawlDatum datum,
- boolean followRedirects)
- throws ProtocolException, IOException;
+
+ protected abstract Response getResponse(URL url, CrawlDatum datum,
+ boolean followRedirects) throws ProtocolException, IOException;
public BaseRobotRules getRobotRules(Text url, CrawlDatum datum) {
return robots.getRobotRulesSet(this, url);
}
}
-
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java
index 4d029830d..ff7ef5b3c 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java
@@ -19,7 +19,6 @@ package org.apache.nutch.protocol.http.api;
// Nutch imports
import org.apache.nutch.protocol.ProtocolException;
-
public class HttpException extends ProtocolException {
public HttpException() {
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
index 55133413e..63c8d5530 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
@@ -32,36 +32,41 @@ import crawlercommons.robots.BaseRobotRules;
import crawlercommons.robots.SimpleRobotRules;
/**
- * This class is used for parsing robots for urls belonging to HTTP protocol.
- * It extends the generic {@link RobotRulesParser} class and contains
- * Http protocol specific implementation for obtaining the robots file.
+ * This class is used for parsing robots for urls belonging to HTTP protocol. It
+ * extends the generic {@link RobotRulesParser} class and contains Http protocol
+ * specific implementation for obtaining the robots file.
*/
public class HttpRobotRulesParser extends RobotRulesParser {
-
- public static final Logger LOG = LoggerFactory.getLogger(HttpRobotRulesParser.class);
+
+ public static final Logger LOG = LoggerFactory
+ .getLogger(HttpRobotRulesParser.class);
protected boolean allowForbidden = false;
- HttpRobotRulesParser() { }
+ HttpRobotRulesParser() {
+ }
public HttpRobotRulesParser(Configuration conf) {
- setConf(conf);
+ setConf(conf);
}
-
+
public void setConf(Configuration conf) {
- super.setConf(conf);
- allowForbidden = conf.getBoolean("http.robots.403.allow", true);
+ super.setConf(conf);
+ allowForbidden = conf.getBoolean("http.robots.403.allow", true);
}
/** Compose unique key to store and access robot rules in cache for given URL */
protected static String getCacheKey(URL url) {
- String protocol = url.getProtocol().toLowerCase(); // normalize to lower case
- String host = url.getHost().toLowerCase(); // normalize to lower case
+ String protocol = url.getProtocol().toLowerCase(); // normalize to lower
+ // case
+ String host = url.getHost().toLowerCase(); // normalize to lower case
int port = url.getPort();
if (port == -1) {
port = url.getDefaultPort();
}
- /* Robot rules apply only to host, protocol, and port where robots.txt is
- * hosted (cf. NUTCH-1752). Consequently */
+ /*
+ * Robot rules apply only to host, protocol, and port where robots.txt is
+ * hosted (cf. NUTCH-1752). Consequently
+ */
String cacheKey = protocol + ":" + host + ":" + port;
return cacheKey;
}
@@ -77,7 +82,7 @@ public class HttpRobotRulesParser extends RobotRulesParser {
* The {@link Protocol} object
* @param url
* URL robots.txt applies to
- *
+ *
* @return {@link BaseRobotRules} holding the rules from robots.txt
*/
public BaseRobotRules getRobotRulesSet(Protocol http, URL url) {
@@ -86,13 +91,15 @@ public class HttpRobotRulesParser extends RobotRulesParser {
BaseRobotRules robotRules = (SimpleRobotRules) CACHE.get(cacheKey);
boolean cacheRule = true;
-
- if (robotRules == null) { // cache miss
+
+ if (robotRules == null) { // cache miss
URL redir = null;
- if (LOG.isTraceEnabled()) { LOG.trace("cache miss " + url); }
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("cache miss " + url);
+ }
try {
- Response response = ((HttpBase)http).getResponse(new URL(url, "/robots.txt"),
- new CrawlDatum(), true);
+ Response response = ((HttpBase) http).getResponse(new URL(url,
+ "/robots.txt"), new CrawlDatum(), true);
// try one level of redirection ?
if (response.getCode() == 301 || response.getCode() == 302) {
String redirection = response.getHeader("Location");
@@ -107,23 +114,23 @@ public class HttpRobotRulesParser extends RobotRulesParser {
} else {
redir = new URL(redirection);
}
-
- response = ((HttpBase)http).getResponse(redir, new CrawlDatum(), true);
+
+ response = ((HttpBase) http).getResponse(redir, new CrawlDatum(),
+ true);
}
}
- if (response.getCode() == 200) // found rules: parse them
- robotRules = parseRules(url.toString(), response.getContent(),
- response.getHeader("Content-Type"),
- agentNames);
+ if (response.getCode() == 200) // found rules: parse them
+ robotRules = parseRules(url.toString(), response.getContent(),
+ response.getHeader("Content-Type"), agentNames);
- else if ( (response.getCode() == 403) && (!allowForbidden) )
- robotRules = FORBID_ALL_RULES; // use forbid all
+ else if ((response.getCode() == 403) && (!allowForbidden))
+ robotRules = FORBID_ALL_RULES; // use forbid all
else if (response.getCode() >= 500) {
cacheRule = false;
robotRules = EMPTY_RULES;
- }else
- robotRules = EMPTY_RULES; // use default rules
+ } else
+ robotRules = EMPTY_RULES; // use default rules
} catch (Throwable t) {
if (LOG.isInfoEnabled()) {
LOG.info("Couldn't get robots.txt for " + url + ": " + t.toString());
@@ -133,7 +140,7 @@ public class HttpRobotRulesParser extends RobotRulesParser {
}
if (cacheRule) {
- CACHE.put(cacheKey, robotRules); // cache rules for host
+ CACHE.put(cacheKey, robotRules); // cache rules for host
if (redir != null && !redir.getHost().equalsIgnoreCase(url.getHost())) {
// cache also for the redirected host
CACHE.put(getCacheKey(redir), robotRules);
diff --git a/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java b/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
index 31b8dbba8..23e4ef63c 100644
--- a/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
+++ b/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
@@ -23,10 +23,10 @@ import org.junit.Test;
import crawlercommons.robots.BaseRobotRules;
/**
- * JUnit test case which tests
- * 1. that robots filtering is performed correctly as per the agent name
- * 2. that crawl delay is extracted correctly from the robots file
- *
+ * JUnit test case which tests 1. that robots filtering is performed correctly
+ * as per the agent name 2. that crawl delay is extracted correctly from the
+ * robots file
+ *
*/
public class TestRobotRulesParser {
@@ -36,39 +36,32 @@ public class TestRobotRulesParser {
private static final String UNKNOWN_AGENT = "AgentABC";
private static final String CR = "\r";
- private static final String ROBOTS_STRING =
- "User-Agent: Agent1 #foo" + CR
- + "Disallow: /a" + CR
- + "Disallow: /b/a" + CR
- + "#Disallow: /c" + CR
- + "Crawl-delay: 10" + CR // set crawl delay for Agent1 as 10 sec
- + "" + CR
- + "" + CR
- + "User-Agent: Agent2" + CR
- + "Disallow: /a/bloh" + CR
- + "Disallow: /c" + CR
- + "Disallow: /foo" + CR
- + "Crawl-delay: 20" + CR
- + "" + CR
- + "User-Agent: *" + CR
- + "Disallow: /foo/bar/" + CR; // no crawl delay for other agents
+ private static final String ROBOTS_STRING = "User-Agent: Agent1 #foo" + CR
+ + "Disallow: /a" + CR + "Disallow: /b/a" + CR + "#Disallow: /c"
+ + CR
+ + "Crawl-delay: 10"
+ + CR // set crawl delay for Agent1 as 10 sec
+ + "" + CR + "" + CR + "User-Agent: Agent2" + CR + "Disallow: /a/bloh"
+ + CR + "Disallow: /c" + CR + "Disallow: /foo" + CR + "Crawl-delay: 20"
+ + CR + "" + CR + "User-Agent: *" + CR + "Disallow: /foo/bar/" + CR; // no
+ // crawl
+ // delay
+ // for
+ // other
+ // agents
private static final String[] TEST_PATHS = new String[] {
- "http://example.com/a",
- "http://example.com/a/bloh/foo.html",
- "http://example.com/b",
- "http://example.com/c",
- "http://example.com/b/a/index.html",
- "http://example.com/foo/bar/baz.html"
- };
-
- private static final boolean[] RESULTS = new boolean[] {
- false, // /a
- false, // /a/bloh/foo.html
- true, // /b
- true, // /c
- false, // /b/a/index.html
- true // /foo/bar/baz.html
+ "http://example.com/a", "http://example.com/a/bloh/foo.html",
+ "http://example.com/b", "http://example.com/c",
+ "http://example.com/b/a/index.html",
+ "http://example.com/foo/bar/baz.html" };
+
+ private static final boolean[] RESULTS = new boolean[] { false, // /a
+ false, // /a/bloh/foo.html
+ true, // /b
+ true, // /c
+ false, // /b/a/index.html
+ true // /foo/bar/baz.html
};
private HttpRobotRulesParser parser;
@@ -79,41 +72,52 @@ public class TestRobotRulesParser {
}
/**
- * Test that the robots rules are interpreted correctly by the robots rules parser.
+ * Test that the robots rules are interpreted correctly by the robots rules
+ * parser.
*/
@Test
public void testRobotsAgent() {
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(), CONTENT_TYPE, SINGLE_AGENT);
-
- for(int counter = 0; counter < TEST_PATHS.length; counter++) {
- Assert.assertTrue("testing on agent (" + SINGLE_AGENT + "), and "
- + "path " + TEST_PATHS[counter]
- + " got " + rules.isAllowed(TEST_PATHS[counter]),
- rules.isAllowed(TEST_PATHS[counter]) == RESULTS[counter]);
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
+ CONTENT_TYPE, SINGLE_AGENT);
+
+ for (int counter = 0; counter < TEST_PATHS.length; counter++) {
+ Assert.assertTrue(
+ "testing on agent (" + SINGLE_AGENT + "), and " + "path "
+ + TEST_PATHS[counter] + " got "
+ + rules.isAllowed(TEST_PATHS[counter]),
+ rules.isAllowed(TEST_PATHS[counter]) == RESULTS[counter]);
}
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(), CONTENT_TYPE, MULTIPLE_AGENTS);
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
+ CONTENT_TYPE, MULTIPLE_AGENTS);
- for(int counter = 0; counter < TEST_PATHS.length; counter++) {
- Assert.assertTrue("testing on agents (" + MULTIPLE_AGENTS + "), and "
- + "path " + TEST_PATHS[counter]
- + " got " + rules.isAllowed(TEST_PATHS[counter]),
- rules.isAllowed(TEST_PATHS[counter]) == RESULTS[counter]);
+ for (int counter = 0; counter < TEST_PATHS.length; counter++) {
+ Assert.assertTrue(
+ "testing on agents (" + MULTIPLE_AGENTS + "), and " + "path "
+ + TEST_PATHS[counter] + " got "
+ + rules.isAllowed(TEST_PATHS[counter]),
+ rules.isAllowed(TEST_PATHS[counter]) == RESULTS[counter]);
}
}
/**
- * Test that the crawl delay is extracted from the robots file for respective agent.
- * If its not specified for a given agent, default value must be returned.
+ * Test that the crawl delay is extracted from the robots file for respective
+ * agent. If its not specified for a given agent, default value must be
+ * returned.
*/
@Test
public void testCrawlDelay() {
- // for SINGLE_AGENT, the crawl delay of 10 sec ie. 10000 msec must be returned by the parser
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(), CONTENT_TYPE, SINGLE_AGENT);
- Assert.assertTrue("testing crawl delay for agent "+ SINGLE_AGENT +" : ", (rules.getCrawlDelay() == 10000));
+ // for SINGLE_AGENT, the crawl delay of 10 sec ie. 10000 msec must be
+ // returned by the parser
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
+ CONTENT_TYPE, SINGLE_AGENT);
+ Assert.assertTrue("testing crawl delay for agent " + SINGLE_AGENT + " : ",
+ (rules.getCrawlDelay() == 10000));
// for UNKNOWN_AGENT, the default crawl delay must be returned.
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(), CONTENT_TYPE, UNKNOWN_AGENT);
- Assert.assertTrue("testing crawl delay for agent "+ UNKNOWN_AGENT +" : ", (rules.getCrawlDelay() == Long.MIN_VALUE));
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
+ CONTENT_TYPE, UNKNOWN_AGENT);
+ Assert.assertTrue("testing crawl delay for agent " + UNKNOWN_AGENT + " : ",
+ (rules.getCrawlDelay() == Long.MIN_VALUE));
}
}
diff --git a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexRule.java b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexRule.java
index f4044f141..1a7bf2710 100644
--- a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexRule.java
+++ b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexRule.java
@@ -16,11 +16,9 @@
*/
package org.apache.nutch.urlfilter.api;
-
-
/**
* A generic regular expression rule.
- *
+ *
* @author J&eacute;r&ocirc;me Charron
*/
public abstract class RegexRule {
@@ -29,13 +27,15 @@ public abstract class RegexRule {
/**
* Constructs a new regular expression rule.
- *
- * @param sign specifies if this rule must filter-in or filter-out.
- * A <code>true</code> value means that any url matching this rule
- * must be accepted, a <code>false</code> value means that any url
- * matching this rule must be rejected.
- * @param regex is the regular expression used for matching (see
- * {@link #match(String)} method).
+ *
+ * @param sign
+ * specifies if this rule must filter-in or filter-out. A
+ * <code>true</code> value means that any url matching this rule must
+ * be accepted, a <code>false</code> value means that any url
+ * matching this rule must be rejected.
+ * @param regex
+ * is the regular expression used for matching (see
+ * {@link #match(String)} method).
*/
protected RegexRule(boolean sign, String regex) {
this.sign = sign;
@@ -43,19 +43,22 @@ public abstract class RegexRule {
/**
* Return if this rule is used for filtering-in or out.
- *
+ *
* @return <code>true</code> if any url matching this rule must be accepted,
* otherwise <code>false</code>.
*/
- protected boolean accept() { return sign; }
-
+ protected boolean accept() {
+ return sign;
+ }
+
/**
* Checks if a url matches this rule.
- * @param url is the url to check.
- * @return <code>true</code> if the specified url matches this rule,
- * otherwise <code>false</code>.
+ *
+ * @param url
+ * is the url to check.
+ * @return <code>true</code> if the specified url matches this rule, otherwise
+ * <code>false</code>.
*/
protected abstract boolean match(String url);
}
-
diff --git a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
index 95c86de3b..a9b5aa430 100644
--- a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
+++ b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
@@ -37,28 +37,32 @@ import org.apache.hadoop.conf.Configuration;
// Nutch imports
import org.apache.nutch.net.*;
-
/**
- * Generic {@link org.apache.nutch.net.URLFilter URL filter} based on
- * regular expressions.
- *
- * <p>The regular expressions rules are expressed in a file. The file of rules
- * is determined for each implementation using the
- * {@link #getRulesReader(Configuration conf)} method.</p>
+ * Generic {@link org.apache.nutch.net.URLFilter URL filter} based on regular
+ * expressions.
*
- * <p>The format of this file is made of many rules (one per line):<br/>
+ * <p>
+ * The regular expressions rules are expressed in a file. The file of rules is
+ * determined for each implementation using the
+ * {@link #getRulesReader(Configuration conf)} method.
+ * </p>
+ *
+ * <p>
+ * The format of this file is made of many rules (one per line):<br/>
* <code>
* [+-]&lt;regex&gt;
* </code><br/>
- * where plus (<code>+</code>)means go ahead and index it and minus
- * (<code>-</code>)means no.</p>
- *
+ * where plus (<code>+</code>)means go ahead and index it and minus (
+ * <code>-</code>)means no.
+ * </p>
+ *
* @author J&eacute;r&ocirc;me Charron
*/
public abstract class RegexURLFilterBase implements URLFilter {
/** My logger */
- private final static Logger LOG = LoggerFactory.getLogger(RegexURLFilterBase.class);
+ private final static Logger LOG = LoggerFactory
+ .getLogger(RegexURLFilterBase.class);
/** An array of applicable rules */
private List<RegexRule> rules;
@@ -66,24 +70,28 @@ public abstract class RegexURLFilterBase implements URLFilter {
/** The current configuration */
private Configuration conf;
-
/**
* Constructs a new empty RegexURLFilterBase
*/
- public RegexURLFilterBase() { }
+ public RegexURLFilterBase() {
+ }
/**
* Constructs a new RegexURLFilter and init it with a file of rules.
- * @param filename is the name of rules file.
+ *
+ * @param filename
+ * is the name of rules file.
*/
- public RegexURLFilterBase(File filename)
- throws IOException, IllegalArgumentException {
+ public RegexURLFilterBase(File filename) throws IOException,
+ IllegalArgumentException {
this(new FileReader(filename));
}
-
+
/**
* Constructs a new RegexURLFilter and inits it with a list of rules.
- * @param rules string with a list of rules, one rule per line
+ *
+ * @param rules
+ * string with a list of rules, one rule per line
* @throws IOException
* @throws IllegalArgumentException
*/
@@ -94,68 +102,82 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Constructs a new RegexURLFilter and init it with a Reader of rules.
- * @param reader is a reader of rules.
+ *
+ * @param reader
+ * is a reader of rules.
*/
- protected RegexURLFilterBase(Reader reader)
- throws IOException, IllegalArgumentException {
+ protected RegexURLFilterBase(Reader reader) throws IOException,
+ IllegalArgumentException {
rules = readRules(reader);
}
-
+
/**
* Creates a new {@link RegexRule}.
- * @param sign of the regular expression.
- * A <code>true</code> value means that any URL matching this rule
- * must be included, whereas a <code>false</code>
- * value means that any URL matching this rule must be excluded.
- * @param regex is the regular expression associated to this rule.
+ *
+ * @param sign
+ * of the regular expression. A <code>true</code> value means that
+ * any URL matching this rule must be included, whereas a
+ * <code>false</code> value means that any URL matching this rule
+ * must be excluded.
+ * @param regex
+ * is the regular expression associated to this rule.
*/
protected abstract RegexRule createRule(boolean sign, String regex);
-
+
/**
- * Returns the name of the file of rules to use for
- * a particular implementation.
- * @param conf is the current configuration.
+ * Returns the name of the file of rules to use for a particular
+ * implementation.
+ *
+ * @param conf
+ * is the current configuration.
* @return the name of the resource containing the rules to use.
*/
- protected abstract Reader getRulesReader(Configuration conf) throws IOException;
-
-
- /* -------------------------- *
- * <implementation:URLFilter> *
- * -------------------------- */
-
+ protected abstract Reader getRulesReader(Configuration conf)
+ throws IOException;
+
+ /*
+ * -------------------------- * <implementation:URLFilter> *
+ * --------------------------
+ */
+
// Inherited Javadoc
public String filter(String url) {
for (RegexRule rule : rules) {
if (rule.match(url)) {
return rule.accept() ? url : null;
}
- };
+ }
+ ;
return null;
}
- /* --------------------------- *
- * </implementation:URLFilter> *
- * --------------------------- */
-
-
- /* ----------------------------- *
- * <implementation:Configurable> *
- * ----------------------------- */
-
+ /*
+ * --------------------------- * </implementation:URLFilter> *
+ * ---------------------------
+ */
+
+ /*
+ * ----------------------------- * <implementation:Configurable> *
+ * -----------------------------
+ */
+
public void setConf(Configuration conf) {
this.conf = conf;
Reader reader = null;
try {
reader = getRulesReader(conf);
} catch (Exception e) {
- if (LOG.isErrorEnabled()) { LOG.error(e.getMessage()); }
- throw new RuntimeException(e.getMessage(), e);
+ if (LOG.isErrorEnabled()) {
+ LOG.error(e.getMessage());
+ }
+ throw new RuntimeException(e.getMessage(), e);
}
try {
rules = readRules(reader);
} catch (IOException e) {
- if (LOG.isErrorEnabled()) { LOG.error(e.getMessage()); }
+ if (LOG.isErrorEnabled()) {
+ LOG.error(e.getMessage());
+ }
throw new RuntimeException(e.getMessage(), e);
}
}
@@ -163,45 +185,51 @@ public abstract class RegexURLFilterBase implements URLFilter {
public Configuration getConf() {
return this.conf;
}
-
- /* ------------------------------ *
- * </implementation:Configurable> *
- * ------------------------------ */
-
+
+ /*
+ * ------------------------------ * </implementation:Configurable> *
+ * ------------------------------
+ */
/**
* Read the specified file of rules.
- * @param reader is a reader of regular expressions rules.
+ *
+ * @param reader
+ * is a reader of regular expressions rules.
* @return the corresponding {@RegexRule rules}.
*/
- private List<RegexRule> readRules(Reader reader)
- throws IOException, IllegalArgumentException {
+ private List<RegexRule> readRules(Reader reader) throws IOException,
+ IllegalArgumentException {
BufferedReader in = new BufferedReader(reader);
List<RegexRule> rules = new ArrayList<RegexRule>();
String line;
-
- while((line=in.readLine())!=null) {
+
+ while ((line = in.readLine()) != null) {
if (line.length() == 0) {
continue;
}
- char first=line.charAt(0);
- boolean sign=false;
+ char first = line.charAt(0);
+ boolean sign = false;
switch (first) {
- case '+' :
- sign=true;
+ case '+':
+ sign = true;
break;
- case '-' :
- sign=false;
+ case '-':
+ sign = false;
break;
- case ' ' : case '\n' : case '#' : // skip blank & comment lines
+ case ' ':
+ case '\n':
+ case '#': // skip blank & comment lines
continue;
- default :
- throw new IOException("Invalid first character: "+line);
+ default:
+ throw new IOException("Invalid first character: " + line);
}
String regex = line.substring(1);
- if (LOG.isTraceEnabled()) { LOG.trace("Adding rule [" + regex + "]"); }
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Adding rule [" + regex + "]");
+ }
RegexRule rule = createRule(sign, regex);
rules.add(rule);
}
@@ -210,18 +238,20 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Filter the standard input using a RegexURLFilterBase.
- * @param filter is the RegexURLFilterBase to use for filtering the
- * standard input.
- * @param args some optional parameters (not used).
+ *
+ * @param filter
+ * is the RegexURLFilterBase to use for filtering the standard input.
+ * @param args
+ * some optional parameters (not used).
*/
public static void main(RegexURLFilterBase filter, String args[])
- throws IOException, IllegalArgumentException {
+ throws IOException, IllegalArgumentException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
- while((line=in.readLine())!=null) {
+ while ((line = in.readLine()) != null) {
String out = filter.filter(line);
- if (out!=null) {
+ if (out != null) {
System.out.print("+");
System.out.println(out);
} else {
diff --git a/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java b/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java
index 356cc6cf6..0b582318e 100644
--- a/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java
+++ b/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java
@@ -31,26 +31,25 @@ import org.slf4j.LoggerFactory;
// Nutch imports
import org.apache.nutch.net.URLFilter;
-
/**
* JUnit based test of class <code>RegexURLFilterBase</code>.
- *
+ *
* @author J&eacute;r&ocirc;me Charron
*/
public abstract class RegexURLFilterBaseTest {
/** My logger */
- protected static final Logger LOG = LoggerFactory.getLogger(RegexURLFilterBaseTest.class);
+ protected static final Logger LOG = LoggerFactory
+ .getLogger(RegexURLFilterBaseTest.class);
- private final static String SEPARATOR = System.getProperty("file.separator");
+ private final static String SEPARATOR = System.getProperty("file.separator");
private final static String SAMPLES = System.getProperty("test.data", ".");
protected abstract URLFilter getURLFilter(Reader rules);
protected void bench(int loops, String file) {
try {
- bench(loops,
- new FileReader(SAMPLES + SEPARATOR + file + ".rules"),
+ bench(loops, new FileReader(SAMPLES + SEPARATOR + file + ".rules"),
new FileReader(SAMPLES + SEPARATOR + file + ".urls"));
} catch (Exception e) {
Assert.fail(e.toString());
@@ -62,14 +61,14 @@ public abstract class RegexURLFilterBaseTest {
try {
URLFilter filter = getURLFilter(rules);
FilteredURL[] expected = readURLFile(urls);
- for (int i=0; i<loops; i++) {
+ for (int i = 0; i < loops; i++) {
test(filter, expected);
}
} catch (Exception e) {
Assert.fail(e.toString());
}
- LOG.info("bench time (" + loops + ") " +
- (System.currentTimeMillis()-start) + "ms");
+ LOG.info("bench time (" + loops + ") "
+ + (System.currentTimeMillis() - start) + "ms");
}
protected void test(String file) {
@@ -90,7 +89,7 @@ public abstract class RegexURLFilterBaseTest {
}
protected void test(URLFilter filter, FilteredURL[] expected) {
- for (int i=0; i<expected.length; i++) {
+ for (int i = 0; i < expected.length; i++) {
String result = filter.filter(expected[i].url);
if (result != null) {
Assert.assertTrue(expected[i].url, expected[i].sign);
@@ -104,7 +103,7 @@ public abstract class RegexURLFilterBaseTest {
BufferedReader in = new BufferedReader(reader);
List<FilteredURL> list = new ArrayList<FilteredURL>();
String line;
- while((line=in.readLine()) != null) {
+ while ((line = in.readLine()) != null) {
if (line.length() != 0) {
list.add(new FilteredURL(line));
}
@@ -119,13 +118,13 @@ public abstract class RegexURLFilterBaseTest {
FilteredURL(String line) {
switch (line.charAt(0)) {
- case '+' :
+ case '+':
sign = true;
break;
- case '-' :
+ case '-':
sign = false;
break;
- default :
+ default:
// Simply ignore...
}
url = line.substring(1);
diff --git a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagIndexingFilter.java b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagIndexingFilter.java
index 3279860e8..e50a15046 100644
--- a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagIndexingFilter.java
+++ b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagIndexingFilter.java
@@ -16,7 +16,6 @@
*/
package org.apache.nutch.microformats.reltag;
-
// Nutch imports
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
@@ -29,29 +28,27 @@ import org.apache.nutch.parse.Parse;
// Hadoop imports
import org.apache.hadoop.conf.Configuration;
-
/**
- * An {@link org.apache.nutch.indexer.IndexingFilter} that
- * add <code>tag</code> field(s) to the document.
- *
+ * An {@link org.apache.nutch.indexer.IndexingFilter} that add <code>tag</code>
+ * field(s) to the document.
+ *
* @see <a href="http://www.microformats.org/wiki/rel-tag">
* http://www.microformats.org/wiki/rel-tag</a>
* @author J&eacute;r&ocirc;me Charron
*/
public class RelTagIndexingFilter implements IndexingFilter {
-
private Configuration conf;
-
// Inherited JavaDoc
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks)
- throws IndexingException {
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
// Check if some Rel-Tags found, possibly put there by RelTagParser
- String[] tags = parse.getData().getParseMeta().getValues(RelTagParser.REL_TAG);
+ String[] tags = parse.getData().getParseMeta()
+ .getValues(RelTagParser.REL_TAG);
if (tags != null) {
- for (int i=0; i<tags.length; i++) {
+ for (int i = 0; i < tags.length; i++) {
doc.add("tag", tags[i]);
}
}
@@ -59,10 +56,11 @@ public class RelTagIndexingFilter implements IndexingFilter {
return doc;
}
- /* ----------------------------- *
- * <implementation:Configurable> *
- * ----------------------------- */
-
+ /*
+ * ----------------------------- * <implementation:Configurable> *
+ * -----------------------------
+ */
+
public void setConf(Configuration conf) {
this.conf = conf;
}
@@ -70,9 +68,10 @@ public class RelTagIndexingFilter implements IndexingFilter {
public Configuration getConf() {
return this.conf;
}
-
- /* ------------------------------ *
- * </implementation:Configurable> *
- * ------------------------------ */
-
+
+ /*
+ * ------------------------------ * </implementation:Configurable> *
+ * ------------------------------
+ */
+
}
diff --git a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
index 6cd68efe9..9176a1e74 100644
--- a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
+++ b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
@@ -45,24 +45,24 @@ import org.apache.hadoop.conf.Configuration;
/**
* Adds microformat rel-tags of document if found.
- *
+ *
* @see <a href="http://www.microformats.org/wiki/rel-tag">
* http://www.microformats.org/wiki/rel-tag</a>
*/
public class RelTagParser implements HtmlParseFilter {
-
+
public final static Logger LOG = LoggerFactory.getLogger(RelTagParser.class);
public final static String REL_TAG = "Rel-Tag";
-
+
private Configuration conf = null;
-
+
/**
* Scan the HTML document looking at possible rel-tags
*/
public ParseResult filter(Content content, ParseResult parseResult,
- HTMLMetaTags metaTags, DocumentFragment doc) {
-
+ HTMLMetaTags metaTags, DocumentFragment doc) {
+
// get parse obj
Parse parse = parseResult.get(content.getUrl());
// Trying to find the document's rel-tags
@@ -79,16 +79,16 @@ public class RelTagParser implements HtmlParseFilter {
private static class Parser {
Set<String> tags = null;
-
+
Parser(Node node) {
tags = new TreeSet<String>();
parse(node);
}
-
+
Set<String> getRelTags() {
return tags;
}
-
+
void parse(Node node) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
@@ -105,7 +105,7 @@ public class RelTagParser implements HtmlParseFilter {
if ("tag".equalsIgnoreCase(relNode.getNodeValue())) {
String tag = parseTag(hrefNode.getNodeValue());
if (!StringUtil.isEmpty(tag)) {
- if(!tags.contains(tag)){
+ if (!tags.contains(tag)) {
tags.add(tag);
LOG.debug("Adding tag: " + tag + " to tag set.");
}
@@ -115,26 +115,27 @@ public class RelTagParser implements HtmlParseFilter {
}
}
}
-
+
// Recurse
NodeList children = node.getChildNodes();
- for (int i=0; children != null && i<children.getLength(); i++)
+ for (int i = 0; children != null && i < children.getLength(); i++)
parse(children.item(i));
}
-
+
private final static String parseTag(String url) {
String tag = null;
try {
URL u = new URL(url);
String path = u.getPath();
- tag = URLDecoder.decode(path.substring(path.lastIndexOf('/') + 1), "UTF-8");
+ tag = URLDecoder.decode(path.substring(path.lastIndexOf('/') + 1),
+ "UTF-8");
} catch (Exception e) {
// Malformed tag...
tag = null;
}
return tag;
}
-
+
}
public void setConf(Configuration conf) {
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 deecf1b50..94d9b322a 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
@@ -50,18 +50,21 @@ import java.nio.charset.Charset;
public class ExtParser implements Parser {
- public static final Logger LOG = LoggerFactory.getLogger("org.apache.nutch.parse.ext");
+ public static final Logger LOG = LoggerFactory
+ .getLogger("org.apache.nutch.parse.ext");
static final int BUFFER_SIZE = 4096;
static final int TIMEOUT_DEFAULT = 30; // in seconds
- // handy map from String contentType to String[] {command, timeoutString, encoding}
+ // handy map from String contentType to String[] {command, timeoutString,
+ // encoding}
Hashtable<String, String[]> TYPE_PARAMS_MAP = new Hashtable<String, String[]>();
- private Configuration conf;
+ private Configuration conf;
- public ExtParser () { }
+ public ExtParser() {
+ }
public ParseResult getParse(Content content) {
@@ -70,14 +73,15 @@ 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).getEmptyParseResult(content.getUrl(), getConf());
+ "No external command defined for contentType: " + contentType)
+ .getEmptyParseResult(content.getUrl(), getConf());
String command = params[0];
int timeout = Integer.parseInt(params[1]);
String encoding = params[2];
if (LOG.isTraceEnabled()) {
- LOG.trace("Use "+command+ " with timeout="+timeout+"secs");
+ LOG.trace("Use " + command + " with timeout=" + timeout + "secs");
}
String text = null;
@@ -89,19 +93,19 @@ public class ExtParser implements Parser {
String contentLength = content.getMetadata().get(Response.CONTENT_LENGTH);
if (contentLength != null
- && raw.length != Integer.parseInt(contentLength)) {
- return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
- "Content truncated at " + raw.length
- +" bytes. Parser can't handle incomplete "
- + contentType + " file.").getEmptyParseResult(content.getUrl(), getConf());
+ && raw.length != Integer.parseInt(contentLength)) {
+ return new ParseStatus(ParseStatus.FAILED,
+ ParseStatus.FAILED_TRUNCATED, "Content truncated at " + raw.length
+ + " bytes. Parser can't handle incomplete " + contentType
+ + " file.").getEmptyParseResult(content.getUrl(), getConf());
}
ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE);
- ByteArrayOutputStream es = new ByteArrayOutputStream(BUFFER_SIZE/4);
+ ByteArrayOutputStream es = new ByteArrayOutputStream(BUFFER_SIZE / 4);
CommandRunner cr = new CommandRunner();
- cr.setCommand(command+ " " +contentType);
+ cr.setCommand(command + " " + contentType);
cr.setInputStream(new ByteArrayInputStream(raw));
cr.setStdOutputStream(os);
cr.setStdErrorStream(es);
@@ -111,14 +115,15 @@ public class ExtParser implements Parser {
cr.evaluate();
if (cr.getExitValue() != 0)
- return new ParseStatus(ParseStatus.FAILED,
- "External command " + command
- + " failed with error: " + es.toString()).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(ParseStatus.FAILED, "External command "
+ + command + " failed with error: " + es.toString())
+ .getEmptyParseResult(content.getUrl(), getConf());
text = os.toString(encoding);
} catch (Exception e) { // run time exception
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e)
+ .getEmptyParseResult(content.getUrl(), getConf());
}
if (text == null)
@@ -131,15 +136,15 @@ public class ExtParser implements Parser {
Outlink[] outlinks = OutlinkExtractor.getOutlinks(text, getConf());
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title,
- outlinks, content.getMetadata());
- return ParseResult.createParseResult(content.getUrl(),
- new ParseImpl(text, parseData));
+ outlinks, content.getMetadata());
+ return ParseResult.createParseResult(content.getUrl(), new ParseImpl(text,
+ parseData));
}
-
+
public void setConf(Configuration conf) {
this.conf = conf;
- Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(
- "org.apache.nutch.parse.Parser").getExtensions();
+ Extension[] extensions = PluginRepository.get(conf)
+ .getExtensionPoint("org.apache.nutch.parse.Parser").getExtensions();
String contentType, command, timeoutString, encoding;
@@ -161,13 +166,14 @@ public class ExtParser implements Parser {
// null encoding means default
encoding = extension.getAttribute("encoding");
if (encoding == null)
- encoding = Charset.defaultCharset().name();
+ encoding = Charset.defaultCharset().name();
timeoutString = extension.getAttribute("timeout");
if (timeoutString == null || timeoutString.equals(""))
timeoutString = "" + TIMEOUT_DEFAULT;
- TYPE_PARAMS_MAP.put(contentType, new String[] { command, timeoutString, encoding });
+ TYPE_PARAMS_MAP.put(contentType, new String[] { command, timeoutString,
+ encoding });
}
}
diff --git a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/package-info.java b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/package-info.java
index 04cf2d296..639448979 100644
--- a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/package-info.java
+++ b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/package-info.java
@@ -19,3 +19,4 @@
* Parse wrapper to run external command to do the parsing.
*/
package org.apache.nutch.parse.ext;
+
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 1057a4292..a39927366 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
@@ -37,15 +37,14 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
-/**
- * Unit tests for ExtParser.
- * First creates a temp file with fixed content, then fetch
- * and parse it using external command 'cat' and 'md5sum' alternately
- * for 10 times. Doing so also does a light stress test for class
- * CommandRunner.java (as used in ExtParser.java).
- *
+/**
+ * Unit tests for ExtParser. First creates a temp file with fixed content, then
+ * fetch and parse it using external command 'cat' and 'md5sum' alternately for
+ * 10 times. Doing so also does a light stress test for class CommandRunner.java
+ * (as used in ExtParser.java).
+ *
* Warning: currently only do test on linux platform.
- *
+ *
* @author John Xing
*/
public class TestExtParser {
@@ -67,10 +66,11 @@ public class TestExtParser {
File tempDir = new File(path);
if (!tempDir.exists())
tempDir.mkdir();
- tempFile = File.createTempFile("nutch.test.plugin.ExtParser.",".txt",tempDir);
+ tempFile = File.createTempFile("nutch.test.plugin.ExtParser.", ".txt",
+ tempDir);
} else {
// otherwise in java.io.tmpdir
- tempFile = File.createTempFile("nutch.test.plugin.ExtParser.",".txt");
+ tempFile = File.createTempFile("nutch.test.plugin.ExtParser.", ".txt");
}
urlString = tempFile.toURI().toURL().toString();
@@ -79,8 +79,10 @@ public class TestExtParser {
fos.close();
// get nutch content
- Protocol protocol = new ProtocolFactory(NutchConfiguration.create()).getProtocol(urlString);
- content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
+ Protocol protocol = new ProtocolFactory(NutchConfiguration.create())
+ .getProtocol(urlString);
+ content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum())
+ .getContent();
protocol = null;
}
@@ -90,8 +92,8 @@ public class TestExtParser {
content = null;
// clean temp file
- //if (tempFile != null && tempFile.exists())
- // tempFile.delete();
+ // if (tempFile != null && tempFile.exists())
+ // tempFile.delete();
}
@Test
@@ -100,24 +102,27 @@ public class TestExtParser {
// now test only on linux platform
if (!System.getProperty("os.name").equalsIgnoreCase("linux")) {
- System.err.println("Current OS is "+System.getProperty("os.name")+".");
+ System.err
+ .println("Current OS is " + System.getProperty("os.name") + ".");
System.err.println("No test is run on OS other than linux.");
return;
}
Configuration conf = NutchConfiguration.create();
// loop alternately, total 10*2 times of invoking external command
- for (int i=0; i<10; i++) {
+ for (int i = 0; i < 10; i++) {
// check external parser that does 'cat'
contentType = "application/vnd.nutch.example.cat";
content.setContentType(contentType);
- parse = new ParseUtil(conf).parseByExtensionId("parse-ext", content).get(content.getUrl());
- Assert.assertEquals(expectedText,parse.getText());
+ parse = new ParseUtil(conf).parseByExtensionId("parse-ext", content).get(
+ content.getUrl());
+ Assert.assertEquals(expectedText, parse.getText());
// check external parser that does 'md5sum'
contentType = "application/vnd.nutch.example.md5sum";
content.setContentType(contentType);
- parse = new ParseUtil(conf).parseByExtensionId("parse-ext", content).get(content.getUrl());
+ parse = new ParseUtil(conf).parseByExtensionId("parse-ext", content).get(
+ content.getUrl());
Assert.assertTrue(parse.getText().startsWith(expectedMD5sum));
}
}
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java
index 2c8a56380..6a1038bc6 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java
@@ -39,136 +39,125 @@ import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.ext.LexicalHandler;
+
/**
- * This class takes SAX events (in addition to some extra events
- * that SAX doesn't handle yet) and adds the result to a document
- * or document fragment.
+ * This class takes SAX events (in addition to some extra events that SAX
+ * doesn't handle yet) and adds the result to a document or document fragment.
*/
-public class DOMBuilder
- implements ContentHandler, LexicalHandler
-{
+public class DOMBuilder implements ContentHandler, LexicalHandler {
- /** Root document */
+ /** Root document */
public Document m_doc;
- /** Current node */
+ /** Current node */
protected Node m_currentNode = null;
- /** First node of document fragment or null if not a DocumentFragment */
+ /** First node of document fragment or null if not a DocumentFragment */
public DocumentFragment m_docFrag = null;
- /** Vector of element nodes */
+ /** Vector of element nodes */
protected Stack<Element> m_elemStack = new Stack<Element>();
/**
- * DOMBuilder instance constructor... it will add the DOM nodes
- * to the document fragment.
- *
- * @param doc Root document
- * @param node Current node
+ * DOMBuilder instance constructor... it will add the DOM nodes to the
+ * document fragment.
+ *
+ * @param doc
+ * Root document
+ * @param node
+ * Current node
*/
- public DOMBuilder(Document doc, Node node)
- {
+ public DOMBuilder(Document doc, Node node) {
m_doc = doc;
m_currentNode = node;
}
/**
- * DOMBuilder instance constructor... it will add the DOM nodes
- * to the document fragment.
- *
- * @param doc Root document
- * @param docFrag Document fragment
+ * DOMBuilder instance constructor... it will add the DOM nodes to the
+ * document fragment.
+ *
+ * @param doc
+ * Root document
+ * @param docFrag
+ * Document fragment
*/
- public DOMBuilder(Document doc, DocumentFragment docFrag)
- {
+ public DOMBuilder(Document doc, DocumentFragment docFrag) {
m_doc = doc;
m_docFrag = docFrag;
}
/**
- * DOMBuilder instance constructor... it will add the DOM nodes
- * to the document.
- *
- * @param doc Root document
+ * DOMBuilder instance constructor... it will add the DOM nodes to the
+ * document.
+ *
+ * @param doc
+ * Root document
*/
- public DOMBuilder(Document doc)
- {
+ public DOMBuilder(Document doc) {
m_doc = doc;
}
/**
- * Get the root node of the DOM being created. This
- * is either a Document or a DocumentFragment.
- *
+ * Get the root node of the DOM being created. This is either a Document or a
+ * DocumentFragment.
+ *
* @return The root document or document fragment if not null
*/
- public Node getRootNode()
- {
+ public Node getRootNode() {
return (null != m_docFrag) ? (Node) m_docFrag : (Node) m_doc;
}
/**
* Get the node currently being processed.
- *
+ *
* @return the current node being processed
*/
- public Node getCurrentNode()
- {
+ public Node getCurrentNode() {
return m_currentNode;
}
/**
* Return null since there is no Writer for this class.
- *
+ *
* @return null
*/
- public java.io.Writer getWriter()
- {
+ public java.io.Writer getWriter() {
return null;
}
/**
* Append a node to the current container.
- *
- * @param newNode New node to append
+ *
+ * @param newNode
+ * New node to append
*/
- protected void append(Node newNode) throws org.xml.sax.SAXException
- {
+ protected void append(Node newNode) throws org.xml.sax.SAXException {
Node currentNode = m_currentNode;
- if (null != currentNode)
- {
+ if (null != currentNode) {
currentNode.appendChild(newNode);
// System.out.println(newNode.getNodeName());
- }
- else if (null != m_docFrag)
- {
+ } else if (null != m_docFrag) {
m_docFrag.appendChild(newNode);
- }
- else
- {
+ } else {
boolean ok = true;
short type = newNode.getNodeType();
- if (type == Node.TEXT_NODE)
- {
+ if (type == Node.TEXT_NODE) {
String data = newNode.getNodeValue();
- if ((null != data) && (data.trim().length() > 0))
- {
- throw new org.xml.sax.SAXException("Warning: can't output text before document element! Ignoring...");
+ if ((null != data) && (data.trim().length() > 0)) {
+ throw new org.xml.sax.SAXException(
+ "Warning: can't output text before document element! Ignoring...");
}
ok = false;
- }
- else if (type == Node.ELEMENT_NODE)
- {
- if (m_doc.getDocumentElement() != null)
- {
- throw new org.xml.sax.SAXException("Can't have more than one root on a DOM!");
+ } else if (type == Node.ELEMENT_NODE) {
+ if (m_doc.getDocumentElement() != null) {
+ throw new org.xml.sax.SAXException(
+ "Can't have more than one root on a DOM!");
}
}
@@ -179,132 +168,139 @@ public class DOMBuilder
/**
* Receive an object for locating the origin of SAX document events.
- *
- * <p>SAX parsers are strongly encouraged (though not absolutely
- * required) to supply a locator: if it does so, it must supply
- * the locator to the application by invoking this method before
- * invoking any of the other methods in the ContentHandler
- * interface.</p>
- *
- * <p>The locator allows the application to determine the end
- * position of any document-related event, even if the parser is
- * not reporting an error. Typically, the application will
- * use this information for reporting its own errors (such as
- * character content that does not match an application's
- * business rules). The information returned by the locator
- * is probably not sufficient for use with a search engine.</p>
- *
- * <p>Note that the locator will return correct information only
- * during the invocation of the events in this interface. The
- * application should not attempt to use it at any other time.</p>
- *
- * @param locator An object that can return the location of
- * any SAX document event.
+ *
+ * <p>
+ * SAX parsers are strongly encouraged (though not absolutely required) to
+ * supply a locator: if it does so, it must supply the locator to the
+ * application by invoking this method before invoking any of the other
+ * methods in the ContentHandler interface.
+ * </p>
+ *
+ * <p>
+ * The locator allows the application to determine the end position of any
+ * document-related event, even if the parser is not reporting an error.
+ * Typically, the application will use this information for reporting its own
+ * errors (such as character content that does not match an application's
+ * business rules). The information returned by the locator is probably not
+ * sufficient for use with a search engine.
+ * </p>
+ *
+ * <p>
+ * Note that the locator will return correct information only during the
+ * invocation of the events in this interface. The application should not
+ * attempt to use it at any other time.
+ * </p>
+ *
+ * @param locator
+ * An object that can return the location of any SAX document event.
* @see org.xml.sax.Locator
*/
- public void setDocumentLocator(Locator locator)
- {
+ public void setDocumentLocator(Locator locator) {
// No action for the moment.
}
/**
* Receive notification of the beginning of a document.
- *
- * <p>The SAX parser will invoke this method only once, before any
- * other methods in this interface or in DTDHandler (except for
- * setDocumentLocator).</p>
+ *
+ * <p>
+ * The SAX parser will invoke this method only once, before any other methods
+ * in this interface or in DTDHandler (except for setDocumentLocator).
+ * </p>
*/
- public void startDocument() throws org.xml.sax.SAXException
- {
+ public void startDocument() throws org.xml.sax.SAXException {
// No action for the moment.
}
/**
* Receive notification of the end of a document.
- *
- * <p>The SAX parser will invoke this method only once, and it will
- * be the last method invoked during the parse. The parser shall
- * not invoke this method until it has either abandoned parsing
- * (because of an unrecoverable error) or reached the end of
- * input.</p>
+ *
+ * <p>
+ * The SAX parser will invoke this method only once, and it will be the last
+ * method invoked during the parse. The parser shall not invoke this method
+ * until it has either abandoned parsing (because of an unrecoverable error)
+ * or reached the end of input.
+ * </p>
*/
- public void endDocument() throws org.xml.sax.SAXException
- {
+ public void endDocument() throws org.xml.sax.SAXException {
// No action for the moment.
}
/**
* Receive notification of the beginning of an element.
- *
- * <p>The Parser will invoke this method at the beginning of every
- * element in the XML document; there will be a corresponding
- * endElement() event for every startElement() event (even when the
- * element is empty). All of the element's content will be
- * reported, in order, before the corresponding endElement()
- * event.</p>
- *
- * <p>If the element name has a namespace prefix, the prefix will
- * still be attached. Note that the attribute list provided will
- * contain only attributes with explicit values (specified or
- * defaulted): #IMPLIED attributes will be omitted.</p>
- *
- *
- * @param ns The namespace of the node
- * @param localName The local part of the qualified name
- * @param name The element name.
- * @param atts The attributes attached to the element, if any.
+ *
+ * <p>
+ * The Parser will invoke this method at the beginning of every element in the
+ * XML document; there will be a corresponding endElement() event for every
+ * startElement() event (even when the element is empty). All of the element's
+ * content will be reported, in order, before the corresponding endElement()
+ * event.
+ * </p>
+ *
+ * <p>
+ * If the element name has a namespace prefix, the prefix will still be
+ * attached. Note that the attribute list provided will contain only
+ * attributes with explicit values (specified or defaulted): #IMPLIED
+ * attributes will be omitted.
+ * </p>
+ *
+ *
+ * @param ns
+ * The namespace of the node
+ * @param localName
+ * The local part of the qualified name
+ * @param name
+ * The element name.
+ * @param atts
+ * The attributes attached to the element, if any.
* @see #endElement
* @see org.xml.sax.Attributes
*/
- public void startElement(
- String ns, String localName, String name, Attributes atts)
- throws org.xml.sax.SAXException
- {
+ public void startElement(String ns, String localName, String name,
+ Attributes atts) throws org.xml.sax.SAXException {
Element elem;
- // Note that the namespace-aware call must be used to correctly
- // construct a Level 2 DOM, even for non-namespaced nodes.
+ // Note that the namespace-aware call must be used to correctly
+ // construct a Level 2 DOM, even for non-namespaced nodes.
if ((null == ns) || (ns.length() == 0))
- elem = m_doc.createElementNS(null,name);
+ elem = m_doc.createElementNS(null, name);
else
elem = m_doc.createElementNS(ns, name);
append(elem);
- try
- {
+ try {
int nAtts = atts.getLength();
- if (0 != nAtts)
- {
- for (int i = 0; i < nAtts; i++)
- {
+ if (0 != nAtts) {
+ for (int i = 0; i < nAtts; i++) {
- //System.out.println("type " + atts.getType(i) + " name " + atts.getLocalName(i) );
+ // System.out.println("type " + atts.getType(i) + " name " +
+ // atts.getLocalName(i) );
// First handle a possible ID attribute
if (atts.getType(i).equalsIgnoreCase("ID"))
setIDAttribute(atts.getValue(i), elem);
String attrNS = atts.getURI(i);
- if("".equals(attrNS))
+ if ("".equals(attrNS))
attrNS = null; // DOM represents no-namespace as null
// System.out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i)
- // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i));
+ // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i));
// Crimson won't let us set an xmlns: attribute on the DOM.
String attrQName = atts.getQName(i);
- // In SAX, xmlns: attributes have an empty namespace, while in DOM they should have the xmlns namespace
+ // In SAX, xmlns: attributes have an empty namespace, while in DOM
+ // they should have the xmlns namespace
if (attrQName.startsWith("xmlns:"))
attrNS = "http://www.w3.org/2000/xmlns/";
// ALWAYS use the DOM Level 2 call!
- elem.setAttributeNS(attrNS,attrQName, atts.getValue(i));
+ elem.setAttributeNS(attrNS, attrQName, atts.getValue(i));
}
}
@@ -315,9 +311,7 @@ public class DOMBuilder
m_currentNode = elem;
// append(elem);
- }
- catch(java.lang.Exception de)
- {
+ } catch (java.lang.Exception de) {
// de.printStackTrace();
throw new org.xml.sax.SAXException(de);
}
@@ -325,74 +319,87 @@ public class DOMBuilder
}
/**
-
-
-
+ *
+ *
+ *
* Receive notification of the end of an element.
- *
- * <p>The SAX parser will invoke this method at the end of every
- * element in the XML document; there will be a corresponding
- * startElement() event for every endElement() event (even when the
- * element is empty).</p>
- *
- * <p>If the element name has a namespace prefix, the prefix will
- * still be attached to the name.</p>
- *
- *
- * @param ns the namespace of the element
- * @param localName The local part of the qualified name of the element
- * @param name The element name
+ *
+ * <p>
+ * The SAX parser will invoke this method at the end of every element in the
+ * XML document; there will be a corresponding startElement() event for every
+ * endElement() event (even when the element is empty).
+ * </p>
+ *
+ * <p>
+ * If the element name has a namespace prefix, the prefix will still be
+ * attached to the name.
+ * </p>
+ *
+ *
+ * @param ns
+ * the namespace of the element
+ * @param localName
+ * The local part of the qualified name of the element
+ * @param name
+ * The element name
*/
public void endElement(String ns, String localName, String name)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
m_elemStack.pop();
- m_currentNode = m_elemStack.isEmpty() ? null : (Node)m_elemStack.peek();
+ m_currentNode = m_elemStack.isEmpty() ? null : (Node) m_elemStack.peek();
}
/**
* Set an ID string to node association in the ID table.
- *
- * @param id The ID string.
- * @param elem The associated ID.
+ *
+ * @param id
+ * The ID string.
+ * @param elem
+ * The associated ID.
*/
- public void setIDAttribute(String id, Element elem)
- {
+ public void setIDAttribute(String id, Element elem) {
// Do nothing. This method is meant to be overiden.
}
/**
* Receive notification of character data.
- *
- * <p>The Parser will call this method to report each chunk of
- * character data. SAX parsers may return all contiguous character
- * data in a single chunk, or they may split it into several
- * chunks; however, all of the characters in any single event
- * must come from the same external entity, so that the Locator
- * provides useful information.</p>
- *
- * <p>The application must not attempt to read from the array
- * outside of the specified range.</p>
- *
- * <p>Note that some parsers will report whitespace using the
- * ignorableWhitespace() method rather than this one (validating
- * parsers must do so).</p>
- *
- * @param ch The characters from the XML document.
- * @param start The start position in the array.
- * @param length The number of characters to read from the array.
+ *
+ * <p>
+ * The Parser will call this method to report each chunk of character data.
+ * SAX parsers may return all contiguous character data in a single chunk, or
+ * they may split it into several chunks; however, all of the characters in
+ * any single event must come from the same external entity, so that the
+ * Locator provides useful information.
+ * </p>
+ *
+ * <p>
+ * The application must not attempt to read from the array outside of the
+ * specified range.
+ * </p>
+ *
+ * <p>
+ * Note that some parsers will report whitespace using the
+ * ignorableWhitespace() method rather than this one (validating parsers must
+ * do so).
+ * </p>
+ *
+ * @param ch
+ * The characters from the XML document.
+ * @param start
+ * The start position in the array.
+ * @param length
+ * The number of characters to read from the array.
* @see #ignorableWhitespace
* @see org.xml.sax.Locator
*/
- public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem()
- && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
- return; // avoid DOM006 Hierarchy request error
-
- if (m_inCData)
- {
+ public void characters(char ch[], int start, int length)
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem()
+ && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
+ return; // avoid DOM006 Hierarchy request error
+
+ if (m_inCData) {
cdata(ch, start, length);
return;
@@ -400,57 +407,55 @@ public class DOMBuilder
String s = new String(ch, start, length);
Node childNode;
- childNode = m_currentNode != null ? m_currentNode.getLastChild(): null;
- if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
- ((Text)childNode).appendData(s);
- }
- else{
- Text text = m_doc.createTextNode(s);
- append(text);
+ childNode = m_currentNode != null ? m_currentNode.getLastChild() : null;
+ if (childNode != null && childNode.getNodeType() == Node.TEXT_NODE) {
+ ((Text) childNode).appendData(s);
+ } else {
+ Text text = m_doc.createTextNode(s);
+ append(text);
}
}
/**
- * If available, when the disable-output-escaping attribute is used,
- * output raw text without escaping. A PI will be inserted in front
- * of the node with the name "lotusxsl-next-is-raw" and a value of
- * "formatter-to-dom".
- *
- * @param ch Array containing the characters
- * @param start Index to start of characters in the array
- * @param length Number of characters in the array
+ * If available, when the disable-output-escaping attribute is used, output
+ * raw text without escaping. A PI will be inserted in front of the node with
+ * the name "lotusxsl-next-is-raw" and a value of "formatter-to-dom".
+ *
+ * @param ch
+ * Array containing the characters
+ * @param start
+ * Index to start of characters in the array
+ * @param length
+ * Number of characters in the array
*/
public void charactersRaw(char ch[], int start, int length)
- throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem()
- && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
- return; // avoid DOM006 Hierarchy request error
-
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem()
+ && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
+ return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
append(m_doc.createProcessingInstruction("xslt-next-is-raw",
- "formatter-to-dom"));
+ "formatter-to-dom"));
append(m_doc.createTextNode(s));
}
/**
* Report the beginning of an entity.
- *
- * The start and end of the document entity are not reported.
- * The start and end of the external DTD subset are reported
- * using the pseudo-name "[dtd]". All other events must be
- * properly nested within start/end entity events.
- *
- * @param name The name of the entity. If it is a parameter
- * entity, the name will begin with '%'.
+ *
+ * The start and end of the document entity are not reported. The start and
+ * end of the external DTD subset are reported using the pseudo-name "[dtd]".
+ * All other events must be properly nested within start/end entity events.
+ *
+ * @param name
+ * The name of the entity. If it is a parameter entity, the name will
+ * begin with '%'.
* @see #endEntity
* @see org.xml.sax.ext.DeclHandler#internalEntityDecl
* @see org.xml.sax.ext.DeclHandler#externalEntityDecl
*/
- public void startEntity(String name) throws org.xml.sax.SAXException
- {
+ public void startEntity(String name) throws org.xml.sax.SAXException {
// Almost certainly the wrong behavior...
// entityReference(name);
@@ -458,49 +463,58 @@ public class DOMBuilder
/**
* Report the end of an entity.
- *
- * @param name The name of the entity that is ending.
+ *
+ * @param name
+ * The name of the entity that is ending.
* @see #startEntity
*/
- public void endEntity(String name) throws org.xml.sax.SAXException{}
+ public void endEntity(String name) throws org.xml.sax.SAXException {
+ }
/**
* Receive notivication of a entityReference.
- *
- * @param name name of the entity reference
+ *
+ * @param name
+ * name of the entity reference
*/
- public void entityReference(String name) throws org.xml.sax.SAXException
- {
+ public void entityReference(String name) throws org.xml.sax.SAXException {
append(m_doc.createEntityReference(name));
}
/**
* Receive notification of ignorable whitespace in element content.
- *
- * <p>Validating Parsers must use this method to report each chunk
- * of ignorable whitespace (see the W3C XML 1.0 recommendation,
- * section 2.10): non-validating parsers may also use this method
- * if they are capable of parsing and using content models.</p>
- *
- * <p>SAX parsers may return all contiguous whitespace in a single
- * chunk, or they may split it into several chunks; however, all of
- * the characters in any single event must come from the same
- * external entity, so that the Locator provides useful
- * information.</p>
- *
- * <p>The application must not attempt to read from the array
- * outside of the specified range.</p>
- *
- * @param ch The characters from the XML document.
- * @param start The start position in the array.
- * @param length The number of characters to read from the array.
+ *
+ * <p>
+ * Validating Parsers must use this method to report each chunk of ignorable
+ * whitespace (see the W3C XML 1.0 recommendation, section 2.10):
+ * non-validating parsers may also use this method if they are capable of
+ * parsing and using content models.
+ * </p>
+ *
+ * <p>
+ * SAX parsers may return all contiguous whitespace in a single chunk, or they
+ * may split it into several chunks; however, all of the characters in any
+ * single event must come from the same external entity, so that the Locator
+ * provides useful information.
+ * </p>
+ *
+ * <p>
+ * The application must not attempt to read from the array outside of the
+ * specified range.
+ * </p>
+ *
+ * @param ch
+ * The characters from the XML document.
+ * @param start
+ * The start position in the array.
+ * @param length
+ * The number of characters to read from the array.
* @see #characters
*/
public void ignorableWhitespace(char ch[], int start, int length)
- throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem())
- return; // avoid DOM006 Hierarchy request error
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem())
+ return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
@@ -509,232 +523,244 @@ public class DOMBuilder
/**
* Tell if the current node is outside the document element.
- *
+ *
* @return true if the current node is outside the document element.
*/
- private boolean isOutsideDocElem()
- {
- return (null == m_docFrag) && m_elemStack.size() == 0 && (null == m_currentNode || m_currentNode.getNodeType() == Node.DOCUMENT_NODE);
- }
+ private boolean isOutsideDocElem() {
+ return (null == m_docFrag)
+ && m_elemStack.size() == 0
+ && (null == m_currentNode || m_currentNode.getNodeType() == Node.DOCUMENT_NODE);
+ }
/**
* Receive notification of a processing instruction.
- *
- * <p>The Parser will invoke this method once for each processing
- * instruction found: note that processing instructions may occur
- * before or after the main document element.</p>
- *
- * <p>A SAX parser should never report an XML declaration (XML 1.0,
- * section 2.8) or a text declaration (XML 1.0, section 4.3.1)
- * using this method.</p>
- *
- * @param target The processing instruction target.
- * @param data The processing instruction data, or null if
- * none was supplied.
+ *
+ * <p>
+ * The Parser will invoke this method once for each processing instruction
+ * found: note that processing instructions may occur before or after the main
+ * document element.
+ * </p>
+ *
+ * <p>
+ * A SAX parser should never report an XML declaration (XML 1.0, section 2.8)
+ * or a text declaration (XML 1.0, section 4.3.1) using this method.
+ * </p>
+ *
+ * @param target
+ * The processing instruction target.
+ * @param data
+ * The processing instruction data, or null if none was supplied.
*/
public void processingInstruction(String target, String data)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
append(m_doc.createProcessingInstruction(target, data));
}
/**
* Report an XML comment anywhere in the document.
- *
- * This callback will be used for comments inside or outside the
- * document element, including comments in the external DTD
- * subset (if read).
- *
- * @param ch An array holding the characters in the comment.
- * @param start The starting position in the array.
- * @param length The number of characters to use from the array.
+ *
+ * This callback will be used for comments inside or outside the document
+ * element, including comments in the external DTD subset (if read).
+ *
+ * @param ch
+ * An array holding the characters in the comment.
+ * @param start
+ * The starting position in the array.
+ * @param length
+ * The number of characters to use from the array.
*/
- public void comment(char ch[], int start, int length) throws org.xml.sax.SAXException
- {
+ public void comment(char ch[], int start, int length)
+ throws org.xml.sax.SAXException {
// tagsoup sometimes submits invalid values here
- if (ch == null || start < 0 || length >= (ch.length - start) || length < 0) return;
+ if (ch == null || start < 0 || length >= (ch.length - start) || length < 0)
+ return;
append(m_doc.createComment(new String(ch, start, length)));
}
- /** Flag indicating that we are processing a CData section */
+ /** Flag indicating that we are processing a CData section */
protected boolean m_inCData = false;
/**
* Report the start of a CDATA section.
- *
+ *
* @see #endCDATA
*/
- public void startCDATA() throws org.xml.sax.SAXException
- {
+ public void startCDATA() throws org.xml.sax.SAXException {
m_inCData = true;
append(m_doc.createCDATASection(""));
}
/**
* Report the end of a CDATA section.
- *
+ *
* @see #startCDATA
*/
- public void endCDATA() throws org.xml.sax.SAXException
- {
+ public void endCDATA() throws org.xml.sax.SAXException {
m_inCData = false;
}
/**
* Receive notification of cdata.
- *
- * <p>The Parser will call this method to report each chunk of
- * character data. SAX parsers may return all contiguous character
- * data in a single chunk, or they may split it into several
- * chunks; however, all of the characters in any single event
- * must come from the same external entity, so that the Locator
- * provides useful information.</p>
- *
- * <p>The application must not attempt to read from the array
- * outside of the specified range.</p>
- *
- * <p>Note that some parsers will report whitespace using the
- * ignorableWhitespace() method rather than this one (validating
- * parsers must do so).</p>
- *
- * @param ch The characters from the XML document.
- * @param start The start position in the array.
- * @param length The number of characters to read from the array.
+ *
+ * <p>
+ * The Parser will call this method to report each chunk of character data.
+ * SAX parsers may return all contiguous character data in a single chunk, or
+ * they may split it into several chunks; however, all of the characters in
+ * any single event must come from the same external entity, so that the
+ * Locator provides useful information.
+ * </p>
+ *
+ * <p>
+ * The application must not attempt to read from the array outside of the
+ * specified range.
+ * </p>
+ *
+ * <p>
+ * Note that some parsers will report whitespace using the
+ * ignorableWhitespace() method rather than this one (validating parsers must
+ * do so).
+ * </p>
+ *
+ * @param ch
+ * The characters from the XML document.
+ * @param start
+ * The start position in the array.
+ * @param length
+ * The number of characters to read from the array.
* @see #ignorableWhitespace
* @see org.xml.sax.Locator
*/
- public void cdata(char ch[], int start, int length) throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem()
- && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
- return; // avoid DOM006 Hierarchy request error
+ public void cdata(char ch[], int start, int length)
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem()
+ && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
+ return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
- // XXX [email protected]: modified from the original, to accomodate TagSoup.
+ // XXX [email protected]: modified from the original, to accomodate TagSoup.
Node n = m_currentNode.getLastChild();
if (n instanceof CDATASection)
- ((CDATASection)n).appendData(s);
+ ((CDATASection) n).appendData(s);
else if (n instanceof Comment)
- ((Comment)n).appendData(s);
+ ((Comment) n).appendData(s);
}
/**
* Report the start of DTD declarations, if any.
- *
- * Any declarations are assumed to be in the internal subset
- * unless otherwise indicated.
- *
- * @param name The document type name.
- * @param publicId The declared public identifier for the
- * external DTD subset, or null if none was declared.
- * @param systemId The declared system identifier for the
- * external DTD subset, or null if none was declared.
+ *
+ * Any declarations are assumed to be in the internal subset unless otherwise
+ * indicated.
+ *
+ * @param name
+ * The document type name.
+ * @param publicId
+ * The declared public identifier for the external DTD subset, or
+ * null if none was declared.
+ * @param systemId
+ * The declared system identifier for the external DTD subset, or
+ * null if none was declared.
* @see #endDTD
* @see #startEntity
*/
public void startDTD(String name, String publicId, String systemId)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
// Do nothing for now.
}
/**
* Report the end of DTD declarations.
- *
+ *
* @see #startDTD
*/
- public void endDTD() throws org.xml.sax.SAXException
- {
+ public void endDTD() throws org.xml.sax.SAXException {
// Do nothing for now.
}
/**
* Begin the scope of a prefix-URI Namespace mapping.
- *
- * <p>The information from this event is not necessary for
- * normal Namespace processing: the SAX XML reader will
- * automatically replace prefixes for element and attribute
- * names when the http://xml.org/sax/features/namespaces
- * feature is true (the default).</p>
- *
- * <p>There are cases, however, when applications need to
- * use prefixes in character data or in attribute values,
- * where they cannot safely be expanded automatically; the
- * start/endPrefixMapping event supplies the information
- * to the application to expand prefixes in those contexts
- * itself, if necessary.</p>
- *
- * <p>Note that start/endPrefixMapping events are not
- * guaranteed to be properly nested relative to each-other:
- * all startPrefixMapping events will occur before the
- * corresponding startElement event, and all endPrefixMapping
- * events will occur after the corresponding endElement event,
- * but their order is not guaranteed.</p>
- *
- * @param prefix The Namespace prefix being declared.
- * @param uri The Namespace URI the prefix is mapped to.
+ *
+ * <p>
+ * The information from this event is not necessary for normal Namespace
+ * processing: the SAX XML reader will automatically replace prefixes for
+ * element and attribute names when the http://xml.org/sax/features/namespaces
+ * feature is true (the default).
+ * </p>
+ *
+ * <p>
+ * There are cases, however, when applications need to use prefixes in
+ * character data or in attribute values, where they cannot safely be expanded
+ * automatically; the start/endPrefixMapping event supplies the information to
+ * the application to expand prefixes in those contexts itself, if necessary.
+ * </p>
+ *
+ * <p>
+ * Note that start/endPrefixMapping events are not guaranteed to be properly
+ * nested relative to each-other: all startPrefixMapping events will occur
+ * before the corresponding startElement event, and all endPrefixMapping
+ * events will occur after the corresponding endElement event, but their order
+ * is not guaranteed.
+ * </p>
+ *
+ * @param prefix
+ * The Namespace prefix being declared.
+ * @param uri
+ * The Namespace URI the prefix is mapped to.
* @see #endPrefixMapping
* @see #startElement
*/
public void startPrefixMapping(String prefix, String uri)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
/*
- // Not sure if this is needed or wanted
- // Also, it fails in the stree.
- if((null != m_currentNode)
- && (m_currentNode.getNodeType() == Node.ELEMENT_NODE))
- {
- String qname;
- if(((null != prefix) && (prefix.length() == 0))
- || (null == prefix))
- qname = "xmlns";
- else
- qname = "xmlns:"+prefix;
-
- Element elem = (Element)m_currentNode;
- String val = elem.getAttribute(qname); // Obsolete, should be DOM2...?
- if(val == null)
- {
- elem.setAttributeNS("http://www.w3.org/XML/1998/namespace",
- qname, uri);
- }
- }
- */
+ * // Not sure if this is needed or wanted // Also, it fails in the stree.
+ * if((null != m_currentNode) && (m_currentNode.getNodeType() ==
+ * Node.ELEMENT_NODE)) { String qname; if(((null != prefix) &&
+ * (prefix.length() == 0)) || (null == prefix)) qname = "xmlns"; else qname
+ * = "xmlns:"+prefix;
+ *
+ * Element elem = (Element)m_currentNode; String val =
+ * elem.getAttribute(qname); // Obsolete, should be DOM2...? if(val == null)
+ * { elem.setAttributeNS("http://www.w3.org/XML/1998/namespace", qname,
+ * uri); } }
+ */
}
/**
* End the scope of a prefix-URI mapping.
- *
- * <p>See startPrefixMapping for details. This event will
- * always occur after the corresponding endElement event,
- * but the order of endPrefixMapping events is not otherwise
- * guaranteed.</p>
- *
- * @param prefix The prefix that was being mapping.
+ *
+ * <p>
+ * See startPrefixMapping for details. This event will always occur after the
+ * corresponding endElement event, but the order of endPrefixMapping events is
+ * not otherwise guaranteed.
+ * </p>
+ *
+ * @param prefix
+ * The prefix that was being mapping.
* @see #startPrefixMapping
* @see #endElement
*/
- public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException{}
+ public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException {
+ }
/**
* Receive notification of a skipped entity.
- *
- * <p>The Parser will invoke this method once for each entity
- * skipped. Non-validating processors may skip entities if they
- * have not seen the declarations (because, for example, the
- * entity was declared in an external DTD subset). All processors
- * may skip external entities, depending on the values of the
- * http://xml.org/sax/features/external-general-entities and the
- * http://xml.org/sax/features/external-parameter-entities
- * properties.</p>
- *
- * @param name The name of the skipped entity. If it is a
- * parameter entity, the name will begin with '%'.
+ *
+ * <p>
+ * The Parser will invoke this method once for each entity skipped.
+ * Non-validating processors may skip entities if they have not seen the
+ * declarations (because, for example, the entity was declared in an external
+ * DTD subset). All processors may skip external entities, depending on the
+ * values of the http://xml.org/sax/features/external-general-entities and the
+ * http://xml.org/sax/features/external-parameter-entities properties.
+ * </p>
+ *
+ * @param name
+ * The name of the skipped entity. If it is a parameter entity, the
+ * name will begin with '%'.
*/
- public void skippedEntity(String name) throws org.xml.sax.SAXException{}
+ public void skippedEntity(String name) throws org.xml.sax.SAXException {
+ }
}
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 aee8e4b58..3c2aba0fc 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
@@ -34,35 +34,35 @@ import org.w3c.dom.*;
/**
* A collection of methods for extracting content from DOM trees.
*
- * This class holds a few utility methods for pulling content out of
- * DOM nodes, such as getOutlinks, getText, etc.
- *
+ * This class holds a few utility methods for pulling content out of DOM nodes,
+ * such as getOutlinks, getText, etc.
+ *
*/
public class DOMContentUtils {
public static class LinkParams {
public String elName;
public String attrName;
- public int childLen;
-
- public LinkParams(String elName, String attrName, int childLen) {
- this.elName = elName;
- this.attrName = attrName;
- this.childLen = childLen;
- }
-
- public String toString() {
- return "LP[el=" + elName + ",attr=" + attrName + ",len=" + childLen + "]";
- }
+ public int childLen;
+
+ public LinkParams(String elName, String attrName, int childLen) {
+ this.elName = elName;
+ this.attrName = attrName;
+ this.childLen = childLen;
+ }
+
+ public String toString() {
+ return "LP[el=" + elName + ",attr=" + attrName + ",len=" + childLen + "]";
+ }
}
-
- private HashMap<String,LinkParams> linkParams = new HashMap<String,LinkParams>();
+
+ private HashMap<String, LinkParams> linkParams = new HashMap<String, LinkParams>();
private Configuration conf;
-
+
public DOMContentUtils(Configuration conf) {
setConf(conf);
}
-
+
public void setConf(Configuration conf) {
// forceTags is used to override configurable tag ignoring, later on
Collection<String> forceTags = new ArrayList<String>(1);
@@ -84,59 +84,57 @@ public class DOMContentUtils {
// remove unwanted link tags from the linkParams map
String[] ignoreTags = conf.getStrings("parser.html.outlinks.ignore_tags");
- for ( int i = 0 ; ignoreTags != null && i < ignoreTags.length ; i++ ) {
- if ( ! forceTags.contains(ignoreTags[i]) )
+ for (int i = 0; ignoreTags != null && i < ignoreTags.length; i++) {
+ if (!forceTags.contains(ignoreTags[i]))
linkParams.remove(ignoreTags[i]);
}
}
-
+
/**
- * This method takes a {@link StringBuffer} and a DOM {@link Node},
- * and will append all the content text found beneath the DOM node to
- * the <code>StringBuffer</code>.
- *
+ * This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
+ * append all the content text found beneath the DOM node to the
+ * <code>StringBuffer</code>.
+ *
* <p>
- *
- * If <code>abortOnNestedAnchors</code> is true, DOM traversal will
- * be aborted and the <code>StringBuffer</code> will not contain
- * any text encountered after a nested anchor is found.
+ *
+ * If <code>abortOnNestedAnchors</code> is true, DOM traversal will be aborted
+ * and the <code>StringBuffer</code> will not contain any text encountered
+ * after a nested anchor is found.
*
* <p>
- *
+ *
* @return true if nested anchors were found
*/
- public boolean getText(StringBuffer sb, Node node,
- boolean abortOnNestedAnchors) {
+ public boolean getText(StringBuffer sb, Node node,
+ boolean abortOnNestedAnchors) {
if (getTextHelper(sb, node, abortOnNestedAnchors, 0)) {
return true;
- }
+ }
return false;
}
-
/**
- * This is a convinience method, equivalent to {@link
- * #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
+ * This is a convinience method, equivalent to
+ * {@link #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
*
*/
public void getText(StringBuffer sb, Node node) {
getText(sb, node, false);
}
- // returns true if abortOnNestedAnchors is true and we find nested
+ // returns true if abortOnNestedAnchors is true and we find nested
// anchors
- private boolean getTextHelper(StringBuffer sb, Node node,
- boolean abortOnNestedAnchors,
- int anchorDepth) {
+ private boolean getTextHelper(StringBuffer sb, Node node,
+ boolean abortOnNestedAnchors, int anchorDepth) {
boolean abort = false;
NodeWalker walker = new NodeWalker(node);
-
+
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
-
+
if ("script".equalsIgnoreCase(nodeName)) {
walker.skipChildren();
}
@@ -148,7 +146,7 @@ public class DOMContentUtils {
if (anchorDepth > 1) {
abort = true;
break;
- }
+ }
}
if (nodeType == Node.COMMENT_NODE) {
walker.skipChildren();
@@ -159,44 +157,45 @@ public class DOMContentUtils {
text = text.replaceAll("\\s+", " ");
text = text.trim();
if (text.length() > 0) {
- if (sb.length() > 0) sb.append(' ');
- sb.append(text);
+ if (sb.length() > 0)
+ sb.append(' ');
+ sb.append(text);
}
}
}
-
+
return abort;
}
/**
- * This method takes a {@link StringBuffer} and a DOM {@link Node},
- * and will append the content text found beneath the first
- * <code>title</code> node to the <code>StringBuffer</code>.
- *
+ * This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
+ * append the content text found beneath the first <code>title</code> node to
+ * the <code>StringBuffer</code>.
+ *
* @return true if a title node was found, false otherwise
*/
public boolean getTitle(StringBuffer sb, Node node) {
-
+
NodeWalker walker = new NodeWalker(node);
-
+
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
-
+
if ("body".equalsIgnoreCase(nodeName)) { // stop after HEAD
return false;
}
-
+
if (nodeType == Node.ELEMENT_NODE) {
if ("title".equalsIgnoreCase(nodeName)) {
getText(sb, currentNode);
return true;
}
}
- }
-
+ }
+
return false;
}
@@ -204,28 +203,29 @@ public class DOMContentUtils {
public URL getBase(Node node) {
NodeWalker walker = new NodeWalker(node);
-
+
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
-
+
// is this node a BASE tag?
if (nodeType == Node.ELEMENT_NODE) {
-
+
if ("body".equalsIgnoreCase(nodeName)) { // stop after HEAD
return null;
}
-
+
if ("base".equalsIgnoreCase(nodeName)) {
NamedNodeMap attrs = currentNode.getAttributes();
- for (int i= 0; i < attrs.getLength(); i++ ) {
+ for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
if ("href".equalsIgnoreCase(attr.getNodeName())) {
try {
return new URL(attr.getNodeValue());
- } catch (MalformedURLException e) {}
+ } catch (MalformedURLException e) {
+ }
}
}
}
@@ -236,10 +236,9 @@ public class DOMContentUtils {
return null;
}
-
private boolean hasOnlyWhiteSpace(Node node) {
- String val= node.getNodeValue();
- for (int i= 0; i < val.length(); i++) {
+ String val = node.getNodeValue();
+ for (int i = 0; i < val.length(); i++) {
if (!Character.isWhitespace(val.charAt(i)))
return false;
}
@@ -248,50 +247,49 @@ public class DOMContentUtils {
// this only covers a few cases of empty links that are symptomatic
// of nekohtml's DOM-fixup process...
- private boolean shouldThrowAwayLink(Node node, NodeList children,
- int childLen, LinkParams params) {
+ private boolean shouldThrowAwayLink(Node node, NodeList children,
+ int childLen, LinkParams params) {
if (childLen == 0) {
- // this has no inner structure
- if (params.childLen == 0) return false;
- else return true;
- } else if ((childLen == 1)
- && (children.item(0).getNodeType() == Node.ELEMENT_NODE)
- && (params.elName.equalsIgnoreCase(children.item(0).getNodeName()))) {
+ // this has no inner structure
+ if (params.childLen == 0)
+ return false;
+ else
+ return true;
+ } else if ((childLen == 1)
+ && (children.item(0).getNodeType() == Node.ELEMENT_NODE)
+ && (params.elName.equalsIgnoreCase(children.item(0).getNodeName()))) {
// single nested link
return true;
} else if (childLen == 2) {
- Node c0= children.item(0);
- Node c1= children.item(1);
+ Node c0 = children.item(0);
+ Node c1 = children.item(1);
if ((c0.getNodeType() == Node.ELEMENT_NODE)
&& (params.elName.equalsIgnoreCase(c0.getNodeName()))
- && (c1.getNodeType() == Node.TEXT_NODE)
- && hasOnlyWhiteSpace(c1) ) {
+ && (c1.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c1)) {
// single link followed by whitespace node
return true;
}
if ((c1.getNodeType() == Node.ELEMENT_NODE)
&& (params.elName.equalsIgnoreCase(c1.getNodeName()))
- && (c0.getNodeType() == Node.TEXT_NODE)
- && hasOnlyWhiteSpace(c0) ) {
+ && (c0.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c0)) {
// whitespace node followed by single link
return true;
}
} else if (childLen == 3) {
- Node c0= children.item(0);
- Node c1= children.item(1);
- Node c2= children.item(2);
-
+ Node c0 = children.item(0);
+ Node c1 = children.item(1);
+ Node c2 = children.item(2);
+
if ((c1.getNodeType() == Node.ELEMENT_NODE)
&& (params.elName.equalsIgnoreCase(c1.getNodeName()))
- && (c0.getNodeType() == Node.TEXT_NODE)
- && (c2.getNodeType() == Node.TEXT_NODE)
- && hasOnlyWhiteSpace(c0)
- && hasOnlyWhiteSpace(c2) ) {
+ && (c0.getNodeType() == Node.TEXT_NODE)
+ && (c2.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c0)
+ && hasOnlyWhiteSpace(c2)) {
// single link surrounded by whitespace nodes
return true;
}
@@ -299,40 +297,37 @@ public class DOMContentUtils {
return false;
}
-
+
/**
- * This method finds all anchors below the supplied DOM
- * <code>node</code>, and creates appropriate {@link Outlink}
- * records for each (relative to the supplied <code>base</code>
- * URL), and adds them to the <code>outlinks</code> {@link
- * ArrayList}.
- *
+ * This method finds all anchors below the supplied DOM <code>node</code>, and
+ * creates appropriate {@link Outlink} records for each (relative to the
+ * supplied <code>base</code> URL), and adds them to the <code>outlinks</code>
+ * {@link ArrayList}.
+ *
* <p>
- *
- * Links without inner structure (tags, text, etc) are discarded, as
- * are links which contain only single nested links and empty text
- * nodes (this is a common DOM-fixup artifact, at least with
- * nekohtml).
+ *
+ * Links without inner structure (tags, text, etc) are discarded, as are links
+ * which contain only single nested links and empty text nodes (this is a
+ * common DOM-fixup artifact, at least with nekohtml).
*/
- public void getOutlinks(URL base, ArrayList<Outlink> outlinks,
- Node node) {
-
+ public void getOutlinks(URL base, ArrayList<Outlink> outlinks, Node node) {
+
NodeWalker walker = new NodeWalker(node);
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
- short nodeType = currentNode.getNodeType();
+ short nodeType = currentNode.getNodeType();
NodeList children = currentNode.getChildNodes();
- int childLen = (children != null) ? children.getLength() : 0;
-
+ int childLen = (children != null) ? children.getLength() : 0;
+
if (nodeType == Node.ELEMENT_NODE) {
-
+
nodeName = nodeName.toLowerCase();
- LinkParams params = (LinkParams)linkParams.get(nodeName);
+ LinkParams params = (LinkParams) linkParams.get(nodeName);
if (params != null) {
if (!shouldThrowAwayLink(currentNode, children, childLen, params)) {
-
+
StringBuffer linkText = new StringBuffer();
getText(linkText, currentNode, true);
if (linkText.toString().trim().length() == 0) {
@@ -347,57 +342,59 @@ public class DOMContentUtils {
if (alt != null) {
String altTxt = alt.getTextContent();
if (altTxt != null && altTxt.trim().length() > 0) {
- if (linkText.length() > 0) linkText.append(' ');
+ if (linkText.length() > 0)
+ linkText.append(' ');
linkText.append(altTxt);
}
}
} else {
// ignore other types of elements
-
- }
+
+ }
} else if (subNode.getNodeType() == Node.TEXT_NODE) {
String txt = subNode.getTextContent();
if (txt != null && txt.length() > 0) {
- if (linkText.length() > 0) linkText.append(' ');
+ if (linkText.length() > 0)
+ linkText.append(' ');
linkText.append(txt);
- }
+ }
}
}
}
-
+
NamedNodeMap attrs = currentNode.getAttributes();
String target = null;
boolean noFollow = false;
boolean post = false;
- for (int i= 0; i < attrs.getLength(); i++ ) {
+ for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
String attrName = attr.getNodeName();
if (params.attrName.equalsIgnoreCase(attrName)) {
target = attr.getNodeValue();
- } else if ("rel".equalsIgnoreCase(attrName) &&
- "nofollow".equalsIgnoreCase(attr.getNodeValue())) {
+ } else if ("rel".equalsIgnoreCase(attrName)
+ && "nofollow".equalsIgnoreCase(attr.getNodeValue())) {
noFollow = true;
- } else if ("method".equalsIgnoreCase(attrName) &&
- "post".equalsIgnoreCase(attr.getNodeValue())) {
+ } else if ("method".equalsIgnoreCase(attrName)
+ && "post".equalsIgnoreCase(attr.getNodeValue())) {
post = true;
}
}
if (target != null && !noFollow && !post)
try {
-
+
URL url = URLUtil.resolveURL(base, target);
- outlinks.add(new Outlink(url.toString(),
- linkText.toString().trim()));
+ outlinks.add(new Outlink(url.toString(), linkText.toString()
+ .trim()));
} catch (MalformedURLException e) {
// don't care
}
}
// this should not have any children, skip them
- if (params.childLen == 0) continue;
+ if (params.childLen == 0)
+ continue;
}
}
}
}
}
-
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java
index 383506cf4..159aa760a 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java
@@ -23,32 +23,31 @@ import org.apache.nutch.parse.HTMLMetaTags;
import org.w3c.dom.*;
/**
- * Class for parsing META Directives from DOM trees. This class
- * handles specifically Robots META directives (all, none, nofollow,
- * noindex), finding BASE HREF tags, and HTTP-EQUIV no-cache
- * instructions. All meta directives are stored in a HTMLMetaTags instance.
+ * Class for parsing META Directives from DOM trees. This class handles
+ * specifically Robots META directives (all, none, nofollow, noindex), finding
+ * BASE HREF tags, and HTTP-EQUIV no-cache instructions. All meta directives are
+ * stored in a HTMLMetaTags instance.
*/
public class HTMLMetaProcessor {
/**
- * Utility class with indicators for the robots directives "noindex"
- * and "nofollow", and HTTP-EQUIV/no-cache
+ * Utility class with indicators for the robots directives "noindex" and
+ * "nofollow", and HTTP-EQUIV/no-cache
*/
-
+
/**
- * Sets the indicators in <code>robotsMeta</code> to appropriate
- * values, based on any META tags found under the given
- * <code>node</code>.
+ * Sets the indicators in <code>robotsMeta</code> to appropriate values, based
+ * on any META tags found under the given <code>node</code>.
*/
- public static final void getMetaTags (
- HTMLMetaTags metaTags, Node node, URL currURL) {
+ public static final void getMetaTags(HTMLMetaTags metaTags, Node node,
+ URL currURL) {
metaTags.reset();
getMetaTagsHelper(metaTags, node, currURL);
}
- private static final void getMetaTagsHelper(
- HTMLMetaTags metaTags, Node node, URL currURL) {
+ private static final void getMetaTagsHelper(HTMLMetaTags metaTags, Node node,
+ URL currURL) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
@@ -63,7 +62,7 @@ public class HTMLMetaProcessor {
Node equivNode = null;
Node contentNode = null;
// Retrieves name, http-equiv and content attribues
- for (int i=0; i<attrs.getLength(); i++) {
+ for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
String attrName = attr.getNodeName().toLowerCase();
if (attrName.equals("name")) {
@@ -74,44 +73,43 @@ public class HTMLMetaProcessor {
contentNode = attr;
}
}
-
+
if (nameNode != null) {
if (contentNode != null) {
String name = nameNode.getNodeValue().toLowerCase();
metaTags.getGeneralTags().add(name, contentNode.getNodeValue());
if ("robots".equals(name)) {
-
+
if (contentNode != null) {
- String directives =
- contentNode.getNodeValue().toLowerCase();
+ String directives = contentNode.getNodeValue().toLowerCase();
int index = directives.indexOf("none");
-
+
if (index >= 0) {
metaTags.setNoIndex();
metaTags.setNoFollow();
}
-
+
index = directives.indexOf("all");
if (index >= 0) {
// do nothing...
}
-
+
index = directives.indexOf("noindex");
if (index >= 0) {
metaTags.setNoIndex();
}
-
+
index = directives.indexOf("nofollow");
if (index >= 0) {
metaTags.setNoFollow();
}
-
+
index = directives.indexOf("noarchive");
if (index >= 0) {
metaTags.setNoCache();
}
- }
-
+ }
+
} // end if (name == robots)
}
}
@@ -124,14 +122,15 @@ public class HTMLMetaProcessor {
if ("pragma".equals(name)) {
content = content.toLowerCase();
int index = content.indexOf("no-cache");
- if (index >= 0)
+ if (index >= 0)
metaTags.setNoCache();
} else if ("refresh".equals(name)) {
int idx = content.indexOf(';');
String time = null;
if (idx == -1) { // just the refresh time
time = content;
- } else time = content.substring(0, idx);
+ } else
+ time = content.substring(0, idx);
try {
metaTags.setRefreshTime(Integer.parseInt(time));
// skip this if we couldn't parse the time
@@ -142,9 +141,11 @@ public class HTMLMetaProcessor {
URL refreshUrl = null;
if (metaTags.getRefresh() && idx != -1) { // set the URL
idx = content.toLowerCase().indexOf("url=");
- if (idx == -1) { // assume a mis-formatted entry with just the url
+ if (idx == -1) { // assume a mis-formatted entry with just the
+ // url
idx = content.indexOf(';') + 1;
- } else idx += 4;
+ } else
+ idx += 4;
if (idx != -1) {
String url = content.substring(idx);
try {
@@ -187,13 +188,13 @@ public class HTMLMetaProcessor {
try {
if (currURL == null)
url = new URL(urlString);
- else
+ else
url = new URL(currURL, urlString);
} catch (Exception e) {
;
}
- if (url != null)
+ if (url != null)
metaTags.setBaseHref(url);
}
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 9fedd2ead..8b349c21f 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
@@ -42,56 +42,55 @@ import org.apache.nutch.parse.*;
import org.apache.nutch.util.*;
public class HtmlParser implements Parser {
- public static final Logger LOG = LoggerFactory.getLogger("org.apache.nutch.parse.html");
+ public static final Logger LOG = LoggerFactory
+ .getLogger("org.apache.nutch.parse.html");
- // I used 1000 bytes at first, but found that some documents have
- // meta tag well past the first 1000 bytes.
+ // I used 1000 bytes at first, but found that some documents have
+ // meta tag well past the first 1000 bytes.
// (e.g. http://cn.promo.yahoo.com/customcare/music.html)
private static final int CHUNK_SIZE = 2000;
// NUTCH-1006 Meta equiv with single quotes not accepted
- private static Pattern metaPattern =
- Pattern.compile("<meta\\s+([^>]*http-equiv=(\"|')?content-type(\"|')?[^>]*)>",
- Pattern.CASE_INSENSITIVE);
- private static Pattern charsetPattern =
- Pattern.compile("charset=\\s*([a-z][_\\-0-9a-z]*)",
- Pattern.CASE_INSENSITIVE);
- private static Pattern charsetPatternHTML5 =
- Pattern.compile("<meta\\s+charset\\s*=\\s*[\"']?([a-z][_\\-0-9a-z]*)[^>]*>",
- Pattern.CASE_INSENSITIVE);
-
+ private static Pattern metaPattern = Pattern.compile(
+ "<meta\\s+([^>]*http-equiv=(\"|')?content-type(\"|')?[^>]*)>",
+ Pattern.CASE_INSENSITIVE);
+ private static Pattern charsetPattern = Pattern.compile(
+ "charset=\\s*([a-z][_\\-0-9a-z]*)", Pattern.CASE_INSENSITIVE);
+ private static Pattern charsetPatternHTML5 = Pattern.compile(
+ "<meta\\s+charset\\s*=\\s*[\"']?([a-z][_\\-0-9a-z]*)[^>]*>",
+ Pattern.CASE_INSENSITIVE);
+
private String parserImpl;
/**
- * Given a <code>byte[]</code> representing an html file of an
- * <em>unknown</em> encoding, read out 'charset' parameter in the meta tag
- * from the first <code>CHUNK_SIZE</code> bytes.
- * If there's no meta tag for Content-Type or no charset is specified,
- * the content is checked for a Unicode Byte Order Mark (BOM).
- * This will also cover non-byte oriented character encodings (UTF-16 only).
- * If no character set can be determined,
- * <code>null</code> is returned. <br />
- * See also http://www.w3.org/International/questions/qa-html-encoding-declarations,
+ * Given a <code>byte[]</code> representing an html file of an
+ * <em>unknown</em> encoding, read out 'charset' parameter in the meta tag
+ * from the first <code>CHUNK_SIZE</code> bytes. If there's no meta tag for
+ * Content-Type or no charset is specified, the content is checked for a
+ * Unicode Byte Order Mark (BOM). This will also cover non-byte oriented
+ * character encodings (UTF-16 only). If no character set can be determined,
+ * <code>null</code> is returned. <br />
+ * See also
+ * http://www.w3.org/International/questions/qa-html-encoding-declarations,
* http://www.w3.org/TR/2011/WD-html5-diff-20110405/#character-encoding, and
* http://www.w3.org/TR/REC-xml/#sec-guessing
- *
- * @param content <code>byte[]</code> representation of an html file
+ *
+ * @param content
+ * <code>byte[]</code> representation of an html file
*/
private static String sniffCharacterEncoding(byte[] content) {
- int length = content.length < CHUNK_SIZE ?
- content.length : CHUNK_SIZE;
+ int length = content.length < CHUNK_SIZE ? content.length : CHUNK_SIZE;
// We don't care about non-ASCII parts so that it's sufficient
- // to just inflate each byte to a 16-bit value by padding.
- // For instance, the sequence {0x41, 0x82, 0xb7} will be turned into
- // {U+0041, U+0082, U+00B7}.
+ // to just inflate each byte to a 16-bit value by padding.
+ // For instance, the sequence {0x41, 0x82, 0xb7} will be turned into
+ // {U+0041, U+0082, U+00B7}.
String str = "";
try {
- str = new String(content, 0, length,
- Charset.forName("ASCII").toString());
+ str = new String(content, 0, length, Charset.forName("ASCII").toString());
} catch (UnsupportedEncodingException e) {
- // code should never come here, but just in case...
+ // code should never come here, but just in case...
return null;
}
@@ -99,7 +98,7 @@ public class HtmlParser implements Parser {
String encoding = null;
if (metaMatcher.find()) {
Matcher charsetMatcher = charsetPattern.matcher(metaMatcher.group(1));
- if (charsetMatcher.find())
+ if (charsetMatcher.find())
encoding = new String(charsetMatcher.group(1));
}
if (encoding == null) {
@@ -111,17 +110,13 @@ public class HtmlParser implements Parser {
}
if (encoding == null) {
// check for BOM
- if (content.length >= 3
- && content[0] == (byte) 0xEF
- && content[1] == (byte) 0xBB
- && content[2] == (byte) 0xBF) {
+ if (content.length >= 3 && content[0] == (byte) 0xEF
+ && content[1] == (byte) 0xBB && content[2] == (byte) 0xBF) {
encoding = "UTF-8";
} else if (content.length >= 2) {
- if (content[0] == (byte)0xFF
- && content[1] == (byte)0xFE) {
+ if (content[0] == (byte) 0xFF && content[1] == (byte) 0xFE) {
encoding = "UTF-16LE";
- } else if (content[0] == (byte)0xFE
- && content[1] == (byte)0xFF) {
+ } else if (content[0] == (byte) 0xFE && content[1] == (byte) 0xFF) {
encoding = "UTF-16BE";
}
}
@@ -133,13 +128,13 @@ public class HtmlParser implements Parser {
private String defaultCharEncoding;
private Configuration conf;
-
+
private DOMContentUtils utils;
private HtmlParseFilters htmlParseFilters;
-
+
private String cachingPolicy;
-
+
public ParseResult getParse(Content content) {
HTMLMetaTags metaTags = new HTMLMetaTags();
@@ -147,7 +142,8 @@ public class HtmlParser implements Parser {
try {
base = new URL(content.getBaseUrl());
} catch (MalformedURLException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e)
+ .getEmptyParseResult(content.getUrl(), getConf());
}
String text = "";
@@ -159,7 +155,8 @@ public class HtmlParser implements Parser {
DocumentFragment root;
try {
byte[] contentInOctets = content.getContent();
- InputSource input = new InputSource(new ByteArrayInputStream(contentInOctets));
+ InputSource input = new InputSource(new ByteArrayInputStream(
+ contentInOctets));
EncodingDetector detector = new EncodingDetector(conf);
detector.autoDetectClues(content, true);
@@ -170,65 +167,78 @@ public class HtmlParser implements Parser {
metadata.set(Metadata.CHAR_ENCODING_FOR_CONVERSION, encoding);
input.setEncoding(encoding);
- if (LOG.isTraceEnabled()) { LOG.trace("Parsing..."); }
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Parsing...");
+ }
root = parse(input);
} catch (IOException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e)
+ .getEmptyParseResult(content.getUrl(), getConf());
} catch (DOMException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e)
+ .getEmptyParseResult(content.getUrl(), getConf());
} catch (SAXException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e)
+ .getEmptyParseResult(content.getUrl(), getConf());
} catch (Exception e) {
LOG.error("Error: ", e);
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(e)
+ .getEmptyParseResult(content.getUrl(), getConf());
}
-
+
// get meta directives
HTMLMetaProcessor.getMetaTags(metaTags, root, base);
if (LOG.isTraceEnabled()) {
LOG.trace("Meta tags for " + base + ": " + metaTags.toString());
}
// check meta directives
- if (!metaTags.getNoIndex()) { // okay to index
+ if (!metaTags.getNoIndex()) { // okay to index
StringBuffer sb = new StringBuffer();
- if (LOG.isTraceEnabled()) { LOG.trace("Getting text..."); }
- utils.getText(sb, root); // extract text
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Getting text...");
+ }
+ utils.getText(sb, root); // extract text
text = sb.toString();
sb.setLength(0);
- if (LOG.isTraceEnabled()) { LOG.trace("Getting title..."); }
- utils.getTitle(sb, root); // extract title
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Getting title...");
+ }
+ utils.getTitle(sb, root); // extract title
title = sb.toString().trim();
}
-
- if (!metaTags.getNoFollow()) { // okay to follow links
- ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks
+
+ if (!metaTags.getNoFollow()) { // okay to follow links
+ ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks
URL baseTag = utils.getBase(root);
- if (LOG.isTraceEnabled()) { LOG.trace("Getting links..."); }
- utils.getOutlinks(baseTag!=null?baseTag:base, l, root);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Getting links...");
+ }
+ utils.getOutlinks(baseTag != null ? baseTag : base, l, root);
outlinks = l.toArray(new Outlink[l.size()]);
if (LOG.isTraceEnabled()) {
- LOG.trace("found "+outlinks.length+" outlinks in "+content.getUrl());
+ LOG.trace("found " + outlinks.length + " outlinks in "
+ + content.getUrl());
}
}
-
+
ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);
if (metaTags.getRefresh()) {
status.setMinorCode(ParseStatus.SUCCESS_REDIRECT);
- status.setArgs(new String[] {metaTags.getRefreshHref().toString(),
- Integer.toString(metaTags.getRefreshTime())});
+ status.setArgs(new String[] { metaTags.getRefreshHref().toString(),
+ Integer.toString(metaTags.getRefreshTime()) });
}
ParseData parseData = new ParseData(status, title, outlinks,
- content.getMetadata(), metadata);
- ParseResult parseResult = ParseResult.createParseResult(content.getUrl(),
- new ParseImpl(text, parseData));
+ content.getMetadata(), metadata);
+ ParseResult parseResult = ParseResult.createParseResult(content.getUrl(),
+ new ParseImpl(text, parseData));
// run filters on parse
- ParseResult filteredParse = this.htmlParseFilters.filter(content, parseResult,
- metaTags, root);
- if (metaTags.getNoCache()) { // not okay to cache
- for (Map.Entry<org.apache.hadoop.io.Text, Parse> entry : filteredParse)
- entry.getValue().getData().getParseMeta().set(Nutch.CACHING_FORBIDDEN_KEY,
- cachingPolicy);
+ ParseResult filteredParse = this.htmlParseFilters.filter(content,
+ parseResult, metaTags, root);
+ if (metaTags.getNoCache()) { // not okay to cache
+ for (Map.Entry<org.apache.hadoop.io.Text, Parse> entry : filteredParse)
+ entry.getValue().getData().getParseMeta()
+ .set(Nutch.CACHING_FORBIDDEN_KEY, cachingPolicy);
}
return filteredParse;
}
@@ -236,9 +246,10 @@ public class HtmlParser implements Parser {
private DocumentFragment parse(InputSource input) throws Exception {
if (parserImpl.equalsIgnoreCase("tagsoup"))
return parseTagSoup(input);
- else return parseNeko(input);
+ else
+ return parseNeko(input);
}
-
+
private DocumentFragment parseTagSoup(InputSource input) throws Exception {
HTMLDocumentImpl doc = new HTMLDocumentImpl();
DocumentFragment frag = doc.createDocumentFragment();
@@ -247,29 +258,39 @@ public class HtmlParser implements Parser {
reader.setContentHandler(builder);
reader.setFeature(org.ccil.cowan.tagsoup.Parser.ignoreBogonsFeature, true);
reader.setFeature(org.ccil.cowan.tagsoup.Parser.bogonsEmptyFeature, false);
- reader.setProperty("http://xml.org/sax/properties/lexical-handler", builder);
+ reader
+ .setProperty("http://xml.org/sax/properties/lexical-handler", builder);
reader.parse(input);
return frag;
}
-
+
private DocumentFragment parseNeko(InputSource input) throws Exception {
DOMFragmentParser parser = new DOMFragmentParser();
try {
- parser.setFeature("http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe",
+ parser
+ .setFeature(
+ "http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe",
true);
parser.setFeature("http://cyberneko.org/html/features/augmentations",
+ true);
+ parser.setProperty(
+ "http://cyberneko.org/html/properties/default-encoding",
+ defaultCharEncoding);
+ parser
+ .setFeature(
+ "http://cyberneko.org/html/features/scanner/ignore-specified-charset",
true);
- parser.setProperty("http://cyberneko.org/html/properties/default-encoding",
- defaultCharEncoding);
- parser.setFeature("http://cyberneko.org/html/features/scanner/ignore-specified-charset",
- true);
- parser.setFeature("http://cyberneko.org/html/features/balance-tags/ignore-outside-content",
+ parser
+ .setFeature(
+ "http://cyberneko.org/html/features/balance-tags/ignore-outside-content",
false);
- parser.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment",
- true);
+ parser.setFeature(
+ "http://cyberneko.org/html/features/balance-tags/document-fragment",
+ true);
parser.setFeature("http://cyberneko.org/html/features/report-errors",
- LOG.isTraceEnabled());
- } catch (SAXException e) {}
+ LOG.isTraceEnabled());
+ } catch (SAXException e) {
+ }
// convert Document to DocumentFragment
HTMLDocumentImpl doc = new HTMLDocumentImpl();
doc.setErrorChecking(false);
@@ -277,40 +298,44 @@ public class HtmlParser implements Parser {
DocumentFragment frag = doc.createDocumentFragment();
parser.parse(input, frag);
res.appendChild(frag);
-
+
try {
- while(true) {
+ while (true) {
frag = doc.createDocumentFragment();
parser.parse(input, frag);
- if (!frag.hasChildNodes()) break;
+ if (!frag.hasChildNodes())
+ break;
if (LOG.isInfoEnabled()) {
- LOG.info(" - new frag, " + frag.getChildNodes().getLength() + " nodes.");
+ LOG.info(" - new frag, " + frag.getChildNodes().getLength()
+ + " nodes.");
}
res.appendChild(frag);
}
- } catch (Exception e) {
+ } catch (Exception e) {
LOG.error("Error: ", e);
- };
+ }
+ ;
return res;
}
-
+
public static void main(String[] args) throws Exception {
- //LOG.setLevel(Level.FINE);
+ // LOG.setLevel(Level.FINE);
String name = args[0];
- String url = "file:"+name;
+ String url = "file:" + name;
File file = new File(name);
- byte[] bytes = new byte[(int)file.length()];
+ byte[] bytes = new byte[(int) file.length()];
DataInputStream in = new DataInputStream(new FileInputStream(file));
in.readFully(bytes);
Configuration conf = NutchConfiguration.create();
HtmlParser parser = new HtmlParser();
parser.setConf(conf);
Parse parse = parser.getParse(
- new Content(url, url, bytes, "text/html", new Metadata(), conf)).get(url);
- System.out.println("data: "+parse.getData());
+ new Content(url, url, bytes, "text/html", new Metadata(), conf)).get(
+ url);
+ System.out.println("data: " + parse.getData());
+
+ System.out.println("text: " + parse.getText());
- System.out.println("text: "+parse.getText());
-
}
public void setConf(Configuration conf) {
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/XMLCharacterRecognizer.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/XMLCharacterRecognizer.java
index dfc694d94..eb382e836 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/XMLCharacterRecognizer.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/XMLCharacterRecognizer.java
@@ -26,40 +26,42 @@
package org.apache.nutch.parse.html;
/**
- * Class used to verify whether the specified <var>ch</var>
- * conforms to the XML 1.0 definition of whitespace.
+ * Class used to verify whether the specified <var>ch</var> conforms to the XML
+ * 1.0 definition of whitespace.
*/
-public class XMLCharacterRecognizer
-{
+public class XMLCharacterRecognizer {
/**
- * Returns whether the specified <var>ch</var> conforms to the XML 1.0 definition
- * of whitespace. Refer to <A href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S">
- * the definition of <CODE>S</CODE></A> for details.
- * @param ch Character to check as XML whitespace.
+ * Returns whether the specified <var>ch</var> conforms to the XML 1.0
+ * definition of whitespace. Refer to <A
+ * href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S"> the definition of
+ * <CODE>S</CODE></A> for details.
+ *
+ * @param ch
+ * Character to check as XML whitespace.
* @return =true if <var>ch</var> is XML whitespace; otherwise =false.
*/
- public static boolean isWhiteSpace(char ch)
- {
+ public static boolean isWhiteSpace(char ch) {
return (ch == 0x20) || (ch == 0x09) || (ch == 0xD) || (ch == 0xA);
}
/**
* Tell if the string is whitespace.
- *
- * @param ch Character array to check as XML whitespace.
- * @param start Start index of characters in the array
- * @param length Number of characters in the array
- * @return True if the characters in the array are
- * XML whitespace; otherwise, false.
+ *
+ * @param ch
+ * Character array to check as XML whitespace.
+ * @param start
+ * Start index of characters in the array
+ * @param length
+ * Number of characters in the array
+ * @return True if the characters in the array are XML whitespace; otherwise,
+ * false.
*/
- public static boolean isWhiteSpace(char ch[], int start, int length)
- {
+ public static boolean isWhiteSpace(char ch[], int start, int length) {
int end = start + length;
- for (int s = start; s < end; s++)
- {
+ for (int s = start; s < end; s++) {
if (!isWhiteSpace(ch[s]))
return false;
}
@@ -69,39 +71,36 @@ public class XMLCharacterRecognizer
/**
* Tell if the string is whitespace.
- *
- * @param buf StringBuffer to check as XML whitespace.
+ *
+ * @param buf
+ * StringBuffer to check as XML whitespace.
* @return True if characters in buffer are XML whitespace, false otherwise
*/
- public static boolean isWhiteSpace(StringBuffer buf)
- {
+ public static boolean isWhiteSpace(StringBuffer buf) {
int n = buf.length();
- for (int i = 0; i < n; i++)
- {
+ for (int i = 0; i < n; i++) {
if (!isWhiteSpace(buf.charAt(i)))
return false;
}
return true;
}
-
+
/**
* Tell if the string is whitespace.
- *
- * @param s String to check as XML whitespace.
+ *
+ * @param s
+ * String to check as XML whitespace.
* @return True if characters in buffer are XML whitespace, false otherwise
*/
- public static boolean isWhiteSpace(String s)
- {
+ public static boolean isWhiteSpace(String s) {
- if(null != s)
- {
+ if (null != s) {
int n = s.length();
-
- for (int i = 0; i < n; i++)
- {
+
+ for (int i = 0; i < n; i++) {
if (!isWhiteSpace(s.charAt(i)))
return false;
}
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 6bb45420b..15725aee6 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
@@ -35,189 +35,133 @@ import org.xml.sax.*;
import org.w3c.dom.*;
import org.apache.html.dom.*;
-/**
+/**
* Unit tests for DOMContentUtils.
*/
public class TestDOMContentUtils {
- private static final String[] testPages= {
- new String("<html><head><title> title </title><script> script </script>"
- + "</head><body> body <a href=\"http://www.nutch.org\">"
- + " anchor </a><!--comment-->"
- + "</body></html>"),
- new String("<html><head><title> title </title><script> script </script>"
- + "</head><body> body <a href=\"/\">"
- + " home </a><!--comment-->"
- + "<style> style </style>"
- + " <a href=\"bot.html\">"
- + " bots </a>"
- + "</body></html>"),
- new String("<html><head><title> </title>"
- + "</head><body> "
- + "<a href=\"/\"> separate this "
- + "<a href=\"ok\"> from this"
- + "</a></a>"
- + "</body></html>"),
- // this one relies on certain neko fixup behavior, possibly
- // distributing the anchors into the LI's-but not the other
- // anchors (outside of them, instead)! So you get a tree that
- // looks like:
- // ... <li> <a href=/> home </a> </li>
- // <li> <a href=/> <a href="1"> 1 </a> </a> </li>
- // <li> <a href=/> <a href="1"> <a href="2"> 2 </a> </a> </a> </li>
- new String("<html><head><title> my title </title>"
- + "</head><body> body "
- + "<ul>"
- + "<li> <a href=\"/\"> home"
- + "<li> <a href=\"1\"> 1"
- + "<li> <a href=\"2\"> 2"
- + "</ul>"
- + "</body></html>"),
- // test frameset link extraction. The invalid frame in the middle will be
- // fixed to a third standalone frame.
- new String("<html><head><title> my title </title>"
- + "</head><frameset rows=\"20,*\"> "
- + "<frame src=\"top.html\">"
- + "</frame>"
- + "<frameset cols=\"20,*\">"
- + "<frame src=\"left.html\">"
- + "<frame src=\"invalid.html\"/>"
- + "</frame>"
- + "<frame src=\"right.html\">"
- + "</frame>"
- + "</frameset>"
- + "</frameset>"
- + "</body></html>"),
- // test <area> and <iframe> link extraction + url normalization
- new String("<html><head><title> my title </title>"
- + "</head><body>"
- + "<img src=\"logo.gif\" usemap=\"#green\" border=\"0\">"
- + "<map name=\"green\">"
- + "<area shape=\"polygon\" coords=\"19,44,45,11,87\" href=\"../index.html\">"
- + "<area shape=\"rect\" coords=\"128,132,241,179\" href=\"#bottom\">"
- + "<area shape=\"circle\" coords=\"68,211,35\" href=\"../bot.html\">"
- + "</map>"
- + "<a name=\"bottom\"/><h1> the bottom </h1> "
- + "<iframe src=\"../docs/index.html\"/>"
- + "</body></html>"),
- // test whitespace processing for plain text extraction
- new String("<html><head>\n <title> my\t\n title\r\n </title>\n"
- + " </head>\n"
- + " <body>\n"
- + " <h1> Whitespace\ttest </h1> \n"
- + "\t<a href=\"../index.html\">\n \twhitespace test\r\n\t</a> \t\n"
- + " <p> This is<span> a whitespace<span></span> test</span>. Newlines\n"
- + "should appear as space too.</p><p>Tabs\tare spaces too.\n</p>"
- + " This\t<b>is a</b> break -&gt;<br>and the line after<i> break</i>.<br>\n"
- + "<table>"
- + " <tr><td>one</td><td>two</td><td>three</td></tr>\n"
- + " <tr><td>space here </td><td> space there</td><td>no space</td></tr>"
- + "\t<tr><td>one\r\ntwo</td><td>two\tthree</td><td>three\r\tfour</td></tr>\n"
- + "</table>put some text here<Br>and there."
- + "<h2>End\tthis\rmadness\n!</h2>\r\n"
- + " . . . ."
- + "</body> </html>"),
+ private static final String[] testPages = {
+ new String("<html><head><title> title </title><script> script </script>"
+ + "</head><body> body <a href=\"http://www.nutch.org\">"
+ + " anchor </a><!--comment-->" + "</body></html>"),
+ new String("<html><head><title> title </title><script> script </script>"
+ + "</head><body> body <a href=\"/\">" + " home </a><!--comment-->"
+ + "<style> style </style>" + " <a href=\"bot.html\">" + " bots </a>"
+ + "</body></html>"),
+ new String("<html><head><title> </title>" + "</head><body> "
+ + "<a href=\"/\"> separate this " + "<a href=\"ok\"> from this"
+ + "</a></a>" + "</body></html>"),
+ // this one relies on certain neko fixup behavior, possibly
+ // distributing the anchors into the LI's-but not the other
+ // anchors (outside of them, instead)! So you get a tree that
+ // looks like:
+ // ... <li> <a href=/> home </a> </li>
+ // <li> <a href=/> <a href="1"> 1 </a> </a> </li>
+ // <li> <a href=/> <a href="1"> <a href="2"> 2 </a> </a> </a> </li>
+ new String("<html><head><title> my title </title>"
+ + "</head><body> body " + "<ul>" + "<li> <a href=\"/\"> home"
+ + "<li> <a href=\"1\"> 1" + "<li> <a href=\"2\"> 2" + "</ul>"
+ + "</body></html>"),
+ // test frameset link extraction. The invalid frame in the middle will be
+ // fixed to a third standalone frame.
+ new String("<html><head><title> my title </title>"
+ + "</head><frameset rows=\"20,*\"> " + "<frame src=\"top.html\">"
+ + "</frame>" + "<frameset cols=\"20,*\">"
+ + "<frame src=\"left.html\">" + "<frame src=\"invalid.html\"/>"
+ + "</frame>" + "<frame src=\"right.html\">" + "</frame>"
+ + "</frameset>" + "</frameset>" + "</body></html>"),
+ // test <area> and <iframe> link extraction + url normalization
+ new String(
+ "<html><head><title> my title </title>"
+ + "</head><body>"
+ + "<img src=\"logo.gif\" usemap=\"#green\" border=\"0\">"
+ + "<map name=\"green\">"
+ + "<area shape=\"polygon\" coords=\"19,44,45,11,87\" href=\"../index.html\">"
+ + "<area shape=\"rect\" coords=\"128,132,241,179\" href=\"#bottom\">"
+ + "<area shape=\"circle\" coords=\"68,211,35\" href=\"../bot.html\">"
+ + "</map>" + "<a name=\"bottom\"/><h1> the bottom </h1> "
+ + "<iframe src=\"../docs/index.html\"/>" + "</body></html>"),
+ // test whitespace processing for plain text extraction
+ new String(
+ "<html><head>\n <title> my\t\n title\r\n </title>\n"
+ + " </head>\n"
+ + " <body>\n"
+ + " <h1> Whitespace\ttest </h1> \n"
+ + "\t<a href=\"../index.html\">\n \twhitespace test\r\n\t</a> \t\n"
+ + " <p> This is<span> a whitespace<span></span> test</span>. Newlines\n"
+ + "should appear as space too.</p><p>Tabs\tare spaces too.\n</p>"
+ + " This\t<b>is a</b> break -&gt;<br>and the line after<i> break</i>.<br>\n"
+ + "<table>"
+ + " <tr><td>one</td><td>two</td><td>three</td></tr>\n"
+ + " <tr><td>space here </td><td> space there</td><td>no space</td></tr>"
+ + "\t<tr><td>one\r\ntwo</td><td>two\tthree</td><td>three\r\tfour</td></tr>\n"
+ + "</table>put some text here<Br>and there."
+ + "<h2>End\tthis\rmadness\n!</h2>\r\n"
+ + " . . . ." + "</body> </html>"),
- // test that <a rel=nofollow> links are not returned
- new String("<html><head></head><body>"
- + "<a href=\"http://www.nutch.org\" rel=\"nofollow\"> ignore </a>"
- + "<a rel=\"nofollow\" href=\"http://www.nutch.org\"> ignore </a>"
- + "</body></html>"),
- // test that POST form actions are skipped
- new String("<html><head></head><body>"
- + "<form method='POST' action='/search.jsp'><input type=text>"
- + "<input type=submit><p>test1</p></form>"
- + "<form method='GET' action='/dummy.jsp'><input type=text>"
- + "<input type=submit><p>test2</p></form></body></html>"),
- // test that all form actions are skipped
- new String("<html><head></head><body>"
- + "<form method='POST' action='/search.jsp'><input type=text>"
- + "<input type=submit><p>test1</p></form>"
- + "<form method='GET' action='/dummy.jsp'><input type=text>"
- + "<input type=submit><p>test2</p></form></body></html>"),
- new String("<html><head><title> title </title>"
- + "</head><body>"
- + "<a href=\";x\">anchor1</a>"
- + "<a href=\"g;x\">anchor2</a>"
- + "<a href=\"g;x?y#s\">anchor3</a>"
- + "</body></html>"),
- new String("<html><head><title> title </title>"
- + "</head><body>"
- + "<a href=\"g\">anchor1</a>"
- + "<a href=\"g?y#s\">anchor2</a>"
- + "<a href=\"?y=1\">anchor3</a>"
- + "<a href=\"?y=1#s\">anchor4</a>"
- + "<a href=\"?y=1;somethingelse\">anchor5</a>"
- + "</body></html>"),
- new String("<html><head><title> title </title>"
- + "</head><body>"
- + "<a href=\"g\"><!--no anchor--></a>"
- + "<a href=\"g1\"> <!--whitespace--> </a>"
- + "<a href=\"g2\"> <img src=test.gif alt='bla bla'> </a>"
- + "</body></html>"),
- };
+ // test that <a rel=nofollow> links are not returned
+ new String("<html><head></head><body>"
+ + "<a href=\"http://www.nutch.org\" rel=\"nofollow\"> ignore </a>"
+ + "<a rel=\"nofollow\" href=\"http://www.nutch.org\"> ignore </a>"
+ + "</body></html>"),
+ // test that POST form actions are skipped
+ new String("<html><head></head><body>"
+ + "<form method='POST' action='/search.jsp'><input type=text>"
+ + "<input type=submit><p>test1</p></form>"
+ + "<form method='GET' action='/dummy.jsp'><input type=text>"
+ + "<input type=submit><p>test2</p></form></body></html>"),
+ // test that all form actions are skipped
+ new String("<html><head></head><body>"
+ + "<form method='POST' action='/search.jsp'><input type=text>"
+ + "<input type=submit><p>test1</p></form>"
+ + "<form method='GET' action='/dummy.jsp'><input type=text>"
+ + "<input type=submit><p>test2</p></form></body></html>"),
+ new String("<html><head><title> title </title>" + "</head><body>"
+ + "<a href=\";x\">anchor1</a>" + "<a href=\"g;x\">anchor2</a>"
+ + "<a href=\"g;x?y#s\">anchor3</a>" + "</body></html>"),
+ new String("<html><head><title> title </title>" + "</head><body>"
+ + "<a href=\"g\">anchor1</a>" + "<a href=\"g?y#s\">anchor2</a>"
+ + "<a href=\"?y=1\">anchor3</a>" + "<a href=\"?y=1#s\">anchor4</a>"
+ + "<a href=\"?y=1;somethingelse\">anchor5</a>" + "</body></html>"),
+ new String("<html><head><title> title </title>" + "</head><body>"
+ + "<a href=\"g\"><!--no anchor--></a>"
+ + "<a href=\"g1\"> <!--whitespace--> </a>"
+ + "<a href=\"g2\"> <img src=test.gif alt='bla bla'> </a>"
+ + "</body></html>"), };
private static int SKIP = 9;
- private static String[] testBaseHrefs= {
- "http://www.nutch.org",
- "http://www.nutch.org/docs/foo.html",
- "http://www.nutch.org/docs/",
- "http://www.nutch.org/docs/",
- "http://www.nutch.org/frames/",
- "http://www.nutch.org/maps/",
- "http://www.nutch.org/whitespace/",
- "http://www.nutch.org//",
- "http://www.nutch.org/",
- "http://www.nutch.org/",
- "http://www.nutch.org/",
- "http://www.nutch.org/;something",
- "http://www.nutch.org/"
- };
-
- private static final DocumentFragment testDOMs[]=
- new DocumentFragment[testPages.length];
+ private static String[] testBaseHrefs = { "http://www.nutch.org",
+ "http://www.nutch.org/docs/foo.html", "http://www.nutch.org/docs/",
+ "http://www.nutch.org/docs/", "http://www.nutch.org/frames/",
+ "http://www.nutch.org/maps/", "http://www.nutch.org/whitespace/",
+ "http://www.nutch.org//", "http://www.nutch.org/",
+ "http://www.nutch.org/", "http://www.nutch.org/",
+ "http://www.nutch.org/;something", "http://www.nutch.org/" };
- private static URL[] testBaseHrefURLs=
- new URL[testPages.length];
+ private static final DocumentFragment testDOMs[] = new DocumentFragment[testPages.length];
+ private static URL[] testBaseHrefURLs = new URL[testPages.length];
- private static final String[] answerText= {
- "title body anchor",
- "title body home bots",
- "separate this from this",
- "my title body home 1 2",
- "my title",
- "my title the bottom",
- "my title Whitespace test whitespace test "
- + "This is a whitespace test . Newlines should appear as space too. "
- + "Tabs are spaces too. This is a break -> and the line after break . "
- + "one two three space here space there no space "
- + "one two two three three four put some text here and there. "
- + "End this madness ! . . . .",
- "ignore ignore",
- "test1 test2",
- "test1 test2",
- "title anchor1 anchor2 anchor3",
- "title anchor1 anchor2 anchor3 anchor4 anchor5",
- "title"
- };
+ private static final String[] answerText = {
+ "title body anchor",
+ "title body home bots",
+ "separate this from this",
+ "my title body home 1 2",
+ "my title",
+ "my title the bottom",
+ "my title Whitespace test whitespace test "
+ + "This is a whitespace test . Newlines should appear as space too. "
+ + "Tabs are spaces too. This is a break -> and the line after break . "
+ + "one two three space here space there no space "
+ + "one two two three three four put some text here and there. "
+ + "End this madness ! . . . .", "ignore ignore", "test1 test2",
+ "test1 test2", "title anchor1 anchor2 anchor3",
+ "title anchor1 anchor2 anchor3 anchor4 anchor5", "title" };
- private static final String[] answerTitle= {
- "title",
- "title",
- "",
- "my title",
- "my title",
- "my title",
- "my title",
- "",
- "",
- "",
- "title",
- "title",
- "title"
- };
+ private static final String[] answerTitle = { "title", "title", "",
+ "my title", "my title", "my title", "my title", "", "", "", "title",
+ "title", "title" };
// note: should be in page-order
private static Outlink[][] answerOutlinks;
@@ -230,87 +174,64 @@ public class TestDOMContentUtils {
conf = NutchConfiguration.create();
conf.setBoolean("parser.html.form.use_action", true);
utils = new DOMContentUtils(conf);
- DOMFragmentParser parser= new DOMFragmentParser();
+ DOMFragmentParser parser = new DOMFragmentParser();
try {
- parser.setFeature(
- "http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe",
- true);
- } catch (SAXException e) {}
- for (int i= 0; i < testPages.length; i++) {
- DocumentFragment node=
- new HTMLDocumentImpl().createDocumentFragment();
+ parser
+ .setFeature(
+ "http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe",
+ true);
+ } catch (SAXException e) {
+ }
+ for (int i = 0; i < testPages.length; i++) {
+ DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
try {
parser.parse(
- new InputSource(
- new ByteArrayInputStream(testPages[i].getBytes()) ),
- node);
- testBaseHrefURLs[i]= new URL(testBaseHrefs[i]);
+ new InputSource(new ByteArrayInputStream(testPages[i].getBytes())),
+ node);
+ testBaseHrefURLs[i] = new URL(testBaseHrefs[i]);
} catch (Exception e) {
Assert.assertTrue("caught exception: " + e, false);
- }
- testDOMs[i]= node;
+ }
+ testDOMs[i] = node;
}
try {
- answerOutlinks = new Outlink[][]{
- {
- new Outlink("http://www.nutch.org", "anchor"),
- },
- {
- new Outlink("http://www.nutch.org/", "home"),
- new Outlink("http://www.nutch.org/docs/bot.html", "bots"),
- },
- {
- new Outlink("http://www.nutch.org/", "separate this"),
- new Outlink("http://www.nutch.org/docs/ok", "from this"),
- },
- {
- 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/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/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/index.html", "whitespace test"),
- },
- {
- },
- {
- new Outlink("http://www.nutch.org/dummy.jsp", "test2"),
- },
- {
- },
- {
- new Outlink("http://www.nutch.org/;x", "anchor1"),
- new Outlink("http://www.nutch.org/g;x", "anchor2"),
- new Outlink("http://www.nutch.org/g;x?y#s", "anchor3")
- },
- {
- // this is tricky - see RFC3986 section 5.4.1 example 7
- new Outlink("http://www.nutch.org/g", "anchor1"),
- new Outlink("http://www.nutch.org/g?y#s", "anchor2"),
- new Outlink("http://www.nutch.org/;something?y=1", "anchor3"),
- new Outlink("http://www.nutch.org/;something?y=1#s", "anchor4"),
- new Outlink("http://www.nutch.org/;something?y=1;somethingelse", "anchor5")
- },
+ answerOutlinks = new Outlink[][] {
+ { new Outlink("http://www.nutch.org", "anchor"), },
+ { new Outlink("http://www.nutch.org/", "home"),
+ new Outlink("http://www.nutch.org/docs/bot.html", "bots"), },
+ { new Outlink("http://www.nutch.org/", "separate this"),
+ new Outlink("http://www.nutch.org/docs/ok", "from this"), },
+ { 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/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/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/index.html", "whitespace test"), },
+ {},
+ { new Outlink("http://www.nutch.org/dummy.jsp", "test2"), },
+ {},
+ { new Outlink("http://www.nutch.org/;x", "anchor1"),
+ new Outlink("http://www.nutch.org/g;x", "anchor2"),
+ new Outlink("http://www.nutch.org/g;x?y#s", "anchor3") },
{
- new Outlink("http://www.nutch.org/g", ""),
- new Outlink("http://www.nutch.org/g1", ""),
- new Outlink("http://www.nutch.org/g2", "bla bla"),
- new Outlink("http://www.nutch.org/test.gif", "bla bla"),
- }
- };
+ // this is tricky - see RFC3986 section 5.4.1 example 7
+ new Outlink("http://www.nutch.org/g", "anchor1"),
+ new Outlink("http://www.nutch.org/g?y#s", "anchor2"),
+ new Outlink("http://www.nutch.org/;something?y=1", "anchor3"),
+ new Outlink("http://www.nutch.org/;something?y=1#s", "anchor4"),
+ new Outlink("http://www.nutch.org/;something?y=1;somethingelse",
+ "anchor5") },
+ { new Outlink("http://www.nutch.org/g", ""),
+ new Outlink("http://www.nutch.org/g1", ""),
+ new Outlink("http://www.nutch.org/g2", "bla bla"),
+ new Outlink("http://www.nutch.org/test.gif", "bla bla"), } };
} catch (MalformedURLException e) {
@@ -318,58 +239,58 @@ public class TestDOMContentUtils {
}
private static boolean equalsIgnoreWhitespace(String s1, String s2) {
- StringTokenizer st1= new StringTokenizer(s1);
- StringTokenizer st2= new StringTokenizer(s2);
+ StringTokenizer st1 = new StringTokenizer(s1);
+ StringTokenizer st2 = new StringTokenizer(s2);
while (st1.hasMoreTokens()) {
- if (!st2.hasMoreTokens())
+ if (!st2.hasMoreTokens())
return false;
- if ( ! st1.nextToken().equals(st2.nextToken()) )
+ if (!st1.nextToken().equals(st2.nextToken()))
return false;
}
- if (st2.hasMoreTokens())
+ if (st2.hasMoreTokens())
return false;
return true;
}
@Test
public void testGetText() {
- if (testDOMs[0] == null)
+ if (testDOMs[0] == null)
setup();
- for (int i= 0; i < testPages.length; i++) {
- StringBuffer sb= new StringBuffer();
+ for (int i = 0; i < testPages.length; i++) {
+ StringBuffer sb = new StringBuffer();
utils.getText(sb, testDOMs[i]);
- String text= sb.toString();
- Assert.assertTrue("expecting text: " + answerText[i]
- + System.getProperty("line.separator")
- + System.getProperty("line.separator")
- + "got text: "+ text,
+ String text = sb.toString();
+ Assert.assertTrue(
+ "expecting text: " + answerText[i]
+ + System.getProperty("line.separator")
+ + System.getProperty("line.separator") + "got text: " + text,
equalsIgnoreWhitespace(answerText[i], text));
}
}
@Test
public void testGetTitle() {
- if (testDOMs[0] == null)
+ if (testDOMs[0] == null)
setup();
- for (int i= 0; i < testPages.length; i++) {
- StringBuffer sb= new StringBuffer();
+ for (int i = 0; i < testPages.length; i++) {
+ StringBuffer sb = new StringBuffer();
utils.getTitle(sb, testDOMs[i]);
- String text= sb.toString();
- Assert.assertTrue("expecting text: " + answerText[i]
- + System.getProperty("line.separator")
- + System.getProperty("line.separator")
- + "got text: "+ text,
+ String text = sb.toString();
+ Assert.assertTrue(
+ "expecting text: " + answerText[i]
+ + System.getProperty("line.separator")
+ + System.getProperty("line.separator") + "got text: " + text,
equalsIgnoreWhitespace(answerTitle[i], text));
}
}
@Test
public void testGetOutlinks() {
- if (testDOMs[0] == null)
+ if (testDOMs[0] == null)
setup();
- for (int i= 0; i < testPages.length; i++) {
- ArrayList<Outlink> outlinks= new ArrayList<Outlink>();
+ for (int i = 0; i < testPages.length; i++) {
+ ArrayList<Outlink> outlinks = new ArrayList<Outlink>();
if (i == SKIP) {
conf.setBoolean("parser.html.form.use_action", false);
utils.setConf(conf);
@@ -378,51 +299,47 @@ public class TestDOMContentUtils {
utils.setConf(conf);
}
utils.getOutlinks(testBaseHrefURLs[i], outlinks, testDOMs[i]);
- Outlink[] outlinkArr= new Outlink[outlinks.size()];
- outlinkArr= (Outlink[]) outlinks.toArray(outlinkArr);
+ Outlink[] outlinkArr = new Outlink[outlinks.size()];
+ outlinkArr = (Outlink[]) outlinks.toArray(outlinkArr);
compareOutlinks(answerOutlinks[i], outlinkArr);
}
}
private static final void appendOutlinks(StringBuffer sb, Outlink[] o) {
- for (int i= 0; i < o.length; i++) {
+ for (int i = 0; i < o.length; i++) {
sb.append(o[i].toString());
sb.append(System.getProperty("line.separator"));
}
}
private static final String outlinksString(Outlink[] o) {
- StringBuffer sb= new StringBuffer();
+ StringBuffer sb = new StringBuffer();
appendOutlinks(sb, o);
return sb.toString();
}
private static final void compareOutlinks(Outlink[] o1, Outlink[] o2) {
if (o1.length != o2.length) {
- Assert.assertTrue("got wrong number of outlinks (expecting " + o1.length
- + ", got " + o2.length + ")"
- + System.getProperty("line.separator")
- + "answer: " + System.getProperty("line.separator")
- + outlinksString(o1)
- + System.getProperty("line.separator")
- + "got: " + System.getProperty("line.separator")
- + outlinksString(o2)
- + System.getProperty("line.separator"),
- false
- );
+ Assert.assertTrue(
+ "got wrong number of outlinks (expecting " + o1.length + ", got "
+ + o2.length + ")" + System.getProperty("line.separator")
+ + "answer: " + System.getProperty("line.separator")
+ + outlinksString(o1) + System.getProperty("line.separator")
+ + "got: " + System.getProperty("line.separator")
+ + outlinksString(o2) + System.getProperty("line.separator"),
+ false);
}
- for (int i= 0; i < o1.length; i++) {
+ for (int i = 0; i < o1.length; i++) {
if (!o1[i].equals(o2[i])) {
- Assert.assertTrue("got wrong outlinks at position " + i
- + System.getProperty("line.separator")
- + "answer: " + System.getProperty("line.separator")
- + "'" + o1[i].getToUrl() + "', anchor: '" + o1[i].getAnchor() + "'"
- + System.getProperty("line.separator")
- + "got: " + System.getProperty("line.separator")
- + "'" + o2[i].getToUrl() + "', anchor: '" + o2[i].getAnchor() + "'",
- false
- );
+ Assert.assertTrue(
+ "got wrong outlinks at position " + i
+ + System.getProperty("line.separator") + "answer: "
+ + System.getProperty("line.separator") + "'" + o1[i].getToUrl()
+ + "', anchor: '" + o1[i].getAnchor() + "'"
+ + System.getProperty("line.separator") + "got: "
+ + System.getProperty("line.separator") + "'" + o2[i].getToUrl()
+ + "', anchor: '" + o2[i].getAnchor() + "'", false);
}
}
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
index 0be1cd8bc..bcfe9e4e1 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
@@ -33,69 +33,54 @@ import org.slf4j.LoggerFactory;
public class TestHtmlParser {
- public static final Logger LOG = LoggerFactory.getLogger(TestHtmlParser.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(TestHtmlParser.class);
- private static final String encodingTestKeywords =
- "français, español, русский язык, čeština, ελληνικά";
- private static final String encodingTestBody =
- "<ul>\n <li>français\n <li>español\n <li>русский язык\n <li>čeština\n <li>ελληνικά\n</ul>";
- private static final String encodingTestContent =
- "<title>" + encodingTestKeywords + "</title>\n"
- + "<meta name=\"keywords\" content=\"" + encodingTestKeywords + "</meta>\n"
- + "</head>\n<body>" + encodingTestBody + "</body>\n</html>";
+ private static final String encodingTestKeywords = "français, español, русский язык, čeština, ελληνικά";
+ private static final String encodingTestBody = "<ul>\n <li>français\n <li>español\n <li>русский язык\n <li>čeština\n <li>ελληνικά\n</ul>";
+ private static final String encodingTestContent = "<title>"
+ + encodingTestKeywords + "</title>\n"
+ + "<meta name=\"keywords\" content=\"" + encodingTestKeywords
+ + "</meta>\n" + "</head>\n<body>" + encodingTestBody + "</body>\n</html>";
- private static String[][] encodingTestPages= {
- {
- "HTML4, utf-8, meta http-equiv, no quotes",
- "utf-8",
- "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
- + "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
- + "<html>\n<head>\n"
- + "<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\" />"
- + encodingTestContent
- },
- {
- "HTML4, utf-8, meta http-equiv, single quotes",
- "utf-8",
- "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
- + "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
- + "<html>\n<head>\n"
- + "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
- + encodingTestContent
- },
- {
- "XHTML, utf-8, meta http-equiv, double quotes",
- "utf-8",
- "<?xml version=\"1.0\"?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">"
- + "<html>\n<head>\n"
- + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
- + encodingTestContent
- },
- {
- "HTML5, utf-8, meta charset",
- "utf-8",
- "<!DOCTYPE html>\n<html>\n<head>\n"
- + "<meta charset=\"utf-8\">"
- + encodingTestContent
- },
- {
- "HTML5, utf-8, BOM",
- "utf-8",
- "\ufeff<!DOCTYPE html>\n<html>\n<head>\n"
- + encodingTestContent
- },
- {
- "HTML5, utf-16, BOM",
- "utf-16",
- "\ufeff<!DOCTYPE html>\n<html>\n<head>\n"
- + encodingTestContent
- }
- };
+ private static String[][] encodingTestPages = {
+ {
+ "HTML4, utf-8, meta http-equiv, no quotes",
+ "utf-8",
+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
+ + "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ + "<html>\n<head>\n"
+ + "<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\" />"
+ + encodingTestContent },
+ {
+ "HTML4, utf-8, meta http-equiv, single quotes",
+ "utf-8",
+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
+ + "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ + "<html>\n<head>\n"
+ + "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
+ + encodingTestContent },
+ {
+ "XHTML, utf-8, meta http-equiv, double quotes",
+ "utf-8",
+ "<?xml version=\"1.0\"?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ + "<html>\n<head>\n"
+ + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
+ + encodingTestContent },
+ {
+ "HTML5, utf-8, meta charset",
+ "utf-8",
+ "<!DOCTYPE html>\n<html>\n<head>\n" + "<meta charset=\"utf-8\">"
+ + encodingTestContent },
+ { "HTML5, utf-8, BOM", "utf-8",
+ "\ufeff<!DOCTYPE html>\n<html>\n<head>\n" + encodingTestContent },
+ { "HTML5, utf-16, BOM", "utf-16",
+ "\ufeff<!DOCTYPE html>\n<html>\n<head>\n" + encodingTestContent } };
private Configuration conf;
private Parser parser;
- public TestHtmlParser() {
+ public TestHtmlParser() {
conf = NutchConfiguration.create();
parser = new HtmlParser();
parser.setConf(conf);
@@ -104,8 +89,8 @@ public class TestHtmlParser {
protected Parse parse(byte[] contentBytes) {
String dummyUrl = "http://dummy.url/";
return parser.getParse(
- new Content(dummyUrl, dummyUrl, contentBytes, "text/html", new Metadata(),
- conf)).get(dummyUrl);
+ new Content(dummyUrl, dummyUrl, contentBytes, "text/html",
+ new Metadata(), conf)).get(dummyUrl);
}
@Test
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java
index f53d389c3..5089a10d5 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java
@@ -33,120 +33,96 @@ import org.apache.html.dom.*;
public class TestRobotsMetaProcessor {
/*
+ *
+ * some sample tags:
+ *
+ * <meta name="robots" content="index,follow"> <meta name="robots"
+ * content="noindex,follow"> <meta name="robots" content="index,nofollow">
+ * <meta name="robots" content="noindex,nofollow">
+ *
+ * <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
+ */
- some sample tags:
+ public static String[] tests = {
+ "<html><head><title>test page</title>"
+ + "<META NAME=\"ROBOTS\" CONTENT=\"NONE\"> "
+ + "<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\"> "
+ + "</head><body>" + " some text" + "</body></html>",
- <meta name="robots" content="index,follow">
- <meta name="robots" content="noindex,follow">
- <meta name="robots" content="index,nofollow">
- <meta name="robots" content="noindex,nofollow">
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"all\"> "
+ + "<meta http-equiv=\"pragma\" content=\"no-cache\"> "
+ + "</head><body>" + " some text" + "</body></html>",
- <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
+ "<html><head><title>test page</title>"
+ + "<MeTa NaMe=\"RoBoTs\" CoNtEnT=\"nOnE\"> "
+ + "<MeTa HtTp-EqUiV=\"pRaGmA\" cOnTeNt=\"No-CaChE\"> "
+ + "</head><body>" + " some text" + "</body></html>",
- */
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"none\"> " + "</head><body>"
+ + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"noindex,nofollow\"> "
+ + "</head><body>" + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"noindex,follow\"> "
+ + "</head><body>" + " some text" + "</body></html>",
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"index,nofollow\"> "
+ + "</head><body>" + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"index,follow\"> "
+ + "<base href=\"http://www.nutch.org/\">" + "</head><body>"
+ + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>" + "<meta name=\"robots\"> "
+ + "<base href=\"http://www.nutch.org/base/\">" + "</head><body>"
+ + " some text" + "</body></html>",
+
+ };
- public static String[] tests=
- {
- "<html><head><title>test page</title>"
- + "<META NAME=\"ROBOTS\" CONTENT=\"NONE\"> "
- + "<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"all\"> "
- + "<meta http-equiv=\"pragma\" content=\"no-cache\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<MeTa NaMe=\"RoBoTs\" CoNtEnT=\"nOnE\"> "
- + "<MeTa HtTp-EqUiV=\"pRaGmA\" cOnTeNt=\"No-CaChE\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"none\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"noindex,nofollow\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"noindex,follow\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"index,nofollow\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"index,follow\"> "
- + "<base href=\"http://www.nutch.org/\">"
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\"> "
- + "<base href=\"http://www.nutch.org/base/\">"
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- };
-
- public static final boolean[][] answers= {
- {true, true, true}, // NONE
- {false, false, true}, // all
- {true, true, true}, // nOnE
- {true, true, false}, // none
- {true, true, false}, // noindex,nofollow
- {true, false, false}, // noindex,follow
- {false, true, false}, // index,nofollow
- {false, false, false}, // index,follow
- {false, false, false}, // missing!
+ public static final boolean[][] answers = { { true, true, true }, // NONE
+ { false, false, true }, // all
+ { true, true, true }, // nOnE
+ { true, true, false }, // none
+ { true, true, false }, // noindex,nofollow
+ { true, false, false }, // noindex,follow
+ { false, true, false }, // index,nofollow
+ { false, false, false }, // index,follow
+ { false, false, false }, // missing!
};
private URL[][] currURLsAndAnswers;
@Test
public void testRobotsMetaProcessor() {
- DOMFragmentParser parser= new DOMFragmentParser();;
-
- try {
- currURLsAndAnswers= new URL[][] {
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org/foo/"),
- new URL("http://www.nutch.org/")},
- {new URL("http://www.nutch.org"),
- new URL("http://www.nutch.org/base/")}
- };
+ DOMFragmentParser parser = new DOMFragmentParser();
+ ;
+
+ try {
+ currURLsAndAnswers = new URL[][] {
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org/foo/"),
+ new URL("http://www.nutch.org/") },
+ { new URL("http://www.nutch.org"),
+ new URL("http://www.nutch.org/base/") } };
} catch (Exception e) {
Assert.assertTrue("couldn't make test URLs!", false);
}
- for (int i= 0; i < tests.length; i++) {
- byte[] bytes= tests[i].getBytes();
+ for (int i = 0; i < tests.length; i++) {
+ byte[] bytes = tests[i].getBytes();
DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
@@ -156,9 +132,8 @@ public class TestRobotsMetaProcessor {
e.printStackTrace();
}
- HTMLMetaTags robotsMeta= new HTMLMetaTags();
- HTMLMetaProcessor.getMetaTags(robotsMeta, node,
- currURLsAndAnswers[i][0]);
+ HTMLMetaTags robotsMeta = new HTMLMetaTags();
+ HTMLMetaProcessor.getMetaTags(robotsMeta, node, currURLsAndAnswers[i][0]);
Assert.assertTrue("got index wrong on test " + i,
robotsMeta.getNoIndex() == answers[i][0]);
@@ -166,13 +141,13 @@ public class TestRobotsMetaProcessor {
robotsMeta.getNoFollow() == answers[i][1]);
Assert.assertTrue("got cache wrong on test " + i,
robotsMeta.getNoCache() == answers[i][2]);
- Assert.assertTrue("got base href wrong on test " + i + " (got "
- + robotsMeta.getBaseHref() + ")",
- ( (robotsMeta.getBaseHref() == null)
- && (currURLsAndAnswers[i][1] == null) )
- || ( (robotsMeta.getBaseHref() != null)
- && robotsMeta.getBaseHref().equals(
- currURLsAndAnswers[i][1]) ) );
+ Assert
+ .assertTrue(
+ "got base href wrong on test " + i + " (got "
+ + robotsMeta.getBaseHref() + ")",
+ ((robotsMeta.getBaseHref() == null) && (currURLsAndAnswers[i][1] == null))
+ || ((robotsMeta.getBaseHref() != null) && robotsMeta
+ .getBaseHref().equals(currURLsAndAnswers[i][1])));
}
}
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 9295cc21b..8c95372cb 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
@@ -1,19 +1,19 @@
/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You 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.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.parse.js;
import java.io.BufferedReader;
@@ -56,9 +56,9 @@ import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
- * This class is a heuristic link extractor for JavaScript files and
- * code snippets. The general idea of a two-pass regex matching comes from
- * Heritrix. Parts of the code come from OutlinkExtractor.java
+ * This class is a heuristic link extractor for JavaScript files and code
+ * snippets. The general idea of a two-pass regex matching comes from Heritrix.
+ * Parts of the code come from OutlinkExtractor.java
*/
public class JSParseFilter implements HtmlParseFilter, Parser {
public static final Logger LOG = LoggerFactory.getLogger(JSParseFilter.class);
@@ -66,9 +66,9 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
private static final int MAX_TITLE_LEN = 80;
private Configuration conf;
-
+
public ParseResult filter(Content content, ParseResult parseResult,
- HTMLMetaTags metaTags, DocumentFragment doc) {
+ HTMLMetaTags metaTags, DocumentFragment doc) {
Parse parse = parseResult.get(content.getUrl());
@@ -82,37 +82,42 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
outlinks.addAll(list);
ParseStatus status = parse.getData().getStatus();
String text = parse.getText();
- Outlink[] newlinks = (Outlink[])outlinks.toArray(new Outlink[outlinks.size()]);
- ParseData parseData = new ParseData(status, title, newlinks,
- parse.getData().getContentMeta(),
- parse.getData().getParseMeta());
+ Outlink[] newlinks = (Outlink[]) outlinks.toArray(new Outlink[outlinks
+ .size()]);
+ ParseData parseData = new ParseData(status, title, newlinks, parse
+ .getData().getContentMeta(), parse.getData().getParseMeta());
// replace original parse obj with new one
parseResult.put(content.getUrl(), new ParseText(text), parseData);
}
return parseResult;
}
-
- private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List<Outlink> outlinks) {
+
+ private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base,
+ List<Outlink> outlinks) {
if (n instanceof Element) {
String name = n.getNodeName();
if (name.equalsIgnoreCase("script")) {
- /* String lang = null;
- Node lNode = n.getAttributes().getNamedItem("language");
- if (lNode == null) lang = "javascript";
- else lang = lNode.getNodeValue(); */
+ /*
+ * String lang = null; Node lNode =
+ * n.getAttributes().getNamedItem("language"); if (lNode == null) lang =
+ * "javascript"; else lang = lNode.getNodeValue();
+ */
StringBuffer script = new StringBuffer();
NodeList nn = n.getChildNodes();
if (nn.getLength() > 0) {
for (int i = 0; i < nn.getLength(); i++) {
- if (i > 0) script.append('\n');
+ if (i > 0)
+ script.append('\n');
script.append(nn.item(i).getNodeValue());
}
// if (LOG.isInfoEnabled()) {
- // LOG.info("script: language=" + lang + ", text: " + script.toString());
+ // LOG.info("script: language=" + lang + ", text: " +
+ // script.toString());
// }
Outlink[] links = getJSLinks(script.toString(), "", base);
- if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
+ if (links != null && links.length > 0)
+ outlinks.addAll(Arrays.asList(links));
// no other children of interest here, go one level up.
return;
}
@@ -124,7 +129,8 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
// Window: onload,onunload
// Form: onchange,onsubmit,onreset,onselect,onblur,onfocus
// Keyboard: onkeydown,onkeypress,onkeyup
- // Mouse: onclick,ondbclick,onmousedown,onmouseout,onmousover,onmouseup
+ // Mouse:
+ // onclick,ondbclick,onmousedown,onmouseout,onmousover,onmouseup
Node anode = attrs.item(i);
Outlink[] links = null;
if (anode.getNodeName().startsWith("on")) {
@@ -135,7 +141,8 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
links = getJSLinks(val, "", base);
}
}
- if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
+ if (links != null && links.length > 0)
+ outlinks.addAll(Arrays.asList(links));
}
}
}
@@ -144,48 +151,56 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
walk(nl.item(i), parse, metaTags, base, outlinks);
}
}
-
+
public ParseResult getParse(Content c) {
String type = c.getContentType();
- if (type != null && !type.trim().equals("") && !type.toLowerCase().startsWith("application/x-javascript"))
+ if (type != null && !type.trim().equals("")
+ && !type.toLowerCase().startsWith("application/x-javascript"))
return new ParseStatus(ParseStatus.FAILED_INVALID_FORMAT,
- "Content not JavaScript: '" + type + "'").getEmptyParseResult(c.getUrl(), getConf());
+ "Content not JavaScript: '" + type + "'").getEmptyParseResult(
+ c.getUrl(), getConf());
String script = new String(c.getContent());
Outlink[] outlinks = getJSLinks(script, "", c.getUrl());
- if (outlinks == null) outlinks = new Outlink[0];
+ if (outlinks == null)
+ outlinks = new Outlink[0];
// Title? use the first line of the script...
String title;
int idx = script.indexOf('\n');
if (idx != -1) {
- if (idx > MAX_TITLE_LEN) idx = MAX_TITLE_LEN;
+ if (idx > MAX_TITLE_LEN)
+ idx = MAX_TITLE_LEN;
title = script.substring(0, idx);
} else {
idx = Math.min(MAX_TITLE_LEN, script.length());
title = script.substring(0, idx);
}
ParseData pd = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks,
- c.getMetadata());
+ c.getMetadata());
return ParseResult.createParseResult(c.getUrl(), new ParseImpl(script, pd));
}
-
+
private static final String STRING_PATTERN = "(\\\\*(?:\"|\'))([^\\s\"\']+?)(?:\\1)";
// A simple pattern. This allows also invalid URL characters.
private static final String URI_PATTERN = "(^|\\s*?)/?\\S+?[/\\.]\\S+($|\\s*)";
+
// Alternative pattern, which limits valid url characters.
- //private static final String URI_PATTERN = "(^|\\s*?)[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2})+[/.](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2})+(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]*))?($|\\s*)";
-
+ // private static final String URI_PATTERN =
+ // "(^|\\s*?)[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2})+[/.](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2})+(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]*))?($|\\s*)";
+
/**
- * This method extracts URLs from literals embedded in JavaScript.
+ * This method extracts URLs from literals embedded in JavaScript.
*/
private Outlink[] getJSLinks(String plainText, String anchor, String base) {
final List<Outlink> outlinks = new ArrayList<Outlink>();
URL baseURL = null;
-
+
try {
baseURL = new URL(base);
} catch (Exception e) {
- if (LOG.isErrorEnabled()) { LOG.error("getJSLinks", e); }
+ if (LOG.isErrorEnabled()) {
+ LOG.error("getJSLinks", e);
+ }
}
try {
@@ -194,8 +209,8 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
Perl5Compiler.CASE_INSENSITIVE_MASK | Perl5Compiler.READ_ONLY_MASK
| Perl5Compiler.MULTILINE_MASK);
final Pattern pattern1 = cp.compile(URI_PATTERN,
- Perl5Compiler.CASE_INSENSITIVE_MASK | Perl5Compiler.READ_ONLY_MASK
- | Perl5Compiler.MULTILINE_MASK);
+ Perl5Compiler.CASE_INSENSITIVE_MASK | Perl5Compiler.READ_ONLY_MASK
+ | Perl5Compiler.MULTILINE_MASK);
final PatternMatcher matcher = new Perl5Matcher();
final PatternMatcher matcher1 = new Perl5Matcher();
@@ -204,26 +219,27 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
MatchResult result;
String url;
- //loop the matches
+ // loop the matches
while (matcher.contains(input, pattern)) {
result = matcher.getMatch();
url = result.group(2);
PatternMatcherInput input1 = new PatternMatcherInput(url);
if (!matcher1.matches(input1, pattern1)) {
- //if (LOG.isTraceEnabled()) { LOG.trace(" - invalid '" + url + "'"); }
+ // if (LOG.isTraceEnabled()) { LOG.trace(" - invalid '" + url + "'");
+ // }
continue;
}
if (url.startsWith("www.")) {
- url = "http://" + url;
+ url = "http://" + url;
} else {
- // See if candidate URL is parseable. If not, pass and move on to
+ // See if candidate URL is parseable. If not, pass and move on to
// the next match.
try {
url = new URL(baseURL, url).toString();
} catch (MalformedURLException ex) {
if (LOG.isTraceEnabled()) {
- LOG.trace(" - failed URL parse '" + url + "' and baseURL '" +
- baseURL + "'", ex);
+ LOG.trace(" - failed URL parse '" + url + "' and baseURL '"
+ + baseURL + "'", ex);
}
continue;
}
@@ -237,12 +253,14 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
} catch (Exception ex) {
// if it is a malformed URL we just throw it away and continue with
// extraction.
- if (LOG.isErrorEnabled()) { LOG.error("getJSLinks", ex); }
+ if (LOG.isErrorEnabled()) {
+ LOG.error("getJSLinks", ex);
+ }
}
final Outlink[] retval;
- //create array of the Outlinks
+ // create array of the Outlinks
if (outlinks != null && outlinks.size() > 0) {
retval = (Outlink[]) outlinks.toArray(new Outlink[0]);
} else {
@@ -251,7 +269,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
return retval;
}
-
+
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println(JSParseFilter.class.getName() + " file.js baseURL");
@@ -261,10 +279,10 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer sb = new StringBuffer();
String line = null;
- while ((line = br.readLine()) != null)
+ while ((line = br.readLine()) != null)
sb.append(line + "\n");
br.close();
-
+
JSParseFilter parseFilter = new JSParseFilter();
parseFilter.setConf(NutchConfiguration.create());
Outlink[] links = parseFilter.getJSLinks(sb.toString(), "", args[1]);
diff --git a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/package-info.java b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/package-info.java
index 3f5ce526c..36d0d1464 100644
--- a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/package-info.java
+++ b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/package-info.java
@@ -20,3 +20,4 @@
* from JavaScript files and embedded JavaScript code snippets.
*/
package org.apache.nutch.parse.js;
+
diff --git a/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/package-info.java b/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/package-info.java
index 51c24b9b9..a55cf5cf1 100644
--- a/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/package-info.java
+++ b/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/package-info.java
@@ -21,3 +21,4 @@
* (see {@link org.apache.nutch.indexer.metadata}).
*/
package org.apache.nutch.parse.metatags;
+
diff --git a/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.java b/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.java
index d8b7028ad..92513669b 100644
--- a/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.java
+++ b/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.java
@@ -44,11 +44,13 @@ import com.anotherbigidea.io.InStream;
* distribution.
*/
public class SWFParser implements Parser {
- public static final Logger LOG = LoggerFactory.getLogger("org.apache.nutch.parse.swf");
+ public static final Logger LOG = LoggerFactory
+ .getLogger("org.apache.nutch.parse.swf");
private Configuration conf = null;
- public SWFParser() {}
+ public SWFParser() {
+ }
public void setConf(Configuration conf) {
this.conf = conf;
@@ -68,10 +70,12 @@ public class SWFParser implements Parser {
byte[] raw = content.getContent();
String contentLength = content.getMetadata().get(Response.CONTENT_LENGTH);
- if (contentLength != null && raw.length != Integer.parseInt(contentLength)) {
- return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
- "Content truncated at " + raw.length +
- " bytes. Parser can't handle incomplete files.").getEmptyParseResult(content.getUrl(), getConf());
+ if (contentLength != null
+ && raw.length != Integer.parseInt(contentLength)) {
+ return new ParseStatus(ParseStatus.FAILED,
+ ParseStatus.FAILED_TRUNCATED, "Content truncated at " + raw.length
+ + " bytes. Parser can't handle incomplete files.")
+ .getEmptyParseResult(content.getUrl(), getConf());
}
ExtractText extractor = new ExtractText();
@@ -87,7 +91,8 @@ public class SWFParser implements Parser {
reader.readFile();
text = extractor.getText();
String atext = extractor.getActionText();
- if (atext != null && atext.length() > 0) text += "\n--------\n" + atext;
+ if (atext != null && atext.length() > 0)
+ text += "\n--------\n" + atext;
// harvest potential outlinks
String[] links = extractor.getUrls();
for (int i = 0; i < links.length; i++) {
@@ -95,19 +100,25 @@ public class SWFParser implements Parser {
outlinks.add(out);
}
Outlink[] olinks = OutlinkExtractor.getOutlinks(text, conf);
- if (olinks != null) for (int i = 0; i < olinks.length; i++) {
- outlinks.add(olinks[i]);
- }
+ if (olinks != null)
+ for (int i = 0; i < olinks.length; i++) {
+ outlinks.add(olinks[i]);
+ }
} catch (Exception e) { // run time exception
LOG.error("Error, runtime exception: ", e);
- return new ParseStatus(ParseStatus.FAILED, "Can't be handled as SWF document. " + e).getEmptyParseResult(content.getUrl(), getConf());
- }
- if (text == null) text = "";
+ return new ParseStatus(ParseStatus.FAILED,
+ "Can't be handled as SWF document. " + e).getEmptyParseResult(
+ content.getUrl(), getConf());
+ }
+ if (text == null)
+ text = "";
- Outlink[] links = (Outlink[]) outlinks.toArray(new Outlink[outlinks.size()]);
+ Outlink[] links = (Outlink[]) outlinks
+ .toArray(new Outlink[outlinks.size()]);
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "", links,
- content.getMetadata());
- return ParseResult.createParseResult(content.getUrl(), new ParseImpl(text, parseData));
+ content.getMetadata());
+ return ParseResult.createParseResult(content.getUrl(), new ParseImpl(text,
+ parseData));
}
/**
@@ -120,10 +131,9 @@ public class SWFParser implements Parser {
in.read(buf);
in.close();
SWFParser parser = new SWFParser();
- ParseResult parseResult = parser.getParse(new Content("file:" + args[0], "file:" + args[0],
- buf, "application/x-shockwave-flash",
- new Metadata(),
- NutchConfiguration.create()));
+ ParseResult parseResult = parser.getParse(new Content("file:" + args[0],
+ "file:" + args[0], buf, "application/x-shockwave-flash",
+ new Metadata(), NutchConfiguration.create()));
Parse p = parseResult.get("file:" + args[0]);
System.out.println("Parse Text:");
System.out.println(p.getText());
@@ -168,7 +178,8 @@ class ExtractText extends SWFTagTypesImpl {
StringBuffer res = new StringBuffer();
Iterator<String> it = strings.iterator();
while (it.hasNext()) {
- if (res.length() > 0) res.append(' ');
+ if (res.length() > 0)
+ res.append(' ');
res.append(it.next());
}
return res.toString();
@@ -176,10 +187,12 @@ class ExtractText extends SWFTagTypesImpl {
public String getActionText() {
StringBuffer res = new StringBuffer();
- String[] strings = (String[])actionStrings.toArray(new String[actionStrings.size()]);
+ String[] strings = (String[]) actionStrings
+ .toArray(new String[actionStrings.size()]);
Arrays.sort(strings);
for (int i = 0; i < strings.length; i++) {
- if (i > 0) res.append('\n');
+ if (i > 0)
+ res.append('\n');
res.append(strings[i]);
}
return res.toString();
@@ -196,14 +209,16 @@ class ExtractText extends SWFTagTypesImpl {
return res;
}
- public void tagDefineFontInfo2(int arg0, String arg1, int arg2, int[] arg3, int arg4) throws IOException {
+ public void tagDefineFontInfo2(int arg0, String arg1, int arg2, int[] arg3,
+ int arg4) throws IOException {
tagDefineFontInfo(arg0, arg1, arg2, arg3);
}
/**
* SWFTagTypes interface Save the Text Font character code info
*/
- public void tagDefineFontInfo(int fontId, String fontName, int flags, int[] codes) throws IOException {
+ public void tagDefineFontInfo(int fontId, String fontName, int flags,
+ int[] codes) throws IOException {
// System.out.println("-defineFontInfo id=" + fontId + ", name=" +
// fontName);
fontCodes.put(new Integer(fontId), codes);
@@ -213,16 +228,16 @@ class ExtractText extends SWFTagTypesImpl {
// XXX codes anyway, so we just give up.
/*
* public SWFVectors tagDefineFont(int arg0, int arg1) throws IOException {
- * return null;
- * }
+ * return null; }
*/
/**
* SWFTagTypes interface. Save the character code info.
*/
- public SWFVectors tagDefineFont2(int id, int flags, String name, int numGlyphs, int ascent, int descent, int leading,
- int[] codes, int[] advances, Rect[] bounds, int[] kernCodes1, int[] kernCodes2, int[] kernAdjustments)
- throws IOException {
+ public SWFVectors tagDefineFont2(int id, int flags, String name,
+ int numGlyphs, int ascent, int descent, int leading, int[] codes,
+ int[] advances, Rect[] bounds, int[] kernCodes1, int[] kernCodes2,
+ int[] kernAdjustments) throws IOException {
// System.out.println("-defineFontInfo id=" + id + ", name=" + name);
fontCodes.put(new Integer(id), (codes != null) ? codes : new int[0]);
@@ -232,9 +247,10 @@ class ExtractText extends SWFTagTypesImpl {
/**
* SWFTagTypes interface. Dump any initial text in the field.
*/
- public void tagDefineTextField(int fieldId, String fieldName, String initialText, Rect boundary, int flags,
- AlphaColor textColor, int alignment, int fontId, int fontSize, int charLimit, int leftMargin,
- int rightMargin, int indentation, int lineSpacing) throws IOException {
+ public void tagDefineTextField(int fieldId, String fieldName,
+ String initialText, Rect boundary, int flags, AlphaColor textColor,
+ int alignment, int fontId, int fontSize, int charLimit, int leftMargin,
+ int rightMargin, int indentation, int lineSpacing) throws IOException {
if (initialText != null) {
strings.add(initialText);
}
@@ -243,7 +259,8 @@ class ExtractText extends SWFTagTypesImpl {
/**
* SWFTagTypes interface
*/
- public SWFText tagDefineText(int id, Rect bounds, Matrix matrix) throws IOException {
+ public SWFText tagDefineText(int id, Rect bounds, Matrix matrix)
+ throws IOException {
lastBounds = curBounds;
curBounds = bounds;
return new TextDumper();
@@ -255,7 +272,8 @@ class ExtractText extends SWFTagTypesImpl {
/**
* SWFTagTypes interface
*/
- public SWFText tagDefineText2(int id, Rect bounds, Matrix matrix) throws IOException {
+ public SWFText tagDefineText2(int id, Rect bounds, Matrix matrix)
+ throws IOException {
lastBounds = curBounds;
curBounds = bounds;
return new TextDumper();
@@ -273,15 +291,16 @@ class ExtractText extends SWFTagTypesImpl {
public void setY(int y) {
if (firstY)
firstY = false;
- else strings.add("\n"); // Change in Y - dump a new line
+ else
+ strings.add("\n"); // Change in Y - dump a new line
}
/*
* There are some issues with this method: sometimes SWF files define their
- * own font, so short of OCR we cannot guess what is the glyph code -> character
- * mapping. Additionally, some files don't use literal space character, instead
- * they adjust glyphAdvances. We don't handle it at all - in such cases the text
- * will be all glued together.
+ * own font, so short of OCR we cannot guess what is the glyph code ->
+ * character mapping. Additionally, some files don't use literal space
+ * character, instead they adjust glyphAdvances. We don't handle it at all -
+ * in such cases the text will be all glued together.
*/
public void text(int[] glyphIndices, int[] glyphAdvances) {
// System.out.println("-text id=" + fontId);
@@ -310,9 +329,11 @@ class ExtractText extends SWFTagTypesImpl {
strings.add(new String(chars));
}
- public void color(Color color) {}
+ public void color(Color color) {
+ }
- public void setX(int x) {}
+ public void setX(int x) {
+ }
public void done() {
strings.add("\n");
@@ -367,7 +388,8 @@ class NutchSWFActions extends SWFActionBlockImpl implements SWFActions {
public void lookupTable(String[] values) throws IOException {
for (int i = 0; i < values.length; i++) {
- if (!strings.contains(values[i])) strings.add(values[i]);
+ if (!strings.contains(values[i]))
+ strings.add(values[i]);
}
super.lookupTable(values);
dict = values;
@@ -379,7 +401,7 @@ class NutchSWFActions extends SWFActionBlockImpl implements SWFActions {
}
public void getURL(int vars, int mode) {
- // System.out.println("-getURL: vars=" + vars + ", mode=" + mode);
+ // System.out.println("-getURL: vars=" + vars + ", mode=" + mode);
}
public void getURL(String url, String target) throws IOException {
@@ -444,7 +466,8 @@ class NutchSWFActions extends SWFActionBlockImpl implements SWFActions {
super.setTarget(var);
}
- public SWFActionBlock startFunction(String var, String[] params) throws IOException {
+ public SWFActionBlock startFunction(String var, String[] params)
+ throws IOException {
stack.push(var);
strings.remove(var);
if (params != null) {
@@ -455,7 +478,8 @@ class NutchSWFActions extends SWFActionBlockImpl implements SWFActions {
return this;
}
- public SWFActionBlock startFunction2(String var, int arg1, int arg2, String[] params, int[] arg3) throws IOException {
+ public SWFActionBlock startFunction2(String var, int arg1, int arg2,
+ String[] params, int[] arg3) throws IOException {
stack.push(var);
strings.remove(var);
if (params != null) {
@@ -655,6 +679,7 @@ class SmallStack extends Stack<Object> {
// tolerate underruns
if (this.size() == 0)
return null;
- else return super.pop();
+ else
+ return super.pop();
}
}
diff --git a/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/package-info.java b/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/package-info.java
index c020f03b2..5942e6418 100644
--- a/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/package-info.java
+++ b/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/package-info.java
@@ -19,3 +19,4 @@
* Parse Flash SWF files.
*/
package org.apache.nutch.parse.swf;
+
diff --git a/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.java b/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.java
index c5745a8d0..129b85f6e 100644
--- a/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.java
+++ b/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.java
@@ -34,17 +34,19 @@ import org.apache.nutch.util.NutchConfiguration;
import org.junit.Assert;
import org.junit.Test;
-/**
+/**
* Unit tests for SWFParser.
*/
public class TestSWFParser {
private String fileSeparator = System.getProperty("file.separator");
// This system property is defined in ./src/plugin/build-plugin.xml
- private String sampleDir = System.getProperty("test.data",".");
+ private String sampleDir = System.getProperty("test.data", ".");
- private String[] sampleFiles = new String[]{"test1.swf", "test2.swf", "test3.swf"};
- private String[] sampleTexts = new String[]{"test1.txt", "test2.txt", "test3.txt"};
+ private String[] sampleFiles = new String[] { "test1.swf", "test2.swf",
+ "test3.swf" };
+ private String[] sampleTexts = new String[] { "test1.txt", "test2.txt",
+ "test3.txt" };
@Test
public void testIt() throws ProtocolException, ParseException {
@@ -58,7 +60,8 @@ public class TestSWFParser {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
protocol = new ProtocolFactory(conf).getProtocol(urlString);
- content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
+ content = protocol.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
parse = new ParseUtil(conf).parse(content).get(content.getUrl());
@@ -67,11 +70,12 @@ public class TestSWFParser {
}
}
- public TestSWFParser() {
+ public TestSWFParser() {
for (int i = 0; i < sampleFiles.length; i++) {
try {
// read the test string
- FileInputStream fis = new FileInputStream(sampleDir + fileSeparator + sampleTexts[i]);
+ FileInputStream fis = new FileInputStream(sampleDir + fileSeparator
+ + sampleTexts[i]);
StringBuffer sb = new StringBuffer();
int len = 0;
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java
index 85cf91d74..8536e84cb 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java
@@ -39,137 +39,126 @@ import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.ext.LexicalHandler;
+
/**
- * This class takes SAX events (in addition to some extra events
- * that SAX doesn't handle yet) and adds the result to a document
- * or document fragment.
+ * This class takes SAX events (in addition to some extra events that SAX
+ * doesn't handle yet) and adds the result to a document or document fragment.
*/
-class DOMBuilder
- implements ContentHandler, LexicalHandler
-{
- private boolean upperCaseElementNames = true;
+class DOMBuilder implements ContentHandler, LexicalHandler {
+ private boolean upperCaseElementNames = true;
- /** Root document */
+ /** Root document */
public Document m_doc;
- /** Current node */
+ /** Current node */
protected Node m_currentNode = null;
- /** First node of document fragment or null if not a DocumentFragment */
+ /** First node of document fragment or null if not a DocumentFragment */
public DocumentFragment m_docFrag = null;
- /** Vector of element nodes */
+ /** Vector of element nodes */
protected Stack<Element> m_elemStack = new Stack<Element>();
/**
- * DOMBuilder instance constructor... it will add the DOM nodes
- * to the document fragment.
- *
- * @param doc Root document
- * @param node Current node
+ * DOMBuilder instance constructor... it will add the DOM nodes to the
+ * document fragment.
+ *
+ * @param doc
+ * Root document
+ * @param node
+ * Current node
*/
- DOMBuilder(Document doc, Node node)
- {
+ DOMBuilder(Document doc, Node node) {
m_doc = doc;
m_currentNode = node;
}
/**
- * DOMBuilder instance constructor... it will add the DOM nodes
- * to the document fragment.
- *
- * @param doc Root document
- * @param docFrag Document fragment
+ * DOMBuilder instance constructor... it will add the DOM nodes to the
+ * document fragment.
+ *
+ * @param doc
+ * Root document
+ * @param docFrag
+ * Document fragment
*/
- DOMBuilder(Document doc, DocumentFragment docFrag)
- {
+ DOMBuilder(Document doc, DocumentFragment docFrag) {
m_doc = doc;
m_docFrag = docFrag;
}
/**
- * DOMBuilder instance constructor... it will add the DOM nodes
- * to the document.
- *
- * @param doc Root document
+ * DOMBuilder instance constructor... it will add the DOM nodes to the
+ * document.
+ *
+ * @param doc
+ * Root document
*/
- DOMBuilder(Document doc)
- {
+ DOMBuilder(Document doc) {
m_doc = doc;
}
/**
- * Get the root node of the DOM being created. This
- * is either a Document or a DocumentFragment.
- *
+ * Get the root node of the DOM being created. This is either a Document or a
+ * DocumentFragment.
+ *
* @return The root document or document fragment if not null
*/
- Node getRootNode()
- {
+ Node getRootNode() {
return (null != m_docFrag) ? (Node) m_docFrag : (Node) m_doc;
}
/**
* Get the node currently being processed.
- *
+ *
* @return the current node being processed
*/
- Node getCurrentNode()
- {
+ Node getCurrentNode() {
return m_currentNode;
}
/**
* Return null since there is no Writer for this class.
- *
+ *
* @return null
*/
- java.io.Writer getWriter()
- {
+ java.io.Writer getWriter() {
return null;
}
/**
* Append a node to the current container.
- *
- * @param newNode New node to append
+ *
+ * @param newNode
+ * New node to append
*/
- protected void append(Node newNode) throws org.xml.sax.SAXException
- {
+ protected void append(Node newNode) throws org.xml.sax.SAXException {
Node currentNode = m_currentNode;
- if (null != currentNode)
- {
+ if (null != currentNode) {
currentNode.appendChild(newNode);
// System.out.println(newNode.getNodeName());
- }
- else if (null != m_docFrag)
- {
+ } else if (null != m_docFrag) {
m_docFrag.appendChild(newNode);
- }
- else
- {
+ } else {
boolean ok = true;
short type = newNode.getNodeType();
- if (type == Node.TEXT_NODE)
- {
+ if (type == Node.TEXT_NODE) {
String data = newNode.getNodeValue();
- if ((null != data) && (data.trim().length() > 0))
- {
- throw new org.xml.sax.SAXException("Warning: can't output text before document element! Ignoring...");
+ if ((null != data) && (data.trim().length() > 0)) {
+ throw new org.xml.sax.SAXException(
+ "Warning: can't output text before document element! Ignoring...");
}
ok = false;
- }
- else if (type == Node.ELEMENT_NODE)
- {
- if (m_doc.getDocumentElement() != null)
- {
- throw new org.xml.sax.SAXException("Can't have more than one root on a DOM!");
+ } else if (type == Node.ELEMENT_NODE) {
+ if (m_doc.getDocumentElement() != null) {
+ throw new org.xml.sax.SAXException(
+ "Can't have more than one root on a DOM!");
}
}
@@ -180,135 +169,142 @@ class DOMBuilder
/**
* Receive an object for locating the origin of SAX document events.
- *
- * <p>SAX parsers are strongly encouraged (though not absolutely
- * required) to supply a locator: if it does so, it must supply
- * the locator to the application by invoking this method before
- * invoking any of the other methods in the ContentHandler
- * interface.</p>
- *
- * <p>The locator allows the application to determine the end
- * position of any document-related event, even if the parser is
- * not reporting an error. Typically, the application will
- * use this information for reporting its own errors (such as
- * character content that does not match an application's
- * business rules). The information returned by the locator
- * is probably not sufficient for use with a search engine.</p>
- *
- * <p>Note that the locator will return correct information only
- * during the invocation of the events in this interface. The
- * application should not attempt to use it at any other time.</p>
- *
- * @param locator An object that can return the location of
- * any SAX document event.
+ *
+ * <p>
+ * SAX parsers are strongly encouraged (though not absolutely required) to
+ * supply a locator: if it does so, it must supply the locator to the
+ * application by invoking this method before invoking any of the other
+ * methods in the ContentHandler interface.
+ * </p>
+ *
+ * <p>
+ * The locator allows the application to determine the end position of any
+ * document-related event, even if the parser is not reporting an error.
+ * Typically, the application will use this information for reporting its own
+ * errors (such as character content that does not match an application's
+ * business rules). The information returned by the locator is probably not
+ * sufficient for use with a search engine.
+ * </p>
+ *
+ * <p>
+ * Note that the locator will return correct information only during the
+ * invocation of the events in this interface. The application should not
+ * attempt to use it at any other time.
+ * </p>
+ *
+ * @param locator
+ * An object that can return the location of any SAX document event.
* @see org.xml.sax.Locator
*/
- public void setDocumentLocator(Locator locator)
- {
+ public void setDocumentLocator(Locator locator) {
// No action for the moment.
}
/**
* Receive notification of the beginning of a document.
- *
- * <p>The SAX parser will invoke this method only once, before any
- * other methods in this interface or in DTDHandler (except for
- * setDocumentLocator).</p>
+ *
+ * <p>
+ * The SAX parser will invoke this method only once, before any other methods
+ * in this interface or in DTDHandler (except for setDocumentLocator).
+ * </p>
*/
- public void startDocument() throws org.xml.sax.SAXException
- {
+ public void startDocument() throws org.xml.sax.SAXException {
// No action for the moment.
}
/**
* Receive notification of the end of a document.
- *
- * <p>The SAX parser will invoke this method only once, and it will
- * be the last method invoked during the parse. The parser shall
- * not invoke this method until it has either abandoned parsing
- * (because of an unrecoverable error) or reached the end of
- * input.</p>
+ *
+ * <p>
+ * The SAX parser will invoke this method only once, and it will be the last
+ * method invoked during the parse. The parser shall not invoke this method
+ * until it has either abandoned parsing (because of an unrecoverable error)
+ * or reached the end of input.
+ * </p>
*/
- public void endDocument() throws org.xml.sax.SAXException
- {
+ public void endDocument() throws org.xml.sax.SAXException {
// No action for the moment.
}
/**
* Receive notification of the beginning of an element.
- *
- * <p>The Parser will invoke this method at the beginning of every
- * element in the XML document; there will be a corresponding
- * endElement() event for every startElement() event (even when the
- * element is empty). All of the element's content will be
- * reported, in order, before the corresponding endElement()
- * event.</p>
- *
- * <p>If the element name has a namespace prefix, the prefix will
- * still be attached. Note that the attribute list provided will
- * contain only attributes with explicit values (specified or
- * defaulted): #IMPLIED attributes will be omitted.</p>
- *
- *
- * @param ns The namespace of the node
- * @param localName The local part of the qualified name
- * @param name The element name.
- * @param atts The attributes attached to the element, if any.
+ *
+ * <p>
+ * The Parser will invoke this method at the beginning of every element in the
+ * XML document; there will be a corresponding endElement() event for every
+ * startElement() event (even when the element is empty). All of the element's
+ * content will be reported, in order, before the corresponding endElement()
+ * event.
+ * </p>
+ *
+ * <p>
+ * If the element name has a namespace prefix, the prefix will still be
+ * attached. Note that the attribute list provided will contain only
+ * attributes with explicit values (specified or defaulted): #IMPLIED
+ * attributes will be omitted.
+ * </p>
+ *
+ *
+ * @param ns
+ * The namespace of the node
+ * @param localName
+ * The local part of the qualified name
+ * @param name
+ * The element name.
+ * @param atts
+ * The attributes attached to the element, if any.
* @see #endElement
* @see org.xml.sax.Attributes
*/
- public void startElement(
- String ns, String localName, String name, Attributes atts)
- throws org.xml.sax.SAXException
- {
+ public void startElement(String ns, String localName, String name,
+ Attributes atts) throws org.xml.sax.SAXException {
Element elem;
-
+
if (upperCaseElementNames)
- name = name.toUpperCase();
-
- // Note that the namespace-aware call must be used to correctly
- // construct a Level 2 DOM, even for non-namespaced nodes.
+ name = name.toUpperCase();
+
+ // Note that the namespace-aware call must be used to correctly
+ // construct a Level 2 DOM, even for non-namespaced nodes.
if ((null == ns) || (ns.length() == 0))
- elem = m_doc.createElementNS(null,name);
+ elem = m_doc.createElementNS(null, name);
else
elem = m_doc.createElementNS(ns, name);
append(elem);
- try
- {
+ try {
int nAtts = atts.getLength();
- if (0 != nAtts)
- {
- for (int i = 0; i < nAtts; i++)
- {
+ if (0 != nAtts) {
+ for (int i = 0; i < nAtts; i++) {
- //System.out.println("type " + atts.getType(i) + " name " + atts.getLocalName(i) );
+ // System.out.println("type " + atts.getType(i) + " name " +
+ // atts.getLocalName(i) );
// First handle a possible ID attribute
if (atts.getType(i).equalsIgnoreCase("ID"))
setIDAttribute(atts.getValue(i), elem);
String attrNS = atts.getURI(i);
- if("".equals(attrNS))
+ if ("".equals(attrNS))
attrNS = null; // DOM represents no-namespace as null
// System.out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i)
- // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i));
+ // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i));
// Crimson won't let us set an xmlns: attribute on the DOM.
String attrQName = atts.getQName(i);
- // In SAX, xmlns: attributes have an empty namespace, while in DOM they should have the xmlns namespace
+ // In SAX, xmlns: attributes have an empty namespace, while in DOM
+ // they should have the xmlns namespace
if (attrQName.startsWith("xmlns:"))
attrNS = "http://www.w3.org/2000/xmlns/";
// ALWAYS use the DOM Level 2 call!
- elem.setAttributeNS(attrNS,attrQName, atts.getValue(i));
+ elem.setAttributeNS(attrNS, attrQName, atts.getValue(i));
}
}
@@ -319,9 +315,7 @@ class DOMBuilder
m_currentNode = elem;
// append(elem);
- }
- catch(java.lang.Exception de)
- {
+ } catch (java.lang.Exception de) {
// de.printStackTrace();
throw new org.xml.sax.SAXException(de);
}
@@ -329,74 +323,87 @@ class DOMBuilder
}
/**
-
-
-
+ *
+ *
+ *
* Receive notification of the end of an element.
- *
- * <p>The SAX parser will invoke this method at the end of every
- * element in the XML document; there will be a corresponding
- * startElement() event for every endElement() event (even when the
- * element is empty).</p>
- *
- * <p>If the element name has a namespace prefix, the prefix will
- * still be attached to the name.</p>
- *
- *
- * @param ns the namespace of the element
- * @param localName The local part of the qualified name of the element
- * @param name The element name
+ *
+ * <p>
+ * The SAX parser will invoke this method at the end of every element in the
+ * XML document; there will be a corresponding startElement() event for every
+ * endElement() event (even when the element is empty).
+ * </p>
+ *
+ * <p>
+ * If the element name has a namespace prefix, the prefix will still be
+ * attached to the name.
+ * </p>
+ *
+ *
+ * @param ns
+ * the namespace of the element
+ * @param localName
+ * The local part of the qualified name of the element
+ * @param name
+ * The element name
*/
public void endElement(String ns, String localName, String name)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
m_elemStack.pop();
- m_currentNode = m_elemStack.isEmpty() ? null : (Node)m_elemStack.peek();
+ m_currentNode = m_elemStack.isEmpty() ? null : (Node) m_elemStack.peek();
}
/**
* Set an ID string to node association in the ID table.
- *
- * @param id The ID string.
- * @param elem The associated ID.
+ *
+ * @param id
+ * The ID string.
+ * @param elem
+ * The associated ID.
*/
- public void setIDAttribute(String id, Element elem)
- {
+ public void setIDAttribute(String id, Element elem) {
// Do nothing. This method is meant to be overiden.
}
/**
* Receive notification of character data.
- *
- * <p>The Parser will call this method to report each chunk of
- * character data. SAX parsers may return all contiguous character
- * data in a single chunk, or they may split it into several
- * chunks; however, all of the characters in any single event
- * must come from the same external entity, so that the Locator
- * provides useful information.</p>
- *
- * <p>The application must not attempt to read from the array
- * outside of the specified range.</p>
- *
- * <p>Note that some parsers will report whitespace using the
- * ignorableWhitespace() method rather than this one (validating
- * parsers must do so).</p>
- *
- * @param ch The characters from the XML document.
- * @param start The start position in the array.
- * @param length The number of characters to read from the array.
+ *
+ * <p>
+ * The Parser will call this method to report each chunk of character data.
+ * SAX parsers may return all contiguous character data in a single chunk, or
+ * they may split it into several chunks; however, all of the characters in
+ * any single event must come from the same external entity, so that the
+ * Locator provides useful information.
+ * </p>
+ *
+ * <p>
+ * The application must not attempt to read from the array outside of the
+ * specified range.
+ * </p>
+ *
+ * <p>
+ * Note that some parsers will report whitespace using the
+ * ignorableWhitespace() method rather than this one (validating parsers must
+ * do so).
+ * </p>
+ *
+ * @param ch
+ * The characters from the XML document.
+ * @param start
+ * The start position in the array.
+ * @param length
+ * The number of characters to read from the array.
* @see #ignorableWhitespace
* @see org.xml.sax.Locator
*/
- public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem()
- && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
- return; // avoid DOM006 Hierarchy request error
-
- if (m_inCData)
- {
+ public void characters(char ch[], int start, int length)
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem()
+ && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
+ return; // avoid DOM006 Hierarchy request error
+
+ if (m_inCData) {
cdata(ch, start, length);
return;
@@ -404,57 +411,55 @@ class DOMBuilder
String s = new String(ch, start, length);
Node childNode;
- childNode = m_currentNode != null ? m_currentNode.getLastChild(): null;
- if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
- ((Text)childNode).appendData(s);
- }
- else{
- Text text = m_doc.createTextNode(s);
- append(text);
+ childNode = m_currentNode != null ? m_currentNode.getLastChild() : null;
+ if (childNode != null && childNode.getNodeType() == Node.TEXT_NODE) {
+ ((Text) childNode).appendData(s);
+ } else {
+ Text text = m_doc.createTextNode(s);
+ append(text);
}
}
/**
- * If available, when the disable-output-escaping attribute is used,
- * output raw text without escaping. A PI will be inserted in front
- * of the node with the name "lotusxsl-next-is-raw" and a value of
- * "formatter-to-dom".
- *
- * @param ch Array containing the characters
- * @param start Index to start of characters in the array
- * @param length Number of characters in the array
+ * If available, when the disable-output-escaping attribute is used, output
+ * raw text without escaping. A PI will be inserted in front of the node with
+ * the name "lotusxsl-next-is-raw" and a value of "formatter-to-dom".
+ *
+ * @param ch
+ * Array containing the characters
+ * @param start
+ * Index to start of characters in the array
+ * @param length
+ * Number of characters in the array
*/
public void charactersRaw(char ch[], int start, int length)
- throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem()
- && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
- return; // avoid DOM006 Hierarchy request error
-
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem()
+ && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
+ return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
append(m_doc.createProcessingInstruction("xslt-next-is-raw",
- "formatter-to-dom"));
+ "formatter-to-dom"));
append(m_doc.createTextNode(s));
}
/**
* Report the beginning of an entity.
- *
- * The start and end of the document entity are not reported.
- * The start and end of the external DTD subset are reported
- * using the pseudo-name "[dtd]". All other events must be
- * properly nested within start/end entity events.
- *
- * @param name The name of the entity. If it is a parameter
- * entity, the name will begin with '%'.
+ *
+ * The start and end of the document entity are not reported. The start and
+ * end of the external DTD subset are reported using the pseudo-name "[dtd]".
+ * All other events must be properly nested within start/end entity events.
+ *
+ * @param name
+ * The name of the entity. If it is a parameter entity, the name will
+ * begin with '%'.
* @see #endEntity
* @see org.xml.sax.ext.DeclHandler#internalEntityDecl
* @see org.xml.sax.ext.DeclHandler#externalEntityDecl
*/
- public void startEntity(String name) throws org.xml.sax.SAXException
- {
+ public void startEntity(String name) throws org.xml.sax.SAXException {
// Almost certainly the wrong behavior...
// entityReference(name);
@@ -462,49 +467,58 @@ class DOMBuilder
/**
* Report the end of an entity.
- *
- * @param name The name of the entity that is ending.
+ *
+ * @param name
+ * The name of the entity that is ending.
* @see #startEntity
*/
- public void endEntity(String name) throws org.xml.sax.SAXException{}
+ public void endEntity(String name) throws org.xml.sax.SAXException {
+ }
/**
* Receive notivication of a entityReference.
- *
- * @param name name of the entity reference
+ *
+ * @param name
+ * name of the entity reference
*/
- public void entityReference(String name) throws org.xml.sax.SAXException
- {
+ public void entityReference(String name) throws org.xml.sax.SAXException {
append(m_doc.createEntityReference(name));
}
/**
* Receive notification of ignorable whitespace in element content.
- *
- * <p>Validating Parsers must use this method to report each chunk
- * of ignorable whitespace (see the W3C XML 1.0 recommendation,
- * section 2.10): non-validating parsers may also use this method
- * if they are capable of parsing and using content models.</p>
- *
- * <p>SAX parsers may return all contiguous whitespace in a single
- * chunk, or they may split it into several chunks; however, all of
- * the characters in any single event must come from the same
- * external entity, so that the Locator provides useful
- * information.</p>
- *
- * <p>The application must not attempt to read from the array
- * outside of the specified range.</p>
- *
- * @param ch The characters from the XML document.
- * @param start The start position in the array.
- * @param length The number of characters to read from the array.
+ *
+ * <p>
+ * Validating Parsers must use this method to report each chunk of ignorable
+ * whitespace (see the W3C XML 1.0 recommendation, section 2.10):
+ * non-validating parsers may also use this method if they are capable of
+ * parsing and using content models.
+ * </p>
+ *
+ * <p>
+ * SAX parsers may return all contiguous whitespace in a single chunk, or they
+ * may split it into several chunks; however, all of the characters in any
+ * single event must come from the same external entity, so that the Locator
+ * provides useful information.
+ * </p>
+ *
+ * <p>
+ * The application must not attempt to read from the array outside of the
+ * specified range.
+ * </p>
+ *
+ * @param ch
+ * The characters from the XML document.
+ * @param start
+ * The start position in the array.
+ * @param length
+ * The number of characters to read from the array.
* @see #characters
*/
public void ignorableWhitespace(char ch[], int start, int length)
- throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem())
- return; // avoid DOM006 Hierarchy request error
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem())
+ return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
@@ -513,240 +527,252 @@ class DOMBuilder
/**
* Tell if the current node is outside the document element.
- *
+ *
* @return true if the current node is outside the document element.
*/
- private boolean isOutsideDocElem()
- {
- return (null == m_docFrag) && m_elemStack.size() == 0 && (null == m_currentNode || m_currentNode.getNodeType() == Node.DOCUMENT_NODE);
- }
+ private boolean isOutsideDocElem() {
+ return (null == m_docFrag)
+ && m_elemStack.size() == 0
+ && (null == m_currentNode || m_currentNode.getNodeType() == Node.DOCUMENT_NODE);
+ }
/**
* Receive notification of a processing instruction.
- *
- * <p>The Parser will invoke this method once for each processing
- * instruction found: note that processing instructions may occur
- * before or after the main document element.</p>
- *
- * <p>A SAX parser should never report an XML declaration (XML 1.0,
- * section 2.8) or a text declaration (XML 1.0, section 4.3.1)
- * using this method.</p>
- *
- * @param target The processing instruction target.
- * @param data The processing instruction data, or null if
- * none was supplied.
+ *
+ * <p>
+ * The Parser will invoke this method once for each processing instruction
+ * found: note that processing instructions may occur before or after the main
+ * document element.
+ * </p>
+ *
+ * <p>
+ * A SAX parser should never report an XML declaration (XML 1.0, section 2.8)
+ * or a text declaration (XML 1.0, section 4.3.1) using this method.
+ * </p>
+ *
+ * @param target
+ * The processing instruction target.
+ * @param data
+ * The processing instruction data, or null if none was supplied.
*/
public void processingInstruction(String target, String data)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
append(m_doc.createProcessingInstruction(target, data));
}
/**
* Report an XML comment anywhere in the document.
- *
- * This callback will be used for comments inside or outside the
- * document element, including comments in the external DTD
- * subset (if read).
- *
- * @param ch An array holding the characters in the comment.
- * @param start The starting position in the array.
- * @param length The number of characters to use from the array.
+ *
+ * This callback will be used for comments inside or outside the document
+ * element, including comments in the external DTD subset (if read).
+ *
+ * @param ch
+ * An array holding the characters in the comment.
+ * @param start
+ * The starting position in the array.
+ * @param length
+ * The number of characters to use from the array.
*/
- public void comment(char ch[], int start, int length) throws org.xml.sax.SAXException
- {
+ public void comment(char ch[], int start, int length)
+ throws org.xml.sax.SAXException {
// tagsoup sometimes submits invalid values here
- if (ch == null || start < 0 || length >= (ch.length - start) || length < 0) return;
+ if (ch == null || start < 0 || length >= (ch.length - start) || length < 0)
+ return;
append(m_doc.createComment(new String(ch, start, length)));
}
- /** Flag indicating that we are processing a CData section */
+ /** Flag indicating that we are processing a CData section */
protected boolean m_inCData = false;
/**
* Report the start of a CDATA section.
- *
+ *
* @see #endCDATA
*/
- public void startCDATA() throws org.xml.sax.SAXException
- {
+ public void startCDATA() throws org.xml.sax.SAXException {
m_inCData = true;
append(m_doc.createCDATASection(""));
}
/**
* Report the end of a CDATA section.
- *
+ *
* @see #startCDATA
*/
- public void endCDATA() throws org.xml.sax.SAXException
- {
+ public void endCDATA() throws org.xml.sax.SAXException {
m_inCData = false;
}
/**
* Receive notification of cdata.
- *
- * <p>The Parser will call this method to report each chunk of
- * character data. SAX parsers may return all contiguous character
- * data in a single chunk, or they may split it into several
- * chunks; however, all of the characters in any single event
- * must come from the same external entity, so that the Locator
- * provides useful information.</p>
- *
- * <p>The application must not attempt to read from the array
- * outside of the specified range.</p>
- *
- * <p>Note that some parsers will report whitespace using the
- * ignorableWhitespace() method rather than this one (validating
- * parsers must do so).</p>
- *
- * @param ch The characters from the XML document.
- * @param start The start position in the array.
- * @param length The number of characters to read from the array.
+ *
+ * <p>
+ * The Parser will call this method to report each chunk of character data.
+ * SAX parsers may return all contiguous character data in a single chunk, or
+ * they may split it into several chunks; however, all of the characters in
+ * any single event must come from the same external entity, so that the
+ * Locator provides useful information.
+ * </p>
+ *
+ * <p>
+ * The application must not attempt to read from the array outside of the
+ * specified range.
+ * </p>
+ *
+ * <p>
+ * Note that some parsers will report whitespace using the
+ * ignorableWhitespace() method rather than this one (validating parsers must
+ * do so).
+ * </p>
+ *
+ * @param ch
+ * The characters from the XML document.
+ * @param start
+ * The start position in the array.
+ * @param length
+ * The number of characters to read from the array.
* @see #ignorableWhitespace
* @see org.xml.sax.Locator
*/
- public void cdata(char ch[], int start, int length) throws org.xml.sax.SAXException
- {
- if(isOutsideDocElem()
- && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
- return; // avoid DOM006 Hierarchy request error
+ public void cdata(char ch[], int start, int length)
+ throws org.xml.sax.SAXException {
+ if (isOutsideDocElem()
+ && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
+ return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
- // XXX [email protected]: modified from the original, to accomodate TagSoup.
+ // XXX [email protected]: modified from the original, to accomodate TagSoup.
Node n = m_currentNode.getLastChild();
if (n instanceof CDATASection)
- ((CDATASection)n).appendData(s);
+ ((CDATASection) n).appendData(s);
else if (n instanceof Comment)
- ((Comment)n).appendData(s);
+ ((Comment) n).appendData(s);
}
/**
* Report the start of DTD declarations, if any.
- *
- * Any declarations are assumed to be in the internal subset
- * unless otherwise indicated.
- *
- * @param name The document type name.
- * @param publicId The declared public identifier for the
- * external DTD subset, or null if none was declared.
- * @param systemId The declared system identifier for the
- * external DTD subset, or null if none was declared.
+ *
+ * Any declarations are assumed to be in the internal subset unless otherwise
+ * indicated.
+ *
+ * @param name
+ * The document type name.
+ * @param publicId
+ * The declared public identifier for the external DTD subset, or
+ * null if none was declared.
+ * @param systemId
+ * The declared system identifier for the external DTD subset, or
+ * null if none was declared.
* @see #endDTD
* @see #startEntity
*/
public void startDTD(String name, String publicId, String systemId)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
// Do nothing for now.
}
/**
* Report the end of DTD declarations.
- *
+ *
* @see #startDTD
*/
- public void endDTD() throws org.xml.sax.SAXException
- {
+ public void endDTD() throws org.xml.sax.SAXException {
// Do nothing for now.
}
/**
* Begin the scope of a prefix-URI Namespace mapping.
- *
- * <p>The information from this event is not necessary for
- * normal Namespace processing: the SAX XML reader will
- * automatically replace prefixes for element and attribute
- * names when the http://xml.org/sax/features/namespaces
- * feature is true (the default).</p>
- *
- * <p>There are cases, however, when applications need to
- * use prefixes in character data or in attribute values,
- * where they cannot safely be expanded automatically; the
- * start/endPrefixMapping event supplies the information
- * to the application to expand prefixes in those contexts
- * itself, if necessary.</p>
- *
- * <p>Note that start/endPrefixMapping events are not
- * guaranteed to be properly nested relative to each-other:
- * all startPrefixMapping events will occur before the
- * corresponding startElement event, and all endPrefixMapping
- * events will occur after the corresponding endElement event,
- * but their order is not guaranteed.</p>
- *
- * @param prefix The Namespace prefix being declared.
- * @param uri The Namespace URI the prefix is mapped to.
+ *
+ * <p>
+ * The information from this event is not necessary for normal Namespace
+ * processing: the SAX XML reader will automatically replace prefixes for
+ * element and attribute names when the http://xml.org/sax/features/namespaces
+ * feature is true (the default).
+ * </p>
+ *
+ * <p>
+ * There are cases, however, when applications need to use prefixes in
+ * character data or in attribute values, where they cannot safely be expanded
+ * automatically; the start/endPrefixMapping event supplies the information to
+ * the application to expand prefixes in those contexts itself, if necessary.
+ * </p>
+ *
+ * <p>
+ * Note that start/endPrefixMapping events are not guaranteed to be properly
+ * nested relative to each-other: all startPrefixMapping events will occur
+ * before the corresponding startElement event, and all endPrefixMapping
+ * events will occur after the corresponding endElement event, but their order
+ * is not guaranteed.
+ * </p>
+ *
+ * @param prefix
+ * The Namespace prefix being declared.
+ * @param uri
+ * The Namespace URI the prefix is mapped to.
* @see #endPrefixMapping
* @see #startElement
*/
public void startPrefixMapping(String prefix, String uri)
- throws org.xml.sax.SAXException
- {
+ throws org.xml.sax.SAXException {
/*
- // Not sure if this is needed or wanted
- // Also, it fails in the stree.
- if((null != m_currentNode)
- && (m_currentNode.getNodeType() == Node.ELEMENT_NODE))
- {
- String qname;
- if(((null != prefix) && (prefix.length() == 0))
- || (null == prefix))
- qname = "xmlns";
- else
- qname = "xmlns:"+prefix;
-
- Element elem = (Element)m_currentNode;
- String val = elem.getAttribute(qname); // Obsolete, should be DOM2...?
- if(val == null)
- {
- elem.setAttributeNS("http://www.w3.org/XML/1998/namespace",
- qname, uri);
- }
- }
- */
+ * // Not sure if this is needed or wanted // Also, it fails in the stree.
+ * if((null != m_currentNode) && (m_currentNode.getNodeType() ==
+ * Node.ELEMENT_NODE)) { String qname; if(((null != prefix) &&
+ * (prefix.length() == 0)) || (null == prefix)) qname = "xmlns"; else qname
+ * = "xmlns:"+prefix;
+ *
+ * Element elem = (Element)m_currentNode; String val =
+ * elem.getAttribute(qname); // Obsolete, should be DOM2...? if(val == null)
+ * { elem.setAttributeNS("http://www.w3.org/XML/1998/namespace", qname,
+ * uri); } }
+ */
}
/**
* End the scope of a prefix-URI mapping.
- *
- * <p>See startPrefixMapping for details. This event will
- * always occur after the corresponding endElement event,
- * but the order of endPrefixMapping events is not otherwise
- * guaranteed.</p>
- *
- * @param prefix The prefix that was being mapping.
+ *
+ * <p>
+ * See startPrefixMapping for details. This event will always occur after the
+ * corresponding endElement event, but the order of endPrefixMapping events is
+ * not otherwise guaranteed.
+ * </p>
+ *
+ * @param prefix
+ * The prefix that was being mapping.
* @see #startPrefixMapping
* @see #endElement
*/
- public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException{}
+ public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException {
+ }
/**
* Receive notification of a skipped entity.
- *
- * <p>The Parser will invoke this method once for each entity
- * skipped. Non-validating processors may skip entities if they
- * have not seen the declarations (because, for example, the
- * entity was declared in an external DTD subset). All processors
- * may skip external entities, depending on the values of the
- * http://xml.org/sax/features/external-general-entities and the
- * http://xml.org/sax/features/external-parameter-entities
- * properties.</p>
- *
- * @param name The name of the skipped entity. If it is a
- * parameter entity, the name will begin with '%'.
+ *
+ * <p>
+ * The Parser will invoke this method once for each entity skipped.
+ * Non-validating processors may skip entities if they have not seen the
+ * declarations (because, for example, the entity was declared in an external
+ * DTD subset). All processors may skip external entities, depending on the
+ * values of the http://xml.org/sax/features/external-general-entities and the
+ * http://xml.org/sax/features/external-parameter-entities properties.
+ * </p>
+ *
+ * @param name
+ * The name of the skipped entity. If it is a parameter entity, the
+ * name will begin with '%'.
*/
- public void skippedEntity(String name) throws org.xml.sax.SAXException{}
-
+ public void skippedEntity(String name) throws org.xml.sax.SAXException {
+ }
+
public boolean isUpperCaseElementNames() {
- return upperCaseElementNames;
+ return upperCaseElementNames;
}
public void setUpperCaseElementNames(boolean upperCaseElementNames) {
- this.upperCaseElementNames = upperCaseElementNames;
+ this.upperCaseElementNames = upperCaseElementNames;
}
}
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
index 489a42e3c..ec9dafa87 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
@@ -34,35 +34,35 @@ import org.w3c.dom.NodeList;
/**
* A collection of methods for extracting content from DOM trees.
*
- * This class holds a few utility methods for pulling content out of
- * DOM nodes, such as getOutlinks, getText, etc.
- *
+ * This class holds a few utility methods for pulling content out of DOM nodes,
+ * such as getOutlinks, getText, etc.
+ *
*/
public class DOMContentUtils {
private static class LinkParams {
- private String elName;
- private String attrName;
- private int childLen;
-
- private LinkParams(String elName, String attrName, int childLen) {
- this.elName = elName;
- this.attrName = attrName;
- this.childLen = childLen;
- }
-
- public String toString() {
- return "LP[el=" + elName + ",attr=" + attrName + ",len=" + childLen + "]";
- }
+ private String elName;
+ private String attrName;
+ private int childLen;
+
+ private LinkParams(String elName, String attrName, int childLen) {
+ this.elName = elName;
+ this.attrName = attrName;
+ this.childLen = childLen;
+ }
+
+ public String toString() {
+ return "LP[el=" + elName + ",attr=" + attrName + ",len=" + childLen + "]";
+ }
}
-
- private HashMap<String,LinkParams> linkParams = new HashMap<String,LinkParams>();
+
+ private HashMap<String, LinkParams> linkParams = new HashMap<String, LinkParams>();
private Configuration conf;
-
+
public DOMContentUtils(Configuration conf) {
setConf(conf);
}
-
+
public void setConf(Configuration conf) {
// forceTags is used to override configurable tag ignoring, later on
Collection<String> forceTags = new ArrayList<String>(1);
@@ -84,59 +84,57 @@ public class DOMContentUtils {
// remove unwanted link tags from the linkParams map
String[] ignoreTags = conf.getStrings("parser.html.outlinks.ignore_tags");
- for ( int i = 0 ; ignoreTags != null && i < ignoreTags.length ; i++ ) {
- if ( ! forceTags.contains(ignoreTags[i]) )
+ for (int i = 0; ignoreTags != null && i < ignoreTags.length; i++) {
+ if (!forceTags.contains(ignoreTags[i]))
linkParams.remove(ignoreTags[i]);
}
}
-
+
/**
- * This method takes a {@link StringBuffer} and a DOM {@link Node},
- * and will append all the content text found beneath the DOM node to
- * the <code>StringBuffer</code>.
- *
+ * This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
+ * append all the content text found beneath the DOM node to the
+ * <code>StringBuffer</code>.
+ *
* <p>
- *
- * If <code>abortOnNestedAnchors</code> is true, DOM traversal will
- * be aborted and the <code>StringBuffer</code> will not contain
- * any text encountered after a nested anchor is found.
+ *
+ * If <code>abortOnNestedAnchors</code> is true, DOM traversal will be aborted
+ * and the <code>StringBuffer</code> will not contain any text encountered
+ * after a nested anchor is found.
*
* <p>
- *
+ *
* @return true if nested anchors were found
*/
- private boolean getText(StringBuffer sb, Node node,
- boolean abortOnNestedAnchors) {
+ private boolean getText(StringBuffer sb, Node node,
+ boolean abortOnNestedAnchors) {
if (getTextHelper(sb, node, abortOnNestedAnchors, 0)) {
return true;
- }
+ }
return false;
}
-
/**
- * This is a convinience method, equivalent to {@link
- * #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
+ * This is a convinience method, equivalent to
+ * {@link #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
*
*/
public void getText(StringBuffer sb, Node node) {
getText(sb, node, false);
}
- // returns true if abortOnNestedAnchors is true and we find nested
+ // returns true if abortOnNestedAnchors is true and we find nested
// anchors
- private boolean getTextHelper(StringBuffer sb, Node node,
- boolean abortOnNestedAnchors,
- int anchorDepth) {
+ private boolean getTextHelper(StringBuffer sb, Node node,
+ boolean abortOnNestedAnchors, int anchorDepth) {
boolean abort = false;
NodeWalker walker = new NodeWalker(node);
-
+
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
-
+
if ("script".equalsIgnoreCase(nodeName)) {
walker.skipChildren();
}
@@ -148,7 +146,7 @@ public class DOMContentUtils {
if (anchorDepth > 1) {
abort = true;
break;
- }
+ }
}
if (nodeType == Node.COMMENT_NODE) {
walker.skipChildren();
@@ -159,44 +157,45 @@ public class DOMContentUtils {
text = text.replaceAll("\\s+", " ");
text = text.trim();
if (text.length() > 0) {
- if (sb.length() > 0) sb.append(' ');
- sb.append(text);
+ if (sb.length() > 0)
+ sb.append(' ');
+ sb.append(text);
}
}
}
-
+
return abort;
}
/**
- * This method takes a {@link StringBuffer} and a DOM {@link Node},
- * and will append the content text found beneath the first
- * <code>title</code> node to the <code>StringBuffer</code>.
- *
+ * This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
+ * append the content text found beneath the first <code>title</code> node to
+ * the <code>StringBuffer</code>.
+ *
* @return true if a title node was found, false otherwise
*/
public boolean getTitle(StringBuffer sb, Node node) {
-
+
NodeWalker walker = new NodeWalker(node);
-
+
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
-
+
if ("body".equalsIgnoreCase(nodeName)) { // stop after HEAD
return false;
}
-
+
if (nodeType == Node.ELEMENT_NODE) {
if ("title".equalsIgnoreCase(nodeName)) {
getText(sb, currentNode);
return true;
}
}
- }
-
+ }
+
return false;
}
@@ -204,28 +203,29 @@ public class DOMContentUtils {
URL getBase(Node node) {
NodeWalker walker = new NodeWalker(node);
-
+
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
-
+
// is this node a BASE tag?
if (nodeType == Node.ELEMENT_NODE) {
-
+
if ("body".equalsIgnoreCase(nodeName)) { // stop after HEAD
return null;
}
-
+
if ("base".equalsIgnoreCase(nodeName)) {
NamedNodeMap attrs = currentNode.getAttributes();
- for (int i= 0; i < attrs.getLength(); i++ ) {
+ for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
if ("href".equalsIgnoreCase(attr.getNodeName())) {
try {
return new URL(attr.getNodeValue());
- } catch (MalformedURLException e) {}
+ } catch (MalformedURLException e) {
+ }
}
}
}
@@ -236,10 +236,9 @@ public class DOMContentUtils {
return null;
}
-
private boolean hasOnlyWhiteSpace(Node node) {
- String val= node.getNodeValue();
- for (int i= 0; i < val.length(); i++) {
+ String val = node.getNodeValue();
+ for (int i = 0; i < val.length(); i++) {
if (!Character.isWhitespace(val.charAt(i)))
return false;
}
@@ -248,50 +247,49 @@ public class DOMContentUtils {
// this only covers a few cases of empty links that are symptomatic
// of nekohtml's DOM-fixup process...
- private boolean shouldThrowAwayLink(Node node, NodeList children,
- int childLen, LinkParams params) {
+ private boolean shouldThrowAwayLink(Node node, NodeList children,
+ int childLen, LinkParams params) {
if (childLen == 0) {
- // this has no inner structure
- if (params.childLen == 0) return false;
- else return true;
- } else if ((childLen == 1)
- && (children.item(0).getNodeType() == Node.ELEMENT_NODE)
- && (params.elName.equalsIgnoreCase(children.item(0).getNodeName()))) {
+ // this has no inner structure
+ if (params.childLen == 0)
+ return false;
+ else
+ return true;
+ } else if ((childLen == 1)
+ && (children.item(0).getNodeType() == Node.ELEMENT_NODE)
+ && (params.elName.equalsIgnoreCase(children.item(0).getNodeName()))) {
// single nested link
return true;
} else if (childLen == 2) {
- Node c0= children.item(0);
- Node c1= children.item(1);
+ Node c0 = children.item(0);
+ Node c1 = children.item(1);
if ((c0.getNodeType() == Node.ELEMENT_NODE)
&& (params.elName.equalsIgnoreCase(c0.getNodeName()))
- && (c1.getNodeType() == Node.TEXT_NODE)
- && hasOnlyWhiteSpace(c1) ) {
+ && (c1.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c1)) {
// single link followed by whitespace node
return true;
}
if ((c1.getNodeType() == Node.ELEMENT_NODE)
&& (params.elName.equalsIgnoreCase(c1.getNodeName()))
- && (c0.getNodeType() == Node.TEXT_NODE)
- && hasOnlyWhiteSpace(c0) ) {
+ && (c0.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c0)) {
// whitespace node followed by single link
return true;
}
} else if (childLen == 3) {
- Node c0= children.item(0);
- Node c1= children.item(1);
- Node c2= children.item(2);
-
+ Node c0 = children.item(0);
+ Node c1 = children.item(1);
+ Node c2 = children.item(2);
+
if ((c1.getNodeType() == Node.ELEMENT_NODE)
&& (params.elName.equalsIgnoreCase(c1.getNodeName()))
- && (c0.getNodeType() == Node.TEXT_NODE)
- && (c2.getNodeType() == Node.TEXT_NODE)
- && hasOnlyWhiteSpace(c0)
- && hasOnlyWhiteSpace(c2) ) {
+ && (c0.getNodeType() == Node.TEXT_NODE)
+ && (c2.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c0)
+ && hasOnlyWhiteSpace(c2)) {
// single link surrounded by whitespace nodes
return true;
}
@@ -299,76 +297,73 @@ public class DOMContentUtils {
return false;
}
-
+
/**
- * This method finds all anchors below the supplied DOM
- * <code>node</code>, and creates appropriate {@link Outlink}
- * records for each (relative to the supplied <code>base</code>
- * URL), and adds them to the <code>outlinks</code> {@link
- * ArrayList}.
- *
+ * This method finds all anchors below the supplied DOM <code>node</code>, and
+ * creates appropriate {@link Outlink} records for each (relative to the
+ * supplied <code>base</code> URL), and adds them to the <code>outlinks</code>
+ * {@link ArrayList}.
+ *
* <p>
- *
- * Links without inner structure (tags, text, etc) are discarded, as
- * are links which contain only single nested links and empty text
- * nodes (this is a common DOM-fixup artifact, at least with
- * nekohtml).
+ *
+ * Links without inner structure (tags, text, etc) are discarded, as are links
+ * which contain only single nested links and empty text nodes (this is a
+ * common DOM-fixup artifact, at least with nekohtml).
*/
- public void getOutlinks(URL base, ArrayList<Outlink> outlinks,
- Node node) {
-
+ public void getOutlinks(URL base, ArrayList<Outlink> outlinks, Node node) {
+
NodeWalker walker = new NodeWalker(node);
while (walker.hasNext()) {
-
+
Node currentNode = walker.nextNode();
String nodeName = currentNode.getNodeName();
- short nodeType = currentNode.getNodeType();
+ short nodeType = currentNode.getNodeType();
NodeList children = currentNode.getChildNodes();
- int childLen = (children != null) ? children.getLength() : 0;
-
+ int childLen = (children != null) ? children.getLength() : 0;
+
if (nodeType == Node.ELEMENT_NODE) {
-
+
nodeName = nodeName.toLowerCase();
- LinkParams params = (LinkParams)linkParams.get(nodeName);
+ LinkParams params = (LinkParams) linkParams.get(nodeName);
if (params != null) {
if (!shouldThrowAwayLink(currentNode, children, childLen, params)) {
-
+
StringBuffer linkText = new StringBuffer();
getText(linkText, currentNode, true);
-
+
NamedNodeMap attrs = currentNode.getAttributes();
String target = null;
boolean noFollow = false;
boolean post = false;
- for (int i= 0; i < attrs.getLength(); i++ ) {
+ for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
String attrName = attr.getNodeName();
if (params.attrName.equalsIgnoreCase(attrName)) {
target = attr.getNodeValue();
- } else if ("rel".equalsIgnoreCase(attrName) &&
- "nofollow".equalsIgnoreCase(attr.getNodeValue())) {
+ } else if ("rel".equalsIgnoreCase(attrName)
+ && "nofollow".equalsIgnoreCase(attr.getNodeValue())) {
noFollow = true;
- } else if ("method".equalsIgnoreCase(attrName) &&
- "post".equalsIgnoreCase(attr.getNodeValue())) {
+ } else if ("method".equalsIgnoreCase(attrName)
+ && "post".equalsIgnoreCase(attr.getNodeValue())) {
post = true;
}
}
if (target != null && !noFollow && !post)
try {
-
+
URL url = URLUtil.resolveURL(base, target);
- outlinks.add(new Outlink(url.toString(),
- linkText.toString().trim()));
+ outlinks.add(new Outlink(url.toString(), linkText.toString()
+ .trim()));
} catch (MalformedURLException e) {
// don't care
}
}
// this should not have any children, skip them
- if (params.childLen == 0) continue;
+ if (params.childLen == 0)
+ continue;
}
}
}
}
}
-
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/HTMLMetaProcessor.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/HTMLMetaProcessor.java
index ac754ddf9..294bde96f 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/HTMLMetaProcessor.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/HTMLMetaProcessor.java
@@ -23,33 +23,32 @@ import org.apache.nutch.parse.HTMLMetaTags;
import org.w3c.dom.*;
/**
- * Class for parsing META Directives from DOM trees. This class
- * handles specifically Robots META directives (all, none, nofollow,
- * noindex), finding BASE HREF tags, and HTTP-EQUIV no-cache
- * instructions. All meta directives are stored in a HTMLMetaTags instance.
+ * Class for parsing META Directives from DOM trees. This class handles
+ * specifically Robots META directives (all, none, nofollow, noindex), finding
+ * BASE HREF tags, and HTTP-EQUIV no-cache instructions. All meta directives are
+ * stored in a HTMLMetaTags instance.
*/
public class HTMLMetaProcessor {
/**
- * Utility class with indicators for the robots directives "noindex"
- * and "nofollow", and HTTP-EQUIV/no-cache
+ * Utility class with indicators for the robots directives "noindex" and
+ * "nofollow", and HTTP-EQUIV/no-cache
*/
-
+
/**
- * Sets the indicators in <code>robotsMeta</code> to appropriate
- * values, based on any META tags found under the given
- * <code>node</code>.
+ * Sets the indicators in <code>robotsMeta</code> to appropriate values, based
+ * on any META tags found under the given <code>node</code>.
*/
- public static final void getMetaTags (
- HTMLMetaTags metaTags, Node node, URL currURL) {
+ public static final void getMetaTags(HTMLMetaTags metaTags, Node node,
+ URL currURL) {
metaTags.reset();
getMetaTagsHelper(metaTags, node, currURL);
}
- private static final void getMetaTagsHelper(
- HTMLMetaTags metaTags, Node node, URL currURL) {
-
+ private static final void getMetaTagsHelper(HTMLMetaTags metaTags, Node node,
+ URL currURL) {
+
if (node.getNodeType() == Node.ELEMENT_NODE) {
if ("body".equalsIgnoreCase(node.getNodeName())) {
@@ -63,7 +62,7 @@ public class HTMLMetaProcessor {
Node equivNode = null;
Node contentNode = null;
// Retrieves name, http-equiv and content attribues
- for (int i=0; i<attrs.getLength(); i++) {
+ for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
String attrName = attr.getNodeName().toLowerCase();
if (attrName.equals("name")) {
@@ -74,44 +73,43 @@ public class HTMLMetaProcessor {
contentNode = attr;
}
}
-
+
if (nameNode != null) {
if (contentNode != null) {
- String name = nameNode.getNodeValue().toLowerCase();
+ String name = nameNode.getNodeValue().toLowerCase();
metaTags.getGeneralTags().add(name, contentNode.getNodeValue());
if ("robots".equals(name)) {
-
+
if (contentNode != null) {
- String directives =
- contentNode.getNodeValue().toLowerCase();
+ String directives = contentNode.getNodeValue().toLowerCase();
int index = directives.indexOf("none");
-
+
if (index >= 0) {
metaTags.setNoIndex();
metaTags.setNoFollow();
}
-
+
index = directives.indexOf("all");
if (index >= 0) {
// do nothing...
}
-
+
index = directives.indexOf("noindex");
if (index >= 0) {
metaTags.setNoIndex();
}
-
+
index = directives.indexOf("nofollow");
if (index >= 0) {
metaTags.setNoFollow();
}
-
+
index = directives.indexOf("noarchive");
if (index >= 0) {
metaTags.setNoCache();
}
- }
-
+ }
+
} // end if (name == robots)
}
}
@@ -124,14 +122,15 @@ public class HTMLMetaProcessor {
if ("pragma".equals(name)) {
content = content.toLowerCase();
int index = content.indexOf("no-cache");
- if (index >= 0)
+ if (index >= 0)
metaTags.setNoCache();
} else if ("refresh".equals(name)) {
int idx = content.indexOf(';');
String time = null;
if (idx == -1) { // just the refresh time
time = content;
- } else time = content.substring(0, idx);
+ } else
+ time = content.substring(0, idx);
try {
metaTags.setRefreshTime(Integer.parseInt(time));
// skip this if we couldn't parse the time
@@ -142,9 +141,11 @@ public class HTMLMetaProcessor {
URL refreshUrl = null;
if (metaTags.getRefresh() && idx != -1) { // set the URL
idx = content.toLowerCase().indexOf("url=");
- if (idx == -1) { // assume a mis-formatted entry with just the url
+ if (idx == -1) { // assume a mis-formatted entry with just the
+ // url
idx = content.indexOf(';') + 1;
- } else idx += 4;
+ } else
+ idx += 4;
if (idx != -1) {
String url = content.substring(idx);
try {
@@ -187,13 +188,13 @@ public class HTMLMetaProcessor {
try {
if (currURL == null)
url = new URL(urlString);
- else
+ else
url = new URL(currURL, urlString);
} catch (Exception e) {
;
}
- if (url != null)
+ if (url != null)
metaTags.setBaseHref(url);
}
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
index 2bb834a53..83585cf67 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
@@ -53,203 +53,200 @@ import org.w3c.dom.DocumentFragment;
public class TikaParser implements org.apache.nutch.parse.Parser {
- public static final Logger LOG = LoggerFactory.getLogger(TikaParser.class);
-
- private Configuration conf;
- private TikaConfig tikaConfig = null;
- private DOMContentUtils utils;
- private HtmlParseFilters htmlParseFilters;
- private String cachingPolicy;
- private HtmlMapper HTMLMapper;
- private boolean upperCaseElementNames = true;
-
- @SuppressWarnings("deprecation")
- public ParseResult getParse(Content content) {
- String mimeType = content.getContentType();
-
- URL base;
- try {
- base = new URL(content.getBaseUrl());
- } catch (MalformedURLException e) {
- return new ParseStatus(e).getEmptyParseResult(content.getUrl(),
- getConf());
- }
-
- // get the right parser using the mime type as a clue
- Parser parser = tikaConfig.getParser(MediaType.parse(mimeType));
- byte[] raw = content.getContent();
-
- if (parser == null) {
- String message = "Can't retrieve Tika parser for mime-type "
- + mimeType;
- LOG.error(message);
- return new ParseStatus(ParseStatus.FAILED, message)
- .getEmptyParseResult(content.getUrl(), getConf());
- }
-
- LOG.debug("Using Tika parser " + parser.getClass().getName()
- + " for mime-type " + mimeType);
-
- Metadata tikamd = new Metadata();
-
- HTMLDocumentImpl doc = new HTMLDocumentImpl();
- doc.setErrorChecking(false);
- DocumentFragment root = doc.createDocumentFragment();
- DOMBuilder domhandler = new DOMBuilder(doc, root);
- domhandler.setUpperCaseElementNames(upperCaseElementNames);
- ParseContext context = new ParseContext();
- if (HTMLMapper != null)
- context.set(HtmlMapper.class, HTMLMapper);
- tikamd.set(Metadata.CONTENT_TYPE, mimeType);
- try {
- parser.parse(new ByteArrayInputStream(raw), domhandler, tikamd,
- context);
- } catch (Exception e) {
- LOG.error("Error parsing " + content.getUrl(), e);
- return new ParseStatus(ParseStatus.FAILED, e.getMessage())
- .getEmptyParseResult(content.getUrl(), getConf());
- }
-
- HTMLMetaTags metaTags = new HTMLMetaTags();
- String text = "";
- String title = "";
- Outlink[] outlinks = new Outlink[0];
- org.apache.nutch.metadata.Metadata nutchMetadata = new org.apache.nutch.metadata.Metadata();
-
- // we have converted the sax events generated by Tika into a DOM object
- // so we can now use the usual HTML resources from Nutch
- // get meta directives
- HTMLMetaProcessor.getMetaTags(metaTags, root, base);
- if (LOG.isTraceEnabled()) {
- LOG.trace("Meta tags for " + base + ": " + metaTags.toString());
- }
-
- // check meta directives
- if (!metaTags.getNoIndex()) { // okay to index
- StringBuffer sb = new StringBuffer();
- if (LOG.isTraceEnabled()) {
- LOG.trace("Getting text...");
- }
- utils.getText(sb, root); // extract text
- text = sb.toString();
- sb.setLength(0);
- if (LOG.isTraceEnabled()) {
- LOG.trace("Getting title...");
- }
- utils.getTitle(sb, root); // extract title
- title = sb.toString().trim();
- }
-
- if (!metaTags.getNoFollow()) { // okay to follow links
- ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks
- URL baseTag = utils.getBase(root);
- if (LOG.isTraceEnabled()) {
- LOG.trace("Getting links...");
- }
- utils.getOutlinks(baseTag != null ? baseTag : base, l, root);
- outlinks = l.toArray(new Outlink[l.size()]);
- if (LOG.isTraceEnabled()) {
- LOG.trace("found " + outlinks.length + " outlinks in "
- + content.getUrl());
- }
- }
-
- // populate Nutch metadata with Tika metadata
- String[] TikaMDNames = tikamd.names();
- for (String tikaMDName : TikaMDNames) {
- if (tikaMDName.equalsIgnoreCase(Metadata.TITLE))
- continue;
- // TODO what if multivalued?
- nutchMetadata.add(tikaMDName, tikamd.get(tikaMDName));
- }
-
- // no outlinks? try OutlinkExtractor e.g works for mime types where no
- // explicit markup for anchors
-
- if (outlinks.length == 0) {
- outlinks = OutlinkExtractor.getOutlinks(text, getConf());
- }
-
- ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);
- if (metaTags.getRefresh()) {
- status.setMinorCode(ParseStatus.SUCCESS_REDIRECT);
- status.setArgs(new String[] { metaTags.getRefreshHref().toString(),
- Integer.toString(metaTags.getRefreshTime()) });
- }
- ParseData parseData = new ParseData(status, title, outlinks,
- content.getMetadata(), nutchMetadata);
- ParseResult parseResult = ParseResult.createParseResult(
- content.getUrl(), new ParseImpl(text, parseData));
-
- // run filters on parse
- ParseResult filteredParse = this.htmlParseFilters.filter(content,
- parseResult, metaTags, root);
- if (metaTags.getNoCache()) { // not okay to cache
- for (Map.Entry<org.apache.hadoop.io.Text, Parse> entry : filteredParse)
- entry.getValue().getData().getParseMeta()
- .set(Nutch.CACHING_FORBIDDEN_KEY, cachingPolicy);
- }
- return filteredParse;
- }
-
- public void setConf(Configuration conf) {
- this.conf = conf;
- this.tikaConfig = null;
-
- // do we want a custom Tika configuration file
- // deprecated since Tika 0.7 which is based on
- // a service provider based configuration
- String customConfFile = conf.get("tika.config.file");
- if (customConfFile != null) {
- try {
- // see if a Tika config file can be found in the job file
- URL customTikaConfig = conf.getResource(customConfFile);
- if (customTikaConfig != null)
- tikaConfig = new TikaConfig(customTikaConfig);
- } catch (Exception e1) {
- String message = "Problem loading custom Tika configuration from "
- + customConfFile;
- LOG.error(message, e1);
- }
- } else {
- try {
- tikaConfig = new TikaConfig(this.getClass().getClassLoader());
- } catch (Exception e2) {
- String message = "Problem loading default Tika configuration";
- LOG.error(message, e2);
- }
- }
-
- // use a custom htmlmapper
- String htmlmapperClassName = conf.get("tika.htmlmapper.classname");
- if (StringUtils.isNotBlank(htmlmapperClassName)) {
- try {
- Class HTMLMapperClass = Class.forName(htmlmapperClassName);
- boolean interfaceOK = HtmlMapper.class
- .isAssignableFrom(HTMLMapperClass);
- if (!interfaceOK) {
- throw new RuntimeException("Class " + htmlmapperClassName
- + " does not implement HtmlMapper");
- }
- HTMLMapper = (HtmlMapper) HTMLMapperClass.newInstance();
- } catch (Exception e) {
- LOG.error("Can't generate instance for class "
- + htmlmapperClassName);
- throw new RuntimeException("Can't generate instance for class "
- + htmlmapperClassName);
- }
- }
-
- this.htmlParseFilters = new HtmlParseFilters(getConf());
- this.utils = new DOMContentUtils(conf);
- this.cachingPolicy = getConf().get("parser.caching.forbidden.policy",
- Nutch.CACHING_FORBIDDEN_CONTENT);
- this.upperCaseElementNames = getConf().getBoolean(
- "tika.uppercase.element.names", true);
- }
-
- public Configuration getConf() {
- return this.conf;
- }
+ public static final Logger LOG = LoggerFactory.getLogger(TikaParser.class);
+
+ private Configuration conf;
+ private TikaConfig tikaConfig = null;
+ private DOMContentUtils utils;
+ private HtmlParseFilters htmlParseFilters;
+ private String cachingPolicy;
+ private HtmlMapper HTMLMapper;
+ private boolean upperCaseElementNames = true;
+
+ @SuppressWarnings("deprecation")
+ public ParseResult getParse(Content content) {
+ String mimeType = content.getContentType();
+
+ URL base;
+ try {
+ base = new URL(content.getBaseUrl());
+ } catch (MalformedURLException e) {
+ return new ParseStatus(e)
+ .getEmptyParseResult(content.getUrl(), getConf());
+ }
+
+ // get the right parser using the mime type as a clue
+ Parser parser = tikaConfig.getParser(MediaType.parse(mimeType));
+ byte[] raw = content.getContent();
+
+ if (parser == null) {
+ String message = "Can't retrieve Tika parser for mime-type " + mimeType;
+ LOG.error(message);
+ return new ParseStatus(ParseStatus.FAILED, message).getEmptyParseResult(
+ content.getUrl(), getConf());
+ }
+
+ LOG.debug("Using Tika parser " + parser.getClass().getName()
+ + " for mime-type " + mimeType);
+
+ Metadata tikamd = new Metadata();
+
+ HTMLDocumentImpl doc = new HTMLDocumentImpl();
+ doc.setErrorChecking(false);
+ DocumentFragment root = doc.createDocumentFragment();
+ DOMBuilder domhandler = new DOMBuilder(doc, root);
+ domhandler.setUpperCaseElementNames(upperCaseElementNames);
+ ParseContext context = new ParseContext();
+ if (HTMLMapper != null)
+ context.set(HtmlMapper.class, HTMLMapper);
+ tikamd.set(Metadata.CONTENT_TYPE, mimeType);
+ try {
+ parser.parse(new ByteArrayInputStream(raw), domhandler, tikamd, context);
+ } catch (Exception e) {
+ LOG.error("Error parsing " + content.getUrl(), e);
+ return new ParseStatus(ParseStatus.FAILED, e.getMessage())
+ .getEmptyParseResult(content.getUrl(), getConf());
+ }
+
+ HTMLMetaTags metaTags = new HTMLMetaTags();
+ String text = "";
+ String title = "";
+ Outlink[] outlinks = new Outlink[0];
+ org.apache.nutch.metadata.Metadata nutchMetadata = new org.apache.nutch.metadata.Metadata();
+
+ // we have converted the sax events generated by Tika into a DOM object
+ // so we can now use the usual HTML resources from Nutch
+ // get meta directives
+ HTMLMetaProcessor.getMetaTags(metaTags, root, base);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Meta tags for " + base + ": " + metaTags.toString());
+ }
+
+ // check meta directives
+ if (!metaTags.getNoIndex()) { // okay to index
+ StringBuffer sb = new StringBuffer();
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Getting text...");
+ }
+ utils.getText(sb, root); // extract text
+ text = sb.toString();
+ sb.setLength(0);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Getting title...");
+ }
+ utils.getTitle(sb, root); // extract title
+ title = sb.toString().trim();
+ }
+
+ if (!metaTags.getNoFollow()) { // okay to follow links
+ ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks
+ URL baseTag = utils.getBase(root);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Getting links...");
+ }
+ utils.getOutlinks(baseTag != null ? baseTag : base, l, root);
+ outlinks = l.toArray(new Outlink[l.size()]);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("found " + outlinks.length + " outlinks in "
+ + content.getUrl());
+ }
+ }
+
+ // populate Nutch metadata with Tika metadata
+ String[] TikaMDNames = tikamd.names();
+ for (String tikaMDName : TikaMDNames) {
+ if (tikaMDName.equalsIgnoreCase(Metadata.TITLE))
+ continue;
+ // TODO what if multivalued?
+ nutchMetadata.add(tikaMDName, tikamd.get(tikaMDName));
+ }
+
+ // no outlinks? try OutlinkExtractor e.g works for mime types where no
+ // explicit markup for anchors
+
+ if (outlinks.length == 0) {
+ outlinks = OutlinkExtractor.getOutlinks(text, getConf());
+ }
+
+ ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);
+ if (metaTags.getRefresh()) {
+ status.setMinorCode(ParseStatus.SUCCESS_REDIRECT);
+ status.setArgs(new String[] { metaTags.getRefreshHref().toString(),
+ Integer.toString(metaTags.getRefreshTime()) });
+ }
+ ParseData parseData = new ParseData(status, title, outlinks,
+ content.getMetadata(), nutchMetadata);
+ ParseResult parseResult = ParseResult.createParseResult(content.getUrl(),
+ new ParseImpl(text, parseData));
+
+ // run filters on parse
+ ParseResult filteredParse = this.htmlParseFilters.filter(content,
+ parseResult, metaTags, root);
+ if (metaTags.getNoCache()) { // not okay to cache
+ for (Map.Entry<org.apache.hadoop.io.Text, Parse> entry : filteredParse)
+ entry.getValue().getData().getParseMeta()
+ .set(Nutch.CACHING_FORBIDDEN_KEY, cachingPolicy);
+ }
+ return filteredParse;
+ }
+
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ this.tikaConfig = null;
+
+ // do we want a custom Tika configuration file
+ // deprecated since Tika 0.7 which is based on
+ // a service provider based configuration
+ String customConfFile = conf.get("tika.config.file");
+ if (customConfFile != null) {
+ try {
+ // see if a Tika config file can be found in the job file
+ URL customTikaConfig = conf.getResource(customConfFile);
+ if (customTikaConfig != null)
+ tikaConfig = new TikaConfig(customTikaConfig);
+ } catch (Exception e1) {
+ String message = "Problem loading custom Tika configuration from "
+ + customConfFile;
+ LOG.error(message, e1);
+ }
+ } else {
+ try {
+ tikaConfig = new TikaConfig(this.getClass().getClassLoader());
+ } catch (Exception e2) {
+ String message = "Problem loading default Tika configuration";
+ LOG.error(message, e2);
+ }
+ }
+
+ // use a custom htmlmapper
+ String htmlmapperClassName = conf.get("tika.htmlmapper.classname");
+ if (StringUtils.isNotBlank(htmlmapperClassName)) {
+ try {
+ Class HTMLMapperClass = Class.forName(htmlmapperClassName);
+ boolean interfaceOK = HtmlMapper.class
+ .isAssignableFrom(HTMLMapperClass);
+ if (!interfaceOK) {
+ throw new RuntimeException("Class " + htmlmapperClassName
+ + " does not implement HtmlMapper");
+ }
+ HTMLMapper = (HtmlMapper) HTMLMapperClass.newInstance();
+ } catch (Exception e) {
+ LOG.error("Can't generate instance for class " + htmlmapperClassName);
+ throw new RuntimeException("Can't generate instance for class "
+ + htmlmapperClassName);
+ }
+ }
+
+ this.htmlParseFilters = new HtmlParseFilters(getConf());
+ this.utils = new DOMContentUtils(conf);
+ this.cachingPolicy = getConf().get("parser.caching.forbidden.policy",
+ Nutch.CACHING_FORBIDDEN_CONTENT);
+ this.upperCaseElementNames = getConf().getBoolean(
+ "tika.uppercase.element.names", true);
+ }
+
+ public Configuration getConf() {
+ return this.conf;
+ }
}
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/XMLCharacterRecognizer.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/XMLCharacterRecognizer.java
index b68106761..d625c3311 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/XMLCharacterRecognizer.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/XMLCharacterRecognizer.java
@@ -26,40 +26,42 @@
package org.apache.nutch.parse.tika;
/**
- * Class used to verify whether the specified <var>ch</var>
- * conforms to the XML 1.0 definition of whitespace.
+ * Class used to verify whether the specified <var>ch</var> conforms to the XML
+ * 1.0 definition of whitespace.
*/
-class XMLCharacterRecognizer
-{
+class XMLCharacterRecognizer {
/**
- * Returns whether the specified <var>ch</var> conforms to the XML 1.0 definition
- * of whitespace. Refer to <A href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S">
- * the definition of <CODE>S</CODE></A> for details.
- * @param ch Character to check as XML whitespace.
+ * Returns whether the specified <var>ch</var> conforms to the XML 1.0
+ * definition of whitespace. Refer to <A
+ * href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S"> the definition of
+ * <CODE>S</CODE></A> for details.
+ *
+ * @param ch
+ * Character to check as XML whitespace.
* @return =true if <var>ch</var> is XML whitespace; otherwise =false.
*/
- static boolean isWhiteSpace(char ch)
- {
+ static boolean isWhiteSpace(char ch) {
return (ch == 0x20) || (ch == 0x09) || (ch == 0xD) || (ch == 0xA);
}
/**
* Tell if the string is whitespace.
- *
- * @param ch Character array to check as XML whitespace.
- * @param start Start index of characters in the array
- * @param length Number of characters in the array
- * @return True if the characters in the array are
- * XML whitespace; otherwise, false.
+ *
+ * @param ch
+ * Character array to check as XML whitespace.
+ * @param start
+ * Start index of characters in the array
+ * @param length
+ * Number of characters in the array
+ * @return True if the characters in the array are XML whitespace; otherwise,
+ * false.
*/
- static boolean isWhiteSpace(char ch[], int start, int length)
- {
+ static boolean isWhiteSpace(char ch[], int start, int length) {
int end = start + length;
- for (int s = start; s < end; s++)
- {
+ for (int s = start; s < end; s++) {
if (!isWhiteSpace(ch[s]))
return false;
}
@@ -69,39 +71,36 @@ class XMLCharacterRecognizer
/**
* Tell if the string is whitespace.
- *
- * @param buf StringBuffer to check as XML whitespace.
+ *
+ * @param buf
+ * StringBuffer to check as XML whitespace.
* @return True if characters in buffer are XML whitespace, false otherwise
*/
- static boolean isWhiteSpace(StringBuffer buf)
- {
+ static boolean isWhiteSpace(StringBuffer buf) {
int n = buf.length();
- for (int i = 0; i < n; i++)
- {
+ for (int i = 0; i < n; i++) {
if (!isWhiteSpace(buf.charAt(i)))
return false;
}
return true;
}
-
+
/**
* Tell if the string is whitespace.
- *
- * @param s String to check as XML whitespace.
+ *
+ * @param s
+ * String to check as XML whitespace.
* @return True if characters in buffer are XML whitespace, false otherwise
*/
- static boolean isWhiteSpace(String s)
- {
+ static boolean isWhiteSpace(String s) {
- if(null != s)
- {
+ if (null != s) {
int n = s.length();
-
- for (int i = 0; i < n; i++)
- {
+
+ for (int i = 0; i < n; i++) {
if (!isWhiteSpace(s.charAt(i)))
return false;
}
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/package-info.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/package-info.java
index 25ebc164a..19e3f4728 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/package-info.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/package-info.java
@@ -20,3 +20,4 @@
* <a href="http://tika.apache.org/">Apache Tika</a>.
*/
package org.apache.nutch.parse.tika;
+
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java
index 611796dfd..96029a6b4 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java
@@ -42,129 +42,129 @@ public class TestDOMContentUtils {
private static final String[] testPages = {
- new String("<html><head><title> title </title><script> script </script>"
- + "</head><body> body <a href=\"http://www.nutch.org\">"
- + " anchor </a><!--comment-->" + "</body></html>"),
-
- new String("<html><head><title> title </title><script> script </script>"
- + "</head><body> body <a href=\"/\">" + " home </a><!--comment-->"
- + "<style> style </style>" + " <a href=\"bot.html\">" + " bots </a>"
- + "</body></html>"),
-
- new String("<html><head><title> </title>" + "</head><body> "
- + "<a href=\"/\"> separate this " + "<a href=\"ok\"> from this"
- + "</a></a>" + "</body></html>"),
-
- // this one relies on certain neko fixup behavior, possibly
- // distributing the anchors into the LI's-but not the other
- // anchors (outside of them, instead)! So you get a tree that
- // looks like:
- // ... <li> <a href=/> home </a> </li>
- // <li> <a href=/> <a href="1"> 1 </a> </a> </li>
- // <li> <a href=/> <a href="1"> <a href="2"> 2 </a> </a> </a> </li>
- new String("<html><head><title> my title </title>"
- + "</head><body> body " + "<ul>" + "<li> <a href=\"/\"> home"
- + "<li> <a href=\"1\"> 1" + "<li> <a href=\"2\"> 2" + "</ul>"
- + "</body></html>"),
-
- // test frameset link extraction. The invalid frame in the middle
- // will be
- // fixed to a third standalone frame.
- new String("<html><head><title> my title </title>"
- + "</head><frameset rows=\"20,*\"> " + "<frame src=\"top.html\">"
- + "</frame>" + "<frameset cols=\"20,*\">"
- + "<frame src=\"left.html\">" + "<frame src=\"invalid.html\"/>"
- + "</frame>" + "<frame src=\"right.html\">" + "</frame>"
- + "</frameset>" + "</frameset>" + "</body></html>"),
-
- // test <area> and <iframe> link extraction + url normalization
- new String(
- "<html><head><title> my title </title>"
- + "</head><body>"
- + "<img src=\"logo.gif\" usemap=\"#green\" border=\"0\">"
- + "<map name=\"green\">"
- + "<area shape=\"polygon\" coords=\"19,44,45,11,87\" href=\"../index.html\">"
- + "<area shape=\"rect\" coords=\"128,132,241,179\" href=\"#bottom\">"
- + "<area shape=\"circle\" coords=\"68,211,35\" href=\"../bot.html\">"
- + "</map>" + "<a name=\"bottom\"/><h1> the bottom </h1> "
- + "<iframe src=\"../docs/index.html\"/>" + "</body></html>"),
-
- // test whitespace processing for plain text extraction
- new String(
- "<html><head>\n <title> my\t\n title\r\n </title>\n"
- + " </head>\n"
- + " <body>\n"
- + " <h1> Whitespace\ttest </h1> \n"
- + "\t<a href=\"../index.html\">\n \twhitespace test\r\n\t</a> \t\n"
- + " <p> This is<span> a whitespace<span></span> test</span>. Newlines\n"
- + "should appear as space too.</p><p>Tabs\tare spaces too.\n</p>"
- + " This\t<b>is a</b> break -&gt;<br>and the line after<i> break</i>.<br>\n"
- + "<table>"
- + " <tr><td>one</td><td>two</td><td>three</td></tr>\n"
- + " <tr><td>space here </td><td> space there</td><td>no space</td></tr>"
- + "\t<tr><td>one\r\ntwo</td><td>two\tthree</td><td>three\r\tfour</td></tr>\n"
- + "</table>put some text here<Br>and there."
- + "<h2>End\tthis\rmadness\n!</h2>\r\n"
- + " . . . ." + "</body> </html>"),
-
- // test that <a rel=nofollow> links are not returned
- new String("<html><head></head><body>"
- + "<a href=\"http://www.nutch.org\" rel=\"nofollow\"> ignore </a>"
- + "<a rel=\"nofollow\" href=\"http://www.nutch.org\"> ignore </a>"
- + "</body></html>"),
- // test that POST form actions are skipped
- new String("<html><head></head><body>"
- + "<form method='POST' action='/search.jsp'><input type=text>"
- + "<input type=submit><p>test1</p></form>"
- + "<form method='GET' action='/dummy.jsp'><input type=text>"
- + "<input type=submit><p>test2</p></form></body></html>"),
- // test that all form actions are skipped
- new String("<html><head></head><body>"
- + "<form method='POST' action='/search.jsp'><input type=text>"
- + "<input type=submit><p>test1</p></form>"
- + "<form method='GET' action='/dummy.jsp'><input type=text>"
- + "<input type=submit><p>test2</p></form></body></html>"),
- new String("<html><head><title> title </title>" + "</head><body>"
- + "<a href=\";x\">anchor1</a>" + "<a href=\"g;x\">anchor2</a>"
- + "<a href=\"g;x?y#s\">anchor3</a>" + "</body></html>"),
- new String("<html><head><title> title </title>" + "</head><body>"
- + "<a href=\"g\">anchor1</a>" + "<a href=\"g?y#s\">anchor2</a>"
- + "<a href=\"?y=1\">anchor3</a>" + "<a href=\"?y=1#s\">anchor4</a>"
- + "<a href=\"?y=1;somethingelse\">anchor5</a>" + "</body></html>"), };
+ new String("<html><head><title> title </title><script> script </script>"
+ + "</head><body> body <a href=\"http://www.nutch.org\">"
+ + " anchor </a><!--comment-->" + "</body></html>"),
+
+ new String("<html><head><title> title </title><script> script </script>"
+ + "</head><body> body <a href=\"/\">" + " home </a><!--comment-->"
+ + "<style> style </style>" + " <a href=\"bot.html\">" + " bots </a>"
+ + "</body></html>"),
+
+ new String("<html><head><title> </title>" + "</head><body> "
+ + "<a href=\"/\"> separate this " + "<a href=\"ok\"> from this"
+ + "</a></a>" + "</body></html>"),
+
+ // this one relies on certain neko fixup behavior, possibly
+ // distributing the anchors into the LI's-but not the other
+ // anchors (outside of them, instead)! So you get a tree that
+ // looks like:
+ // ... <li> <a href=/> home </a> </li>
+ // <li> <a href=/> <a href="1"> 1 </a> </a> </li>
+ // <li> <a href=/> <a href="1"> <a href="2"> 2 </a> </a> </a> </li>
+ new String("<html><head><title> my title </title>"
+ + "</head><body> body " + "<ul>" + "<li> <a href=\"/\"> home"
+ + "<li> <a href=\"1\"> 1" + "<li> <a href=\"2\"> 2" + "</ul>"
+ + "</body></html>"),
+
+ // test frameset link extraction. The invalid frame in the middle
+ // will be
+ // fixed to a third standalone frame.
+ new String("<html><head><title> my title </title>"
+ + "</head><frameset rows=\"20,*\"> " + "<frame src=\"top.html\">"
+ + "</frame>" + "<frameset cols=\"20,*\">"
+ + "<frame src=\"left.html\">" + "<frame src=\"invalid.html\"/>"
+ + "</frame>" + "<frame src=\"right.html\">" + "</frame>"
+ + "</frameset>" + "</frameset>" + "</body></html>"),
+
+ // test <area> and <iframe> link extraction + url normalization
+ new String(
+ "<html><head><title> my title </title>"
+ + "</head><body>"
+ + "<img src=\"logo.gif\" usemap=\"#green\" border=\"0\">"
+ + "<map name=\"green\">"
+ + "<area shape=\"polygon\" coords=\"19,44,45,11,87\" href=\"../index.html\">"
+ + "<area shape=\"rect\" coords=\"128,132,241,179\" href=\"#bottom\">"
+ + "<area shape=\"circle\" coords=\"68,211,35\" href=\"../bot.html\">"
+ + "</map>" + "<a name=\"bottom\"/><h1> the bottom </h1> "
+ + "<iframe src=\"../docs/index.html\"/>" + "</body></html>"),
+
+ // test whitespace processing for plain text extraction
+ new String(
+ "<html><head>\n <title> my\t\n title\r\n </title>\n"
+ + " </head>\n"
+ + " <body>\n"
+ + " <h1> Whitespace\ttest </h1> \n"
+ + "\t<a href=\"../index.html\">\n \twhitespace test\r\n\t</a> \t\n"
+ + " <p> This is<span> a whitespace<span></span> test</span>. Newlines\n"
+ + "should appear as space too.</p><p>Tabs\tare spaces too.\n</p>"
+ + " This\t<b>is a</b> break -&gt;<br>and the line after<i> break</i>.<br>\n"
+ + "<table>"
+ + " <tr><td>one</td><td>two</td><td>three</td></tr>\n"
+ + " <tr><td>space here </td><td> space there</td><td>no space</td></tr>"
+ + "\t<tr><td>one\r\ntwo</td><td>two\tthree</td><td>three\r\tfour</td></tr>\n"
+ + "</table>put some text here<Br>and there."
+ + "<h2>End\tthis\rmadness\n!</h2>\r\n"
+ + " . . . ." + "</body> </html>"),
+
+ // test that <a rel=nofollow> links are not returned
+ new String("<html><head></head><body>"
+ + "<a href=\"http://www.nutch.org\" rel=\"nofollow\"> ignore </a>"
+ + "<a rel=\"nofollow\" href=\"http://www.nutch.org\"> ignore </a>"
+ + "</body></html>"),
+ // test that POST form actions are skipped
+ new String("<html><head></head><body>"
+ + "<form method='POST' action='/search.jsp'><input type=text>"
+ + "<input type=submit><p>test1</p></form>"
+ + "<form method='GET' action='/dummy.jsp'><input type=text>"
+ + "<input type=submit><p>test2</p></form></body></html>"),
+ // test that all form actions are skipped
+ new String("<html><head></head><body>"
+ + "<form method='POST' action='/search.jsp'><input type=text>"
+ + "<input type=submit><p>test1</p></form>"
+ + "<form method='GET' action='/dummy.jsp'><input type=text>"
+ + "<input type=submit><p>test2</p></form></body></html>"),
+ new String("<html><head><title> title </title>" + "</head><body>"
+ + "<a href=\";x\">anchor1</a>" + "<a href=\"g;x\">anchor2</a>"
+ + "<a href=\"g;x?y#s\">anchor3</a>" + "</body></html>"),
+ new String("<html><head><title> title </title>" + "</head><body>"
+ + "<a href=\"g\">anchor1</a>" + "<a href=\"g?y#s\">anchor2</a>"
+ + "<a href=\"?y=1\">anchor3</a>" + "<a href=\"?y=1#s\">anchor4</a>"
+ + "<a href=\"?y=1;somethingelse\">anchor5</a>" + "</body></html>"), };
private static int SKIP = 9;
private static String[] testBaseHrefs = { "http://www.nutch.org",
- "http://www.nutch.org/docs/foo.html", "http://www.nutch.org/docs/",
- "http://www.nutch.org/docs/", "http://www.nutch.org/frames/",
- "http://www.nutch.org/maps/", "http://www.nutch.org/whitespace/",
- "http://www.nutch.org//", "http://www.nutch.org/",
- "http://www.nutch.org/", "http://www.nutch.org/",
- "http://www.nutch.org/;something" };
+ "http://www.nutch.org/docs/foo.html", "http://www.nutch.org/docs/",
+ "http://www.nutch.org/docs/", "http://www.nutch.org/frames/",
+ "http://www.nutch.org/maps/", "http://www.nutch.org/whitespace/",
+ "http://www.nutch.org//", "http://www.nutch.org/",
+ "http://www.nutch.org/", "http://www.nutch.org/",
+ "http://www.nutch.org/;something" };
private static final DocumentFragment testDOMs[] = new DocumentFragment[testPages.length];
private static URL[] testBaseHrefURLs = new URL[testPages.length];
private static final String[] answerText = {
- "title body anchor",
- "title body home bots",
- "separate this from this",
- "my title body home 1 2",
- "my title",
- "my title the bottom",
- "my title Whitespace test whitespace test "
- + "This is a whitespace test . Newlines should appear as space too. "
- + "Tabs are spaces too. This is a break -> and the line after break . "
- + "one two three space here space there no space "
- + "one two two three three four put some text here and there. "
- + "End this madness ! . . . .", "ignore ignore", "test1 test2",
- "test1 test2", "title anchor1 anchor2 anchor3",
- "title anchor1 anchor2 anchor3 anchor4 anchor5" };
+ "title body anchor",
+ "title body home bots",
+ "separate this from this",
+ "my title body home 1 2",
+ "my title",
+ "my title the bottom",
+ "my title Whitespace test whitespace test "
+ + "This is a whitespace test . Newlines should appear as space too. "
+ + "Tabs are spaces too. This is a break -> and the line after break . "
+ + "one two three space here space there no space "
+ + "one two two three three four put some text here and there. "
+ + "End this madness ! . . . .", "ignore ignore", "test1 test2",
+ "test1 test2", "title anchor1 anchor2 anchor3",
+ "title anchor1 anchor2 anchor3 anchor4 anchor5" };
private static final String[] answerTitle = { "title", "title", "",
- "my title", "my title", "my title", "my title", "", "", "", "title",
- "title" };
+ "my title", "my title", "my title", "my title", "", "", "", "title",
+ "title" };
// note: should be in page-order
private static Outlink[][] answerOutlinks;
@@ -196,36 +196,36 @@ public class TestDOMContentUtils {
answerOutlinks = new Outlink[][] {
{ new Outlink("http://www.nutch.org", "anchor"), },
{ new Outlink("http://www.nutch.org/", "home"),
- new Outlink("http://www.nutch.org/docs/bot.html", "bots"), },
- { new Outlink("http://www.nutch.org/", "separate this"),
+ new Outlink("http://www.nutch.org/docs/bot.html", "bots"), },
+ { new Outlink("http://www.nutch.org/", "separate this"),
new Outlink("http://www.nutch.org/docs/ok", "from this"), },
- { 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/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/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/index.html", "whitespace test"), },
- {},
- { new Outlink("http://www.nutch.org/dummy.jsp", "test2"), },
- {},
- { new Outlink("http://www.nutch.org/;x", "anchor1"),
- new Outlink("http://www.nutch.org/g;x", "anchor2"),
- new Outlink("http://www.nutch.org/g;x?y#s", "anchor3") },
- {
- // this is tricky - see RFC3986 section 5.4.1 example 7
- new Outlink("http://www.nutch.org/g", "anchor1"),
- new Outlink("http://www.nutch.org/g?y#s", "anchor2"),
- new Outlink("http://www.nutch.org/;something?y=1", "anchor3"),
- new Outlink("http://www.nutch.org/;something?y=1#s", "anchor4"),
- new Outlink("http://www.nutch.org/;something?y=1;somethingelse",
- "anchor5") } };
+ { 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/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/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/index.html", "whitespace test"), },
+ {},
+ { new Outlink("http://www.nutch.org/dummy.jsp", "test2"), },
+ {},
+ { new Outlink("http://www.nutch.org/;x", "anchor1"),
+ new Outlink("http://www.nutch.org/g;x", "anchor2"),
+ new Outlink("http://www.nutch.org/g;x?y#s", "anchor3") },
+ {
+ // this is tricky - see RFC3986 section 5.4.1 example 7
+ new Outlink("http://www.nutch.org/g", "anchor1"),
+ new Outlink("http://www.nutch.org/g?y#s", "anchor2"),
+ new Outlink("http://www.nutch.org/;something?y=1", "anchor3"),
+ new Outlink("http://www.nutch.org/;something?y=1#s", "anchor4"),
+ new Outlink("http://www.nutch.org/;something?y=1;somethingelse",
+ "anchor5") } };
}
@@ -256,7 +256,7 @@ public class TestDOMContentUtils {
"expecting text: " + answerText[i]
+ System.getProperty("line.separator")
+ System.getProperty("line.separator") + "got text: " + text,
- equalsIgnoreWhitespace(answerText[i], text));
+ equalsIgnoreWhitespace(answerText[i], text));
}
}
@@ -272,7 +272,7 @@ public class TestDOMContentUtils {
"expecting text: " + answerText[i]
+ System.getProperty("line.separator")
+ System.getProperty("line.separator") + "got text: " + text,
- equalsIgnoreWhitespace(answerTitle[i], text));
+ equalsIgnoreWhitespace(answerTitle[i], text));
}
}
@@ -318,19 +318,19 @@ public class TestDOMContentUtils {
+ outlinksString(o1) + System.getProperty("line.separator")
+ "got: " + System.getProperty("line.separator")
+ outlinksString(o2) + System.getProperty("line.separator"),
- false);
+ false);
}
for (int i = 0; i < o1.length; i++) {
if (!o1[i].equals(o2[i])) {
Assert.assertTrue(
"got wrong outlinks at position " + i
- + System.getProperty("line.separator") + "answer: "
- + System.getProperty("line.separator") + "'" + o1[i].getToUrl()
- + "', anchor: '" + o1[i].getAnchor() + "'"
- + System.getProperty("line.separator") + "got: "
- + System.getProperty("line.separator") + "'" + o2[i].getToUrl()
- + "', anchor: '" + o2[i].getAnchor() + "'", false);
+ + System.getProperty("line.separator") + "answer: "
+ + System.getProperty("line.separator") + "'" + o1[i].getToUrl()
+ + "', anchor: '" + o1[i].getAnchor() + "'"
+ + System.getProperty("line.separator") + "got: "
+ + System.getProperty("line.separator") + "'" + o2[i].getToUrl()
+ + "', anchor: '" + o2[i].getAnchor() + "'", false);
}
}
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestFeedParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestFeedParser.java
index 6b9f6a11e..c9394dc0f 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestFeedParser.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestFeedParser.java
@@ -80,8 +80,8 @@ public class TestFeedParser {
protocol = new ProtocolFactory(conf).getProtocol(urlString);
content = protocol.getProtocolOutput(new Text(urlString),
new CrawlDatum()).getContent();
- parse = new ParseUtil(conf).parseByExtensionId("parse-tika",
- content).get(content.getUrl());
+ parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content)
+ .get(content.getUrl());
// check that there are 2 outlinks:
// unlike the original parse-rss
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestImageMetadata.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestImageMetadata.java
index 0df7083b1..b1762e603 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestImageMetadata.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestImageMetadata.java
@@ -31,18 +31,16 @@ import org.apache.nutch.crawl.CrawlDatum;
import org.junit.Assert;
import org.junit.Test;
-/**
+/**
* Test extraction of image metadata
*/
public class TestImageMetadata {
private String fileSeparator = System.getProperty("file.separator");
// This system property is defined in ./src/plugin/build-plugin.xml
- private String sampleDir = System.getProperty("test.data",".");
+ private String sampleDir = System.getProperty("test.data", ".");
// Make sure sample files are copied to "test.data" as specified in
- private String[] sampleFiles = {
- "nutch_logo_tm.gif",
- };
+ private String[] sampleFiles = { "nutch_logo_tm.gif", };
@Test
public void testIt() throws ProtocolException, ParseException {
@@ -56,8 +54,10 @@ public class TestImageMetadata {
Configuration conf = NutchConfiguration.create();
protocol = new ProtocolFactory(conf).getProtocol(urlString);
- content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
- parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content).get(content.getUrl());
+ content = protocol.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
+ parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content)
+ .get(content.getUrl());
Assert.assertEquals("121", parse.getData().getMeta("width"));
Assert.assertEquals("48", parse.getData().getMeta("height"));
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestMSWordParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestMSWordParser.java
index 90f1309ae..576b3dfdd 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestMSWordParser.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestMSWordParser.java
@@ -34,20 +34,20 @@ import org.junit.Test;
import java.io.File;
-/**
+/**
* Unit tests for MSWordParser.
- *
+ *
* @author John Xing
*/
public class TestMSWordParser {
private String fileSeparator = System.getProperty("file.separator");
// This system property is defined in ./src/plugin/build-plugin.xml
- private String sampleDir = System.getProperty("test.data",".");
+ private String sampleDir = System.getProperty("test.data", ".");
// Make sure sample files are copied to "test.data" as specified in
// ./src/plugin/parse-msword/build.xml during plugin compilation.
// Check ./src/plugin/parse-msword/sample/README.txt for what they are.
- private String[] sampleFiles = {"word97.doc"};
+ private String[] sampleFiles = { "word97.doc" };
private String expectedText = "This is a sample doc file prepared for nutch.";
@@ -59,19 +59,23 @@ public class TestMSWordParser {
conf.set("file.content.limit", "-1");
}
- public String getTextContent(String fileName) throws ProtocolException, ParseException {
+ public String getTextContent(String fileName) throws ProtocolException,
+ ParseException {
String urlString = "file:" + sampleDir + fileSeparator + fileName;
Protocol protocol = new ProtocolFactory(conf).getProtocol(urlString);
- Content content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
- Parse parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content).get(content.getUrl());
+ Content content = protocol.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
+ Parse parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content)
+ .get(content.getUrl());
return parse.getText();
}
@Test
public void testIt() throws ProtocolException, ParseException {
- for (int i=0; i<sampleFiles.length; i++) {
+ for (int i = 0; i < sampleFiles.length; i++) {
String found = getTextContent(sampleFiles[i]);
- Assert.assertTrue("text found : '"+found+"'",found.startsWith(expectedText));
+ Assert.assertTrue("text found : '" + found + "'",
+ found.startsWith(expectedText));
}
}
@@ -79,8 +83,10 @@ public class TestMSWordParser {
public void testOpeningDocs() throws ProtocolException, ParseException {
String[] filenames = new File(sampleDir).list();
for (int i = 0; i < filenames.length; i++) {
- if (filenames[i].endsWith(".doc")==false) continue;
- Assert.assertTrue("cann't read content of " + filenames[i], getTextContent(filenames[i]).length() > 0);
- }
+ if (filenames[i].endsWith(".doc") == false)
+ continue;
+ Assert.assertTrue("cann't read content of " + filenames[i],
+ getTextContent(filenames[i]).length() > 0);
+ }
}
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestOOParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestOOParser.java
index 1c7205d92..6960bad66 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestOOParser.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestOOParser.java
@@ -31,22 +31,22 @@ import org.apache.nutch.util.NutchConfiguration;
import org.junit.Assert;
import org.junit.Test;
-/**
+/**
* Unit tests for OOParser.
- *
+ *
* @author Andrzej Bialecki
*/
public class TestOOParser {
private String fileSeparator = System.getProperty("file.separator");
// This system property is defined in ./src/plugin/build-plugin.xml
- private String sampleDir = System.getProperty("test.data",".");
+ private String sampleDir = System.getProperty("test.data", ".");
// Make sure sample files are copied to "test.data" as specified in
// ./src/plugin/parse-oo/build.xml during plugin compilation.
- private String[] sampleFiles = {"ootest.odt", "ootest.sxw"};
+ private String[] sampleFiles = { "ootest.odt", "ootest.sxw" };
private String expectedText;
-
+
private String sampleText = "ootest.txt";
@Test
@@ -58,31 +58,36 @@ public class TestOOParser {
Protocol protocol;
ProtocolFactory factory = new ProtocolFactory(conf);
- System.out.println("Expected : "+expectedText);
+ System.out.println("Expected : " + expectedText);
- for (int i=0; i<sampleFiles.length; i++) {
+ for (int i = 0; i < sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
- if (sampleFiles[i].startsWith("ootest")==false) continue;
+ if (sampleFiles[i].startsWith("ootest") == false)
+ continue;
protocol = factory.getProtocol(urlString);
- content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
- parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content).get(content.getUrl());
+ content = protocol.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
+ parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content)
+ .get(content.getUrl());
String text = parse.getText().replaceAll("[ \t\r\n]+", " ").trim();
- // simply test for the presence of a text - the ordering of the elements may differ from what was expected
+ // simply test for the presence of a text - the ordering of the elements
+ // may differ from what was expected
// in the previous tests
- Assert.assertTrue(text!=null && text.length() > 0);
+ Assert.assertTrue(text != null && text.length() > 0);
- System.out.println("Found "+sampleFiles[i]+": "+text);
+ System.out.println("Found " + sampleFiles[i] + ": " + text);
}
}
- public TestOOParser() {
+ public TestOOParser() {
try {
// read the test string
- FileInputStream fis = new FileInputStream(sampleDir + fileSeparator + sampleText);
+ FileInputStream fis = new FileInputStream(sampleDir + fileSeparator
+ + sampleText);
StringBuffer sb = new StringBuffer();
int len = 0;
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
@@ -99,5 +104,4 @@ public class TestOOParser {
}
}
-
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestPdfParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestPdfParser.java
index dbd3b27b1..9884f0cf4 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestPdfParser.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestPdfParser.java
@@ -31,23 +31,20 @@ import org.apache.nutch.crawl.CrawlDatum;
import org.junit.Assert;
import org.junit.Test;
-/**
+/**
* Unit tests for PdfParser.
- *
+ *
* @author John Xing
*/
public class TestPdfParser {
private String fileSeparator = System.getProperty("file.separator");
// This system property is defined in ./src/plugin/build-plugin.xml
- private String sampleDir = System.getProperty("test.data",".");
+ private String sampleDir = System.getProperty("test.data", ".");
// Make sure sample files are copied to "test.data" as specified in
// ./src/plugin/parse-pdf/build.xml during plugin compilation.
// Check ./src/plugin/parse-pdf/sample/README.txt for what they are.
- private String[] sampleFiles = {
- "pdftest.pdf",
- "encrypted.pdf"
- };
+ private String[] sampleFiles = { "pdftest.pdf", "encrypted.pdf" };
private String expectedText = "A VERY SMALL PDF FILE";
@@ -63,8 +60,10 @@ public class TestPdfParser {
Configuration conf = NutchConfiguration.create();
protocol = new ProtocolFactory(conf).getProtocol(urlString);
- content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
- parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content).get(content.getUrl());
+ content = protocol.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
+ parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content)
+ .get(content.getUrl());
int index = parse.getText().indexOf(expectedText);
Assert.assertTrue(index > 0);
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRTFParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRTFParser.java
index 2d5663d23..f15d821fe 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRTFParser.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRTFParser.java
@@ -63,12 +63,13 @@ public class TestRTFParser {
Configuration conf = NutchConfiguration.create();
urlString = "file:" + sampleDir + fileSeparator + rtfFile;
protocol = new ProtocolFactory(conf).getProtocol(urlString);
- content = protocol.getProtocolOutput(new Text(urlString),
- new CrawlDatum()).getContent();
- parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content)
- .get(content.getUrl());
+ content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum())
+ .getContent();
+ parse = new ParseUtil(conf).parseByExtensionId("parse-tika", content).get(
+ content.getUrl());
String text = parse.getText();
- Assert.assertEquals("The quick brown fox jumps over the lazy dog", text.trim());
+ Assert.assertEquals("The quick brown fox jumps over the lazy dog",
+ text.trim());
String title = parse.getData().getTitle();
Metadata meta = parse.getData().getParseMeta();
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRobotsMetaProcessor.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRobotsMetaProcessor.java
index 09d541a40..4224f934d 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRobotsMetaProcessor.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestRobotsMetaProcessor.java
@@ -34,120 +34,96 @@ import org.junit.Test;
public class TestRobotsMetaProcessor {
/*
+ *
+ * some sample tags:
+ *
+ * <meta name="robots" content="index,follow"> <meta name="robots"
+ * content="noindex,follow"> <meta name="robots" content="index,nofollow">
+ * <meta name="robots" content="noindex,nofollow">
+ *
+ * <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
+ */
- some sample tags:
+ public static String[] tests = {
+ "<html><head><title>test page</title>"
+ + "<META NAME=\"ROBOTS\" CONTENT=\"NONE\"> "
+ + "<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\"> "
+ + "</head><body>" + " some text" + "</body></html>",
- <meta name="robots" content="index,follow">
- <meta name="robots" content="noindex,follow">
- <meta name="robots" content="index,nofollow">
- <meta name="robots" content="noindex,nofollow">
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"all\"> "
+ + "<meta http-equiv=\"pragma\" content=\"no-cache\"> "
+ + "</head><body>" + " some text" + "</body></html>",
- <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
+ "<html><head><title>test page</title>"
+ + "<MeTa NaMe=\"RoBoTs\" CoNtEnT=\"nOnE\"> "
+ + "<MeTa HtTp-EqUiV=\"pRaGmA\" cOnTeNt=\"No-CaChE\"> "
+ + "</head><body>" + " some text" + "</body></html>",
- */
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"none\"> " + "</head><body>"
+ + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"noindex,nofollow\"> "
+ + "</head><body>" + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"noindex,follow\"> "
+ + "</head><body>" + " some text" + "</body></html>",
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"index,nofollow\"> "
+ + "</head><body>" + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>"
+ + "<meta name=\"robots\" content=\"index,follow\"> "
+ + "<base href=\"http://www.nutch.org/\">" + "</head><body>"
+ + " some text" + "</body></html>",
+
+ "<html><head><title>test page</title>" + "<meta name=\"robots\"> "
+ + "<base href=\"http://www.nutch.org/base/\">" + "</head><body>"
+ + " some text" + "</body></html>",
+
+ };
- public static String[] tests=
- {
- "<html><head><title>test page</title>"
- + "<META NAME=\"ROBOTS\" CONTENT=\"NONE\"> "
- + "<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"all\"> "
- + "<meta http-equiv=\"pragma\" content=\"no-cache\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<MeTa NaMe=\"RoBoTs\" CoNtEnT=\"nOnE\"> "
- + "<MeTa HtTp-EqUiV=\"pRaGmA\" cOnTeNt=\"No-CaChE\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"none\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"noindex,nofollow\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"noindex,follow\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"index,nofollow\"> "
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\" content=\"index,follow\"> "
- + "<base href=\"http://www.nutch.org/\">"
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- "<html><head><title>test page</title>"
- + "<meta name=\"robots\"> "
- + "<base href=\"http://www.nutch.org/base/\">"
- + "</head><body>"
- + " some text"
- + "</body></html>",
-
- };
-
- public static final boolean[][] answers= {
- {true, true, true}, // NONE
- {false, false, true}, // all
- {true, true, true}, // nOnE
- {true, true, false}, // none
- {true, true, false}, // noindex,nofollow
- {true, false, false}, // noindex,follow
- {false, true, false}, // index,nofollow
- {false, false, false}, // index,follow
- {false, false, false}, // missing!
+ public static final boolean[][] answers = { { true, true, true }, // NONE
+ { false, false, true }, // all
+ { true, true, true }, // nOnE
+ { true, true, false }, // none
+ { true, true, false }, // noindex,nofollow
+ { true, false, false }, // noindex,follow
+ { false, true, false }, // index,nofollow
+ { false, false, false }, // index,follow
+ { false, false, false }, // missing!
};
private URL[][] currURLsAndAnswers;
@Test
public void testRobotsMetaProcessor() {
- DOMFragmentParser parser= new DOMFragmentParser();;
-
- try {
- currURLsAndAnswers= new URL[][] {
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org"), null},
- {new URL("http://www.nutch.org/foo/"),
- new URL("http://www.nutch.org/")},
- {new URL("http://www.nutch.org"),
- new URL("http://www.nutch.org/base/")}
- };
+ DOMFragmentParser parser = new DOMFragmentParser();
+ ;
+
+ try {
+ currURLsAndAnswers = new URL[][] {
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org"), null },
+ { new URL("http://www.nutch.org/foo/"),
+ new URL("http://www.nutch.org/") },
+ { new URL("http://www.nutch.org"),
+ new URL("http://www.nutch.org/base/") } };
} catch (Exception e) {
Assert.assertTrue("couldn't make test URLs!", false);
}
- for (int i= 0; i < tests.length; i++) {
- byte[] bytes= tests[i].getBytes();
+ for (int i = 0; i < tests.length; i++) {
+ byte[] bytes = tests[i].getBytes();
DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
@@ -157,9 +133,8 @@ public class TestRobotsMetaProcessor {
e.printStackTrace();
}
- HTMLMetaTags robotsMeta= new HTMLMetaTags();
- HTMLMetaProcessor.getMetaTags(robotsMeta, node,
- currURLsAndAnswers[i][0]);
+ HTMLMetaTags robotsMeta = new HTMLMetaTags();
+ HTMLMetaProcessor.getMetaTags(robotsMeta, node, currURLsAndAnswers[i][0]);
Assert.assertTrue("got index wrong on test " + i,
robotsMeta.getNoIndex() == answers[i][0]);
@@ -167,13 +142,13 @@ public class TestRobotsMetaProcessor {
robotsMeta.getNoFollow() == answers[i][1]);
Assert.assertTrue("got cache wrong on test " + i,
robotsMeta.getNoCache() == answers[i][2]);
- Assert.assertTrue("got base href wrong on test " + i + " (got "
- + robotsMeta.getBaseHref() + ")",
- ( (robotsMeta.getBaseHref() == null)
- && (currURLsAndAnswers[i][1] == null) )
- || ( (robotsMeta.getBaseHref() != null)
- && robotsMeta.getBaseHref().equals(
- currURLsAndAnswers[i][1]) ) );
+ Assert
+ .assertTrue(
+ "got base href wrong on test " + i + " (got "
+ + robotsMeta.getBaseHref() + ")",
+ ((robotsMeta.getBaseHref() == null) && (currURLsAndAnswers[i][1] == null))
+ || ((robotsMeta.getBaseHref() != null) && robotsMeta
+ .getBaseHref().equals(currURLsAndAnswers[i][1])));
}
}
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 b4835f03c..5d0c2f75a 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
@@ -55,9 +55,12 @@ public class ZipParser implements Parser {
List<Outlink> outLinksList = new ArrayList<Outlink>();
try {
- final String contentLen = content.getMetadata().get(Response.CONTENT_LENGTH);
+ final String contentLen = content.getMetadata().get(
+ Response.CONTENT_LENGTH);
final int len = Integer.parseInt(contentLen);
- if (LOG.isDebugEnabled()) { LOG.debug("ziplen: " + len); }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("ziplen: " + len);
+ }
final byte[] contentInBytes = content.getContent();
if (contentLen != null && contentInBytes.length != len) {
@@ -76,7 +79,8 @@ public class ZipParser implements Parser {
} catch (Exception e) {
return new ParseStatus(ParseStatus.FAILED,
- "Can't be handled as Zip document. " + e).getEmptyParseResult(content.getUrl(), getConf());
+ "Can't be handled as Zip document. " + e).getEmptyParseResult(
+ content.getUrl(), getConf());
}
if (resultText == null) {
@@ -89,11 +93,13 @@ public class ZipParser implements Parser {
outlinks = (Outlink[]) outLinksList.toArray(new Outlink[0]);
final ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS,
- resultTitle, outlinks,
- content.getMetadata());
+ resultTitle, outlinks, content.getMetadata());
- if (LOG.isTraceEnabled()) { LOG.trace("Zip file parsed sucessfully !!"); }
- return ParseResult.createParseResult(content.getUrl(), new ParseImpl(resultText, parseData));
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Zip file parsed sucessfully !!");
+ }
+ return ParseResult.createParseResult(content.getUrl(), new ParseImpl(
+ resultText, parseData));
}
public void setConf(Configuration conf) {
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 d2593ac02..b45472728 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
@@ -44,12 +44,13 @@ import org.apache.nutch.protocol.Content;
import org.apache.tika.Tika;
/**
- *
+ *
* @author Rohit Kulkarni & Ashish Vaidya
*/
public class ZipTextExtractor {
-
- public static final Logger LOG = LoggerFactory.getLogger(ZipTextExtractor.class);
+
+ public static final Logger LOG = LoggerFactory
+ .getLogger(ZipTextExtractor.class);
private Configuration conf;
@@ -57,21 +58,22 @@ public class ZipTextExtractor {
public ZipTextExtractor(Configuration conf) {
this.conf = conf;
}
-
- public String extractText(InputStream input, String url, List<Outlink> outLinksList) throws IOException {
+
+ public String extractText(InputStream input, String url,
+ List<Outlink> outLinksList) throws IOException {
String resultText = "";
ZipInputStream zin = new ZipInputStream(input);
ZipEntry entry;
-
+
while ((entry = zin.getNextEntry()) != null) {
-
+
if (!entry.isDirectory()) {
int size = (int) entry.getSize();
byte[] b = new byte[size];
- for(int x = 0; x < size; x++) {
+ for (int x = 0; x < size; x++) {
int err = zin.read();
- if(err != -1) {
- b[x] = (byte)err;
+ if (err != -1) {
+ b[x] = (byte) err;
}
}
String newurl = url + "/";
@@ -86,29 +88,33 @@ public class ZipTextExtractor {
String contentType = tika.detect(fname);
try {
Metadata metadata = new Metadata();
- metadata.set(Response.CONTENT_LENGTH, Long.toString(entry.getSize()));
+ metadata.set(Response.CONTENT_LENGTH,
+ Long.toString(entry.getSize()));
metadata.set(Response.CONTENT_TYPE, contentType);
- Content content = new Content(newurl, base, b, contentType, metadata, this.conf);
- Parse parse = new ParseUtil(this.conf).parse(content).get(content.getUrl());
+ Content content = new Content(newurl, base, b, contentType,
+ metadata, this.conf);
+ Parse parse = new ParseUtil(this.conf).parse(content).get(
+ content.getUrl());
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()));
+
+ for (int count = 0; count < theOutlinks.length; count++) {
+ outLinksList.add(new Outlink(theOutlinks[count].getToUrl(),
+ theOutlinks[count].getAnchor()));
}
-
+
resultText += entry.getName() + " " + parse.getText() + " ";
} catch (ParseException e) {
- if (LOG.isInfoEnabled()) {
- LOG.info("fetch okay, but can't parse " + fname + ", reason: " + e.getMessage());
+ if (LOG.isInfoEnabled()) {
+ LOG.info("fetch okay, but can't parse " + fname + ", reason: "
+ + e.getMessage());
}
}
}
}
}
-
+
return resultText;
}
-
-}
+}
diff --git a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/package-info.java b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/package-info.java
index becff50b5..fc81ee138 100644
--- a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/package-info.java
+++ b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/package-info.java
@@ -19,3 +19,4 @@
* Parse ZIP files: embedded files are recursively passed to appropriate parsers.
*/
package org.apache.nutch.parse.zip;
+
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 69ef48c10..17e386ad1 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
@@ -31,20 +31,20 @@ import org.apache.nutch.crawl.CrawlDatum;
import org.junit.Assert;
import org.junit.Test;
-/**
+/**
* Based on Unit tests for MSWordParser by John Xing
- *
+ *
* @author Rohit Kulkarni & Ashish Vaidya
*/
public class TestZipParser {
private String fileSeparator = System.getProperty("file.separator");
// This system property is defined in ./src/plugin/build-plugin.xml
- private String sampleDir = System.getProperty("test.data",".");
-
+ private String sampleDir = System.getProperty("test.data", ".");
+
// Make sure sample files are copied to "test.data"
-
- private String[] sampleFiles = {"test.zip"};
+
+ private String[] sampleFiles = { "test.zip" };
private String expectedText = "textfile.txt This is text file number 1 ";
@@ -60,8 +60,10 @@ public class TestZipParser {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
protocol = new ProtocolFactory(conf).getProtocol(urlString);
- content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
- parse = new ParseUtil(conf).parseByExtensionId("parse-zip",content).get(content.getUrl());
+ content = protocol.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
+ parse = new ParseUtil(conf).parseByExtensionId("parse-zip", content).get(
+ content.getUrl());
Assert.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 522445593..27122183c 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
@@ -37,11 +37,12 @@ import org.apache.nutch.util.NutchConfiguration;
import crawlercommons.robots.BaseRobotRules;
/**
- * This class is a protocol plugin used for file: scheme.
- * It creates {@link FileResponse} object and gets the content of the url from it.
- * Configurable parameters are {@code file.content.limit} and {@code file.crawl.parent}
- * in nutch-default.xml defined under "file properties" section.
- *
+ * This class is a protocol plugin used for file: scheme. It creates
+ * {@link FileResponse} object and gets the content of the url from it.
+ * Configurable parameters are {@code file.content.limit} and
+ * {@code file.crawl.parent} in nutch-default.xml defined under
+ * "file properties" section.
+ *
* @author John Xing
*/
public class File implements Protocol {
@@ -61,7 +62,8 @@ public class File implements Protocol {
private Configuration conf;
- public File() {}
+ public File() {
+ }
/**
* Set the {@link Configuration} object
@@ -80,52 +82,59 @@ public class File implements Protocol {
public Configuration getConf() {
return this.conf;
}
-
- /**
- * Set the length after at which content is truncated.
+
+ /**
+ * Set the length after at which content is truncated.
*/
public void setMaxContentLength(int maxContentLength) {
this.maxContentLength = maxContentLength;
}
- /**
- * Creates a {@link FileResponse} object corresponding to the url and
- * return a {@link ProtocolOutput} object as per the content received
+ /**
+ * Creates a {@link FileResponse} object corresponding to the url and return a
+ * {@link ProtocolOutput} object as per the content received
*
- * @param url Text containing the url
- * @param datum The CrawlDatum object corresponding to the url
+ * @param url
+ * Text containing the url
+ * @param datum
+ * The CrawlDatum object corresponding to the url
*
- * @return {@link ProtocolOutput} object for the content of the file indicated by url
+ * @return {@link ProtocolOutput} object for the content of the file indicated
+ * by url
*/
public ProtocolOutput getProtocolOutput(Text url, CrawlDatum datum) {
String urlString = url.toString();
try {
URL u = new URL(urlString);
-
+
int redirects = 0;
-
+
while (true) {
FileResponse response;
- response = new FileResponse(u, datum, this, getConf()); // make a request
-
+ response = new FileResponse(u, datum, this, getConf()); // make a
+ // request
+
int code = response.getCode();
-
- if (code == 200) { // got a good response
- return new ProtocolOutput(response.toContent()); // return it
-
- } else if (code == 304) { // got not modified
- return new ProtocolOutput(response.toContent(), ProtocolStatus.STATUS_NOTMODIFIED);
- } else if (code == 401) { // access denied / no read permissions
- return new ProtocolOutput(response.toContent(), new ProtocolStatus(ProtocolStatus.ACCESS_DENIED));
+ if (code == 200) { // got a good response
+ return new ProtocolOutput(response.toContent()); // return it
- } else if (code == 404) { // no such file
- return new ProtocolOutput(response.toContent(), ProtocolStatus.STATUS_NOTFOUND);
+ } else if (code == 304) { // got not modified
+ return new ProtocolOutput(response.toContent(),
+ ProtocolStatus.STATUS_NOTMODIFIED);
- } else if (code >= 300 && code < 400) { // handle redirect
+ } else if (code == 401) { // access denied / no read permissions
+ return new ProtocolOutput(response.toContent(), new ProtocolStatus(
+ ProtocolStatus.ACCESS_DENIED));
+
+ } else if (code == 404) { // no such file
+ return new ProtocolOutput(response.toContent(),
+ ProtocolStatus.STATUS_NOTFOUND);
+
+ } else if (code >= 300 && code < 400) { // handle redirect
u = new URL(response.getHeader("Location"));
if (LOG.isTraceEnabled()) {
- LOG.trace("redirect to " + u);
+ LOG.trace("redirect to " + u);
}
if (symlinksAsRedirects) {
return new ProtocolOutput(response.toContent(), new ProtocolStatus(
@@ -136,18 +145,18 @@ public class File implements Protocol {
ProtocolStatus.REDIR_EXCEEDED, u));
}
redirects++;
-
- } else { // convert to exception
+
+ } else { // convert to exception
throw new FileError(code);
}
- }
+ }
} catch (Exception e) {
e.printStackTrace();
return new ProtocolOutput(null, new ProtocolStatus(e));
}
}
- /**
+ /**
* Quick way for running this class. Useful for debugging.
*/
public static void main(String[] args) throws Exception {
@@ -162,7 +171,7 @@ public class File implements Protocol {
System.err.println(usage);
System.exit(-1);
}
-
+
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-logLevel")) {
logLevel = args[++i];
@@ -170,7 +179,7 @@ public class File implements Protocol {
maxContentLength = Integer.parseInt(args[++i]);
} else if (args[i].equals("-dumpContent")) {
dumpContent = true;
- } else if (i != args.length-1) {
+ } else if (i != args.length - 1) {
System.err.println(usage);
System.exit(-1);
} else
@@ -184,18 +193,19 @@ public class File implements Protocol {
file.setMaxContentLength(maxContentLength);
// set log level
- //LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));
+ // LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));
- ProtocolOutput output = file.getProtocolOutput(new Text(urlString), new CrawlDatum());
+ ProtocolOutput output = file.getProtocolOutput(new Text(urlString),
+ new CrawlDatum());
Content content = output.getContent();
System.err.println("URL: " + content.getUrl());
System.err.println("Status: " + output.getStatus());
System.err.println("Content-Type: " + content.getContentType());
- System.err.println("Content-Length: " +
- content.getMetadata().get(Response.CONTENT_LENGTH));
- System.err.println("Last-Modified: " +
- content.getMetadata().get(Response.LAST_MODIFIED));
+ System.err.println("Content-Length: "
+ + content.getMetadata().get(Response.CONTENT_LENGTH));
+ System.err.println("Last-Modified: "
+ + content.getMetadata().get(Response.LAST_MODIFIED));
String redirectLocation = content.getMetadata().get("Location");
if (redirectLocation != null) {
System.err.println("Location: " + redirectLocation);
@@ -208,12 +218,11 @@ public class File implements Protocol {
file = null;
}
- /**
- * No robots parsing is done for file protocol.
- * So this returns a set of empty rules which will allow every url.
+ /**
+ * No robots parsing is done for file protocol. So this returns a set of empty
+ * rules which will allow every url.
*/
public BaseRobotRules getRobotRules(Text url, CrawlDatum datum) {
return RobotRulesParser.EMPTY_RULES;
}
}
-
diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileError.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileError.java
index 24c10f57e..4fef340ef 100644
--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileError.java
+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileError.java
@@ -17,13 +17,16 @@
package org.apache.nutch.protocol.file;
-/** Thrown for File error codes.
+/**
+ * Thrown for File error codes.
*/
public class FileError extends FileException {
private int code;
-
- public int getCode(int code) { return code; }
+
+ public int getCode(int code) {
+ return code;
+ }
public FileError(int code) {
super("File Error: " + code);
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 3b07cb94d..b6e74ffdf 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
@@ -95,6 +95,7 @@ public class FileResponse {
/**
* Default public constructor
+ *
* @param url
* @param datum
* @param file
@@ -103,13 +104,13 @@ public class FileResponse {
* @throws IOException
*/
public FileResponse(URL url, CrawlDatum datum, File file, Configuration conf)
- throws FileException, IOException {
+ throws FileException, IOException {
this.orig = url.toString();
this.base = url.toString();
this.file = file;
this.conf = conf;
-
+
MIME = new MimeUtil(conf);
tika = new Tika();
@@ -139,16 +140,16 @@ public class FileResponse {
this.content = null;
// url.toURI() is only in j2se 1.5.0
- //java.io.File f = new java.io.File(url.toURI());
+ // java.io.File f = new java.io.File(url.toURI());
java.io.File f = new java.io.File(path);
if (!f.exists()) {
- this.code = 404; // http Not Found
+ this.code = 404; // http Not Found
return;
}
if (!f.canRead()) {
- this.code = 401; // http Unauthorized
+ this.code = 401; // http Unauthorized
return;
}
@@ -157,20 +158,23 @@ public class FileResponse {
// where case is insensitive
if (!f.equals(f.getCanonicalFile())) {
// set headers
- //hdrs.put("Location", f.getCanonicalFile().toURI());
+ // hdrs.put("Location", f.getCanonicalFile().toURI());
//
- // we want to automatically escape characters that are illegal in URLs.
- // It is recommended that new code convert an abstract pathname into a URL
- // by first converting it into a URI, via the toURI method, and then
+ // we want to automatically escape characters that are illegal in URLs.
+ // It is recommended that new code convert an abstract pathname into a
+ // URL
+ // by first converting it into a URI, via the toURI method, and then
// converting the URI into a URL via the URI.toURL method.
- headers.set(Response.LOCATION, f.getCanonicalFile().toURI().toURL().toString());
+ headers.set(Response.LOCATION, f.getCanonicalFile().toURI().toURL()
+ .toString());
- this.code = 300; // http redirect
+ this.code = 300; // http redirect
return;
}
if (f.lastModified() <= datum.getModifiedTime()) {
this.code = 304;
- this.headers.set("Last-Modified", HttpDateFormat.toString(f.lastModified()));
+ this.headers.set("Last-Modified",
+ HttpDateFormat.toString(f.lastModified()));
return;
}
@@ -240,6 +244,7 @@ public class FileResponse {
/**
* get dir list as http response
+ *
* @param f
* @throws IOException
*/
@@ -265,6 +270,7 @@ public class FileResponse {
/**
* generate html page from dir list
+ *
* @param list
* @param path
* @param includeDotDot
diff --git a/src/plugin/protocol-file/src/test/org/apache/nutch/protocol/file/TestProtocolFile.java b/src/plugin/protocol-file/src/test/org/apache/nutch/protocol/file/TestProtocolFile.java
index 3f9e693a5..5f95377c9 100644
--- a/src/plugin/protocol-file/src/test/org/apache/nutch/protocol/file/TestProtocolFile.java
+++ b/src/plugin/protocol-file/src/test/org/apache/nutch/protocol/file/TestProtocolFile.java
@@ -49,7 +49,8 @@ public class TestProtocolFile {
private String sampleDir = System.getProperty("test.data", ".");
private static final String[] testTextFiles = new String[] {
- "testprotocolfile.txt", "testprotocolfile_(encoded).txt", "testprotocolfile_%28encoded%29.txt" };
+ "testprotocolfile.txt", "testprotocolfile_(encoded).txt",
+ "testprotocolfile_%28encoded%29.txt" };
private static final CrawlDatum datum = new CrawlDatum();
@@ -90,8 +91,8 @@ public class TestProtocolFile {
Assert.assertNotNull(output.getContent().getContentType());
Assert.assertEquals(expectedMimeType, output.getContent().getContentType());
Assert.assertNotNull(output.getContent().getMetadata());
- Assert.assertEquals(expectedMimeType,
- output.getContent().getMetadata().get(Response.CONTENT_TYPE));
+ Assert.assertEquals(expectedMimeType, output.getContent().getMetadata()
+ .get(Response.CONTENT_TYPE));
}
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java
index a28f76244..da25d87bc 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java
@@ -40,565 +40,556 @@ import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
/***********************************************
- * Client.java encapsulates functionalities necessary for nutch to
- * get dir list and retrieve file from an FTP server.
- * This class takes care of all low level details of interacting
- * with an FTP server and provides a convenient higher level interface.
- *
+ * Client.java encapsulates functionalities necessary for nutch to get dir list
+ * and retrieve file from an FTP server. This class takes care of all low level
+ * details of interacting with an FTP server and provides a convenient higher
+ * level interface.
+ *
* Modified from FtpClient.java in apache commons-net.
*
- * Notes by John Xing:
- * ftp server implementations are hardly uniform and none seems to follow
- * RFCs whole-heartedly. We have no choice, but assume common denominator
- * as following:
- * (1) Use stream mode for data transfer. Block mode will be better for
- * multiple file downloading and partial file downloading. However
- * not every ftpd has block mode support.
- * (2) Use passive mode for data connection.
- * So Nutch will work if we run behind firewall.
- * (3) Data connection is opened/closed per ftp command for the reasons
- * listed in (1). There are ftp servers out there,
- * when partial downloading is enforced by closing data channel
- * socket on our client side, the server side immediately closes
- * control channel (socket). Our codes deal with such a bad behavior.
- * (4) LIST is used to obtain remote file attributes if possible.
- * MDTM & SIZE would be nice, but not as ubiquitously implemented as LIST.
- * (5) Avoid using ABOR in single thread? Do not use it at all.
- *
- * About exceptions:
- * Some specific exceptions are re-thrown as one of FtpException*.java
- * In fact, each function throws FtpException*.java or pass IOException.
- *
+ * Notes by John Xing: ftp server implementations are hardly uniform and none
+ * seems to follow RFCs whole-heartedly. We have no choice, but assume common
+ * denominator as following: (1) Use stream mode for data transfer. Block mode
+ * will be better for multiple file downloading and partial file downloading.
+ * However not every ftpd has block mode support. (2) Use passive mode for data
+ * connection. So Nutch will work if we run behind firewall. (3) Data connection
+ * is opened/closed per ftp command for the reasons listed in (1). There are ftp
+ * servers out there, when partial downloading is enforced by closing data
+ * channel socket on our client side, the server side immediately closes control
+ * channel (socket). Our codes deal with such a bad behavior. (4) LIST is used
+ * to obtain remote file attributes if possible. MDTM & SIZE would be nice, but
+ * not as ubiquitously implemented as LIST. (5) Avoid using ABOR in single
+ * thread? Do not use it at all.
+ *
+ * About exceptions: Some specific exceptions are re-thrown as one of
+ * FtpException*.java In fact, each function throws FtpException*.java or pass
+ * IOException.
+ *
* @author John Xing
***********************************************/
-public class Client extends FTP
-{
- private int __dataTimeout;
- private int __passivePort;
- private String __passiveHost;
-// private int __fileType, __fileFormat;
- private boolean __remoteVerificationEnabled;
-// private FTPFileEntryParser __entryParser;
- private String __systemName;
-
- /** Public default constructor */
- public Client()
- {
- __initDefaults();
- __dataTimeout = -1;
- __remoteVerificationEnabled = true;
+public class Client extends FTP {
+ private int __dataTimeout;
+ private int __passivePort;
+ private String __passiveHost;
+ // private int __fileType, __fileFormat;
+ private boolean __remoteVerificationEnabled;
+ // private FTPFileEntryParser __entryParser;
+ private String __systemName;
+
+ /** Public default constructor */
+ public Client() {
+ __initDefaults();
+ __dataTimeout = -1;
+ __remoteVerificationEnabled = true;
+ }
+
+ // defaults when initialize
+ private void __initDefaults() {
+ __passiveHost = null;
+ __passivePort = -1;
+ __systemName = null;
+ // __fileType = FTP.ASCII_FILE_TYPE;
+ // __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
+ // __entryParser = null;
+ }
+
+ // parse reply for pass()
+ private void __parsePassiveModeReply(String reply)
+ throws MalformedServerReplyException {
+ int i, index, lastIndex;
+ String octet1, octet2;
+ StringBuffer host;
+
+ reply = reply.substring(reply.indexOf('(') + 1, reply.indexOf(')')).trim();
+
+ host = new StringBuffer(24);
+ lastIndex = 0;
+ index = reply.indexOf(',');
+ host.append(reply.substring(lastIndex, index));
+
+ for (i = 0; i < 3; i++) {
+ host.append('.');
+ lastIndex = index + 1;
+ index = reply.indexOf(',', lastIndex);
+ host.append(reply.substring(lastIndex, index));
}
- // defaults when initialize
- private void __initDefaults()
- {
- __passiveHost = null;
- __passivePort = -1;
- __systemName = null;
-// __fileType = FTP.ASCII_FILE_TYPE;
-// __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
-// __entryParser = null;
- }
+ lastIndex = index + 1;
+ index = reply.indexOf(',', lastIndex);
+
+ octet1 = reply.substring(lastIndex, index);
+ octet2 = reply.substring(index + 1);
- // parse reply for pass()
- private void __parsePassiveModeReply(String reply)
- throws MalformedServerReplyException
- {
- int i, index, lastIndex;
- String octet1, octet2;
- StringBuffer host;
-
- reply = reply.substring(reply.indexOf('(') + 1,
- reply.indexOf(')')).trim();
-
- host = new StringBuffer(24);
- lastIndex = 0;
- index = reply.indexOf(',');
- host.append(reply.substring(lastIndex, index));
-
- for (i = 0; i < 3; i++)
- {
- host.append('.');
- lastIndex = index + 1;
- index = reply.indexOf(',', lastIndex);
- host.append(reply.substring(lastIndex, index));
- }
-
- lastIndex = index + 1;
- index = reply.indexOf(',', lastIndex);
-
- octet1 = reply.substring(lastIndex, index);
- octet2 = reply.substring(index + 1);
-
- // index and lastIndex now used as temporaries
- try
- {
- index = Integer.parseInt(octet1);
- lastIndex = Integer.parseInt(octet2);
- }
- catch (NumberFormatException e)
- {
- throw new MalformedServerReplyException(
- "Could not parse passive host information.\nServer Reply: " + reply);
- }
-
- index <<= 8;
- index |= lastIndex;
-
- __passiveHost = host.toString();
- __passivePort = index;
+ // index and lastIndex now used as temporaries
+ try {
+ index = Integer.parseInt(octet1);
+ lastIndex = Integer.parseInt(octet2);
+ } catch (NumberFormatException e) {
+ throw new MalformedServerReplyException(
+ "Could not parse passive host information.\nServer Reply: " + reply);
}
- /**
- * open a passive data connection socket
- * @param command
- * @param arg
- * @return
- * @throws IOException
- * @throws FtpExceptionCanNotHaveDataConnection
- */
- protected Socket __openPassiveDataConnection(int command, String arg)
+ index <<= 8;
+ index |= lastIndex;
+
+ __passiveHost = host.toString();
+ __passivePort = index;
+ }
+
+ /**
+ * open a passive data connection socket
+ *
+ * @param command
+ * @param arg
+ * @return
+ * @throws IOException
+ * @throws FtpExceptionCanNotHaveDataConnection
+ */
+ protected Socket __openPassiveDataConnection(int command, String arg)
throws IOException, FtpExceptionCanNotHaveDataConnection {
- Socket socket;
-
-// // 20040317, xing, accommodate ill-behaved servers, see below
-// int port_previous = __passivePort;
-
- if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
- throw new FtpExceptionCanNotHaveDataConnection(
- "pasv() failed. " + getReplyString());
-
- try {
- __parsePassiveModeReply(getReplyStrings()[0]);
- } catch (MalformedServerReplyException e) {
- throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
- }
-
-// // 20040317, xing, accommodate ill-behaved servers, see above
-// int count = 0;
-// System.err.println("__passivePort "+__passivePort);
-// System.err.println("port_previous "+port_previous);
-// while (__passivePort == port_previous) {
-// // just quit if too many tries. make it an exception here?
-// if (count++ > 10)
-// return null;
-// // slow down further for each new try
-// Thread.sleep(500*count);
-// if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
-// throw new FtpExceptionCanNotHaveDataConnection(
-// "pasv() failed. " + getReplyString());
-// //return null;
-// try {
-// __parsePassiveModeReply(getReplyStrings()[0]);
-// } catch (MalformedServerReplyException e) {
-// throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
-// }
-// }
-
- socket = _socketFactory_.createSocket(__passiveHost, __passivePort);
-
- if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
- socket.close();
- return null;
- }
-
- if (__remoteVerificationEnabled && !verifyRemote(socket))
- {
- InetAddress host1, host2;
-
- host1 = socket.getInetAddress();
- host2 = getRemoteAddress();
-
- socket.close();
-
- // our precaution
- throw new FtpExceptionCanNotHaveDataConnection(
- "Host attempting data connection " + host1.getHostAddress() +
- " is not same as server " + host2.getHostAddress() +
- " So we intentionally close it for security precaution."
- );
- }
-
- if (__dataTimeout >= 0)
- socket.setSoTimeout(__dataTimeout);
-
- return socket;
- }
+ Socket socket;
- /***
- * Sets the timeout in milliseconds to use for data connection.
- * set immediately after opening the data connection.
- ***/
- public void setDataTimeout(int timeout)
- {
- __dataTimeout = timeout;
- }
+ // // 20040317, xing, accommodate ill-behaved servers, see below
+ // int port_previous = __passivePort;
- /***
- * Closes the connection to the FTP server and restores
- * connection parameters to the default values.
- * <p>
- * @exception IOException If an error occurs while disconnecting.
- ***/
- public void disconnect() throws IOException
- {
- __initDefaults();
- super.disconnect();
- // no worry for data connection, since we always close it
- // in every ftp command that invloves data connection
- }
+ if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
+ throw new FtpExceptionCanNotHaveDataConnection("pasv() failed. "
+ + getReplyString());
- /***
- * Enable or disable verification that the remote host taking part
- * of a data connection is the same as the host to which the control
- * connection is attached. The default is for verification to be
- * enabled. You may set this value at any time, whether the
- * FTPClient is currently connected or not.
- * <p>
- * @param enable True to enable verification, false to disable verification.
- ***/
- public void setRemoteVerificationEnabled(boolean enable)
- {
- __remoteVerificationEnabled = enable;
+ try {
+ __parsePassiveModeReply(getReplyStrings()[0]);
+ } catch (MalformedServerReplyException e) {
+ throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
}
- /***
- * Return whether or not verification of the remote host participating
- * in data connections is enabled. The default behavior is for
- * verification to be enabled.
- * <p>
- * @return True if verification is enabled, false if not.
- ***/
- public boolean isRemoteVerificationEnabled()
- {
- return __remoteVerificationEnabled;
+ // // 20040317, xing, accommodate ill-behaved servers, see above
+ // int count = 0;
+ // System.err.println("__passivePort "+__passivePort);
+ // System.err.println("port_previous "+port_previous);
+ // while (__passivePort == port_previous) {
+ // // just quit if too many tries. make it an exception here?
+ // if (count++ > 10)
+ // return null;
+ // // slow down further for each new try
+ // Thread.sleep(500*count);
+ // if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
+ // throw new FtpExceptionCanNotHaveDataConnection(
+ // "pasv() failed. " + getReplyString());
+ // //return null;
+ // try {
+ // __parsePassiveModeReply(getReplyStrings()[0]);
+ // } catch (MalformedServerReplyException e) {
+ // throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
+ // }
+ // }
+
+ socket = _socketFactory_.createSocket(__passiveHost, __passivePort);
+
+ if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
+ socket.close();
+ return null;
}
- /***
- * Login to the FTP server using the provided username and password.
- * <p>
- * @param username The username to login under.
- * @param password The password to use.
- * @return True if successfully completed, false if not.
- * @exception FTPConnectionClosedException
- * If the FTP server prematurely closes the connection as a result
- * of the client being idle or some other reason causing the server
- * to send FTP reply code 421. This exception may be caught either
- * as an IOException or independently as itself.
- * @exception IOException If an I/O error occurs while either sending a
- * command to the server or receiving a reply from the server.
- ***/
- public boolean login(String username, String password) throws IOException
- {
- user(username);
-
- if (FTPReply.isPositiveCompletion(getReplyCode()))
- return true;
-
- // If we get here, we either have an error code, or an intermmediate
- // reply requesting password.
- if (!FTPReply.isPositiveIntermediate(getReplyCode()))
- return false;
-
- return FTPReply.isPositiveCompletion(pass(password));
- }
+ if (__remoteVerificationEnabled && !verifyRemote(socket)) {
+ InetAddress host1, host2;
- /***
- * Logout of the FTP server by sending the QUIT command.
- * <p>
- * @return True if successfully completed, false if not.
- * @exception FTPConnectionClosedException
- * If the FTP server prematurely closes the connection as a result
- * of the client being idle or some other reason causing the server
- * to send FTP reply code 421. This exception may be caught either
- * as an IOException or independently as itself.
- * @exception IOException If an I/O error occurs while either sending a
- * command to the server or receiving a reply from the server.
- ***/
- public boolean logout() throws IOException
- {
- return FTPReply.isPositiveCompletion(quit());
+ host1 = socket.getInetAddress();
+ host2 = getRemoteAddress();
+
+ socket.close();
+
+ // our precaution
+ throw new FtpExceptionCanNotHaveDataConnection(
+ "Host attempting data connection " + host1.getHostAddress()
+ + " is not same as server " + host2.getHostAddress()
+ + " So we intentionally close it for security precaution.");
}
- /**
- * retrieve list reply for path
- * @param path
- * @param entries
- * @param limit
- * @param parser
- * @throws IOException
- * @throws FtpExceptionCanNotHaveDataConnection
- * @throws FtpExceptionUnknownForcedDataClose
- * @throws FtpExceptionControlClosedByForcedDataClose
- */
- public void retrieveList(String path, List<FTPFile> entries, int limit,
- FTPFileEntryParser parser)
- throws IOException,
- FtpExceptionCanNotHaveDataConnection,
- FtpExceptionUnknownForcedDataClose,
- FtpExceptionControlClosedByForcedDataClose {
- Socket socket = __openPassiveDataConnection(FTPCommand.LIST, path);
-
- if (socket == null)
- throw new FtpExceptionCanNotHaveDataConnection("LIST "
+ if (__dataTimeout >= 0)
+ socket.setSoTimeout(__dataTimeout);
+
+ return socket;
+ }
+
+ /***
+ * Sets the timeout in milliseconds to use for data connection. set
+ * immediately after opening the data connection.
+ ***/
+ public void setDataTimeout(int timeout) {
+ __dataTimeout = timeout;
+ }
+
+ /***
+ * Closes the connection to the FTP server and restores connection parameters
+ * to the default values.
+ * <p>
+ *
+ * @exception IOException
+ * If an error occurs while disconnecting.
+ ***/
+ public void disconnect() throws IOException {
+ __initDefaults();
+ super.disconnect();
+ // no worry for data connection, since we always close it
+ // in every ftp command that invloves data connection
+ }
+
+ /***
+ * Enable or disable verification that the remote host taking part of a data
+ * connection is the same as the host to which the control connection is
+ * attached. The default is for verification to be enabled. You may set this
+ * value at any time, whether the FTPClient is currently connected or not.
+ * <p>
+ *
+ * @param enable
+ * True to enable verification, false to disable verification.
+ ***/
+ public void setRemoteVerificationEnabled(boolean enable) {
+ __remoteVerificationEnabled = enable;
+ }
+
+ /***
+ * Return whether or not verification of the remote host participating in data
+ * connections is enabled. The default behavior is for verification to be
+ * enabled.
+ * <p>
+ *
+ * @return True if verification is enabled, false if not.
+ ***/
+ public boolean isRemoteVerificationEnabled() {
+ return __remoteVerificationEnabled;
+ }
+
+ /***
+ * Login to the FTP server using the provided username and password.
+ * <p>
+ *
+ * @param username
+ * The username to login under.
+ * @param password
+ * The password to use.
+ * @return True if successfully completed, false if not.
+ * @exception FTPConnectionClosedException
+ * If the FTP server prematurely closes the connection as a
+ * result of the client being idle or some other reason causing
+ * the server to send FTP reply code 421. This exception may be
+ * caught either as an IOException or independently as itself.
+ * @exception IOException
+ * If an I/O error occurs while either sending a command to the
+ * server or receiving a reply from the server.
+ ***/
+ public boolean login(String username, String password) throws IOException {
+ user(username);
+
+ if (FTPReply.isPositiveCompletion(getReplyCode()))
+ return true;
+
+ // If we get here, we either have an error code, or an intermmediate
+ // reply requesting password.
+ if (!FTPReply.isPositiveIntermediate(getReplyCode()))
+ return false;
+
+ return FTPReply.isPositiveCompletion(pass(password));
+ }
+
+ /***
+ * Logout of the FTP server by sending the QUIT command.
+ * <p>
+ *
+ * @return True if successfully completed, false if not.
+ * @exception FTPConnectionClosedException
+ * If the FTP server prematurely closes the connection as a
+ * result of the client being idle or some other reason causing
+ * the server to send FTP reply code 421. This exception may be
+ * caught either as an IOException or independently as itself.
+ * @exception IOException
+ * If an I/O error occurs while either sending a command to the
+ * server or receiving a reply from the server.
+ ***/
+ public boolean logout() throws IOException {
+ return FTPReply.isPositiveCompletion(quit());
+ }
+
+ /**
+ * retrieve list reply for path
+ *
+ * @param path
+ * @param entries
+ * @param limit
+ * @param parser
+ * @throws IOException
+ * @throws FtpExceptionCanNotHaveDataConnection
+ * @throws FtpExceptionUnknownForcedDataClose
+ * @throws FtpExceptionControlClosedByForcedDataClose
+ */
+ public void retrieveList(String path, List<FTPFile> entries, int limit,
+ FTPFileEntryParser parser) throws IOException,
+ FtpExceptionCanNotHaveDataConnection, FtpExceptionUnknownForcedDataClose,
+ FtpExceptionControlClosedByForcedDataClose {
+ Socket socket = __openPassiveDataConnection(FTPCommand.LIST, path);
+
+ if (socket == null)
+ throw new FtpExceptionCanNotHaveDataConnection("LIST "
+ ((path == null) ? "" : path));
- BufferedReader reader =
- new BufferedReader(new InputStreamReader(socket.getInputStream()));
-
- // force-close data channel socket, when download limit is reached
-// boolean mandatory_close = false;
-
- //List entries = new LinkedList();
- int count = 0;
- String line = parser.readNextEntry(reader);
- while (line != null) {
- FTPFile ftpFile = parser.parseFTPEntry(line);
- // skip non-formatted lines
- if (ftpFile == null) {
- line = parser.readNextEntry(reader);
- continue;
- }
- entries.add(ftpFile);
- count += line.length();
- // impose download limit if limit >= 0, otherwise no limit
- // here, cut off is up to the line when total bytes is just over limit
- if (limit >= 0 && count > limit) {
-// mandatory_close = true;
- break;
- }
- line = parser.readNextEntry(reader);
- }
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ socket.getInputStream()));
- //if (mandatory_close)
- // you always close here, no matter mandatory_close or not.
- // however different ftp servers respond differently, see below.
- socket.close();
+ // force-close data channel socket, when download limit is reached
+ // boolean mandatory_close = false;
- // scenarios:
- // (1) mandatory_close is false, download limit not reached
- // no special care here
- // (2) mandatory_close is true, download limit is reached
- // different servers have different reply codes:
-
- try {
- int reply = getReply();
- if (!_notBadReply(reply))
- throw new FtpExceptionUnknownForcedDataClose(getReplyString());
- } catch (FTPConnectionClosedException e) {
- // some ftp servers will close control channel if data channel socket
- // is closed by our end before all data has been read out. Check:
- // tux414.q-tam.hp.com FTP server (hp.com version whp02)
- // so must catch FTPConnectionClosedException thrown by getReply() above
- //disconnect();
- throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
+ // List entries = new LinkedList();
+ int count = 0;
+ String line = parser.readNextEntry(reader);
+ while (line != null) {
+ FTPFile ftpFile = parser.parseFTPEntry(line);
+ // skip non-formatted lines
+ if (ftpFile == null) {
+ line = parser.readNextEntry(reader);
+ continue;
}
+ entries.add(ftpFile);
+ count += line.length();
+ // impose download limit if limit >= 0, otherwise no limit
+ // here, cut off is up to the line when total bytes is just over limit
+ if (limit >= 0 && count > limit) {
+ // mandatory_close = true;
+ break;
+ }
+ line = parser.readNextEntry(reader);
+ }
+ // if (mandatory_close)
+ // you always close here, no matter mandatory_close or not.
+ // however different ftp servers respond differently, see below.
+ socket.close();
+
+ // scenarios:
+ // (1) mandatory_close is false, download limit not reached
+ // no special care here
+ // (2) mandatory_close is true, download limit is reached
+ // different servers have different reply codes:
+
+ try {
+ int reply = getReply();
+ if (!_notBadReply(reply))
+ throw new FtpExceptionUnknownForcedDataClose(getReplyString());
+ } catch (FTPConnectionClosedException e) {
+ // some ftp servers will close control channel if data channel socket
+ // is closed by our end before all data has been read out. Check:
+ // tux414.q-tam.hp.com FTP server (hp.com version whp02)
+ // so must catch FTPConnectionClosedException thrown by getReply() above
+ // disconnect();
+ throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
}
- /**
- * retrieve file for path
- * @param path
- * @param os
- * @param limit
- * @throws IOException
- * @throws FtpExceptionCanNotHaveDataConnection
- * @throws FtpExceptionUnknownForcedDataClose
- * @throws FtpExceptionControlClosedByForcedDataClose
- */
- public void retrieveFile(String path, OutputStream os, int limit)
- throws IOException,
- FtpExceptionCanNotHaveDataConnection,
- FtpExceptionUnknownForcedDataClose,
- FtpExceptionControlClosedByForcedDataClose {
-
- Socket socket = __openPassiveDataConnection(FTPCommand.RETR, path);
-
- if (socket == null)
- throw new FtpExceptionCanNotHaveDataConnection("RETR "
+ }
+
+ /**
+ * retrieve file for path
+ *
+ * @param path
+ * @param os
+ * @param limit
+ * @throws IOException
+ * @throws FtpExceptionCanNotHaveDataConnection
+ * @throws FtpExceptionUnknownForcedDataClose
+ * @throws FtpExceptionControlClosedByForcedDataClose
+ */
+ public void retrieveFile(String path, OutputStream os, int limit)
+ throws IOException, FtpExceptionCanNotHaveDataConnection,
+ FtpExceptionUnknownForcedDataClose,
+ FtpExceptionControlClosedByForcedDataClose {
+
+ Socket socket = __openPassiveDataConnection(FTPCommand.RETR, path);
+
+ if (socket == null)
+ throw new FtpExceptionCanNotHaveDataConnection("RETR "
+ ((path == null) ? "" : path));
- InputStream input = socket.getInputStream();
-
- // 20040318, xing, treat everything as BINARY_FILE_TYPE for now
- // do we ever need ASCII_FILE_TYPE?
- //if (__fileType == ASCII_FILE_TYPE)
- // input = new FromNetASCIIInputStream(input);
-
- // fixme, should we instruct server here for binary file type?
-
- // force-close data channel socket
- // boolean mandatory_close = false;
-
- int len; int count = 0;
- byte[] buf =
- new byte[org.apache.commons.net.io.Util.DEFAULT_COPY_BUFFER_SIZE];
- while((len=input.read(buf,0,buf.length)) != -1){
- count += len;
- // impose download limit if limit >= 0, otherwise no limit
- // here, cut off is exactly of limit bytes
- if (limit >= 0 && count > limit) {
- os.write(buf,0,len-(count-limit));
- // mandatory_close = true;
- break;
- }
- os.write(buf,0,len);
- os.flush();
- }
-
- //if (mandatory_close)
- // you always close here, no matter mandatory_close or not.
- // however different ftp servers respond differently, see below.
- socket.close();
-
- // scenarios:
- // (1) mandatory_close is false, download limit not reached
- // no special care here
- // (2) mandatory_close is true, download limit is reached
- // different servers have different reply codes:
-
- // do not need this
- //sendCommand("ABOR");
-
- try {
- int reply = getReply();
- if (!_notBadReply(reply))
- throw new FtpExceptionUnknownForcedDataClose(getReplyString());
- } catch (FTPConnectionClosedException e) {
- // some ftp servers will close control channel if data channel socket
- // is closed by our end before all data has been read out. Check:
- // tux414.q-tam.hp.com FTP server (hp.com version whp02)
- // so must catch FTPConnectionClosedException thrown by getReply() above
- //disconnect();
- throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
+ InputStream input = socket.getInputStream();
+
+ // 20040318, xing, treat everything as BINARY_FILE_TYPE for now
+ // do we ever need ASCII_FILE_TYPE?
+ // if (__fileType == ASCII_FILE_TYPE)
+ // input = new FromNetASCIIInputStream(input);
+
+ // fixme, should we instruct server here for binary file type?
+
+ // force-close data channel socket
+ // boolean mandatory_close = false;
+
+ int len;
+ int count = 0;
+ byte[] buf = new byte[org.apache.commons.net.io.Util.DEFAULT_COPY_BUFFER_SIZE];
+ while ((len = input.read(buf, 0, buf.length)) != -1) {
+ count += len;
+ // impose download limit if limit >= 0, otherwise no limit
+ // here, cut off is exactly of limit bytes
+ if (limit >= 0 && count > limit) {
+ os.write(buf, 0, len - (count - limit));
+ // mandatory_close = true;
+ break;
}
+ os.write(buf, 0, len);
+ os.flush();
+ }
+ // if (mandatory_close)
+ // you always close here, no matter mandatory_close or not.
+ // however different ftp servers respond differently, see below.
+ socket.close();
+
+ // scenarios:
+ // (1) mandatory_close is false, download limit not reached
+ // no special care here
+ // (2) mandatory_close is true, download limit is reached
+ // different servers have different reply codes:
+
+ // do not need this
+ // sendCommand("ABOR");
+
+ try {
+ int reply = getReply();
+ if (!_notBadReply(reply))
+ throw new FtpExceptionUnknownForcedDataClose(getReplyString());
+ } catch (FTPConnectionClosedException e) {
+ // some ftp servers will close control channel if data channel socket
+ // is closed by our end before all data has been read out. Check:
+ // tux414.q-tam.hp.com FTP server (hp.com version whp02)
+ // so must catch FTPConnectionClosedException thrown by getReply() above
+ // disconnect();
+ throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
}
- /**
- * reply check after closing data connection
- * @param reply
- * @return
- */
- private boolean _notBadReply(int reply) {
+ }
+
+ /**
+ * reply check after closing data connection
+ *
+ * @param reply
+ * @return
+ */
+ private boolean _notBadReply(int reply) {
- if (FTPReply.isPositiveCompletion(reply)) {
- // do nothing
- } else if (reply == 426) { // FTPReply.TRANSFER_ABORTED
+ if (FTPReply.isPositiveCompletion(reply)) {
+ // do nothing
+ } else if (reply == 426) { // FTPReply.TRANSFER_ABORTED
// some ftp servers reply 426, e.g.,
// foggy FTP server (Version wu-2.6.2(2)
- // there is second reply witing? no!
- //getReply();
- } else if (reply == 450) { // FTPReply.FILE_ACTION_NOT_TAKEN
+ // there is second reply witing? no!
+ // getReply();
+ } else if (reply == 450) { // FTPReply.FILE_ACTION_NOT_TAKEN
// some ftp servers reply 450, e.g.,
// ProFTPD [ftp.kernel.org]
- // there is second reply witing? no!
- //getReply();
- } else if (reply == 451) { // FTPReply.ACTION_ABORTED
+ // there is second reply witing? no!
+ // getReply();
+ } else if (reply == 451) { // FTPReply.ACTION_ABORTED
// some ftp servers reply 451, e.g.,
// ProFTPD [ftp.kernel.org]
- // there is second reply witing? no!
- //getReply();
- } else if (reply == 451) { // FTPReply.ACTION_ABORTED
- } else {
+ // there is second reply witing? no!
+ // getReply();
+ } else if (reply == 451) { // FTPReply.ACTION_ABORTED
+ } else {
// what other kind of ftp server out there?
- return false;
- }
-
- return true;
+ return false;
}
- /***
- * Sets the file type to be transferred. This should be one of
- * <code> FTP.ASCII_FILE_TYPE </code>, <code> FTP.IMAGE_FILE_TYPE </code>,
- * etc. The file type only needs to be set when you want to change the
- * type. After changing it, the new type stays in effect until you change
- * it again. The default file type is <code> FTP.ASCII_FILE_TYPE </code>
- * if this method is never called.
- * <p>
- * @param fileType The <code> _FILE_TYPE </code> constant indcating the
- * type of file.
- * @return True if successfully completed, false if not.
- * @exception FTPConnectionClosedException
- * If the FTP server prematurely closes the connection as a result
- * of the client being idle or some other reason causing the server
- * to send FTP reply code 421. This exception may be caught either
- * as an IOException or independently as itself.
- * @exception IOException If an I/O error occurs while either sending a
- * command to the server or receiving a reply from the server.
- ***/
- public boolean setFileType(int fileType) throws IOException
- {
- if (FTPReply.isPositiveCompletion(type(fileType)))
- {
-/* __fileType = fileType;
- __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;*/
- return true;
- }
- return false;
- }
-
- /***
- * Fetches the system type name from the server and returns the string.
- * This value is cached for the duration of the connection after the
- * first call to this method. In other words, only the first time
- * that you invoke this method will it issue a SYST command to the
- * FTP server. FTPClient will remember the value and return the
- * cached value until a call to disconnect.
- * <p>
- * @return The system type name obtained from the server. null if the
- * information could not be obtained.
- * @exception FTPConnectionClosedException
- * If the FTP server prematurely closes the connection as a result
- * of the client being idle or some other reason causing the server
- * to send FTP reply code 421. This exception may be caught either
- * as an IOException or independently as itself.
- * @exception IOException If an I/O error occurs while either sending a
- * command to the server or receiving a reply from the server.
- ***/
- public String getSystemName()
- throws IOException, FtpExceptionBadSystResponse
- {
- //if (syst() == FTPReply.NAME_SYSTEM_TYPE)
- // Technically, we should expect a NAME_SYSTEM_TYPE response, but
- // in practice FTP servers deviate, so we soften the condition to
- // a positive completion.
- if (__systemName == null && FTPReply.isPositiveCompletion(syst())) {
- __systemName = (getReplyStrings()[0]).substring(4);
- } else {
- throw new FtpExceptionBadSystResponse(
- "Bad response of SYST: " + getReplyString());
- }
-
- return __systemName;
+ return true;
+ }
+
+ /***
+ * Sets the file type to be transferred. This should be one of
+ * <code> FTP.ASCII_FILE_TYPE </code>, <code> FTP.IMAGE_FILE_TYPE </code>,
+ * etc. The file type only needs to be set when you want to change the type.
+ * After changing it, the new type stays in effect until you change it again.
+ * The default file type is <code> FTP.ASCII_FILE_TYPE </code> if this method
+ * is never called.
+ * <p>
+ *
+ * @param fileType
+ * The <code> _FILE_TYPE </code> constant indcating the type of file.
+ * @return True if successfully completed, false if not.
+ * @exception FTPConnectionClosedException
+ * If the FTP server prematurely closes the connection as a
+ * result of the client being idle or some other reason causing
+ * the server to send FTP reply code 421. This exception may be
+ * caught either as an IOException or independently as itself.
+ * @exception IOException
+ * If an I/O error occurs while either sending a command to the
+ * server or receiving a reply from the server.
+ ***/
+ public boolean setFileType(int fileType) throws IOException {
+ if (FTPReply.isPositiveCompletion(type(fileType))) {
+ /*
+ * __fileType = fileType; __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
+ */
+ return true;
}
-
- /***
- * Sends a NOOP command to the FTP server. This is useful for preventing
- * server timeouts.
- * <p>
- * @return True if successfully completed, false if not.
- * @exception FTPConnectionClosedException
- * If the FTP server prematurely closes the connection as a result
- * of the client being idle or some other reason causing the server
- * to send FTP reply code 421. This exception may be caught either
- * as an IOException or independently as itself.
- * @exception IOException If an I/O error occurs while either sending a
- * command to the server or receiving a reply from the server.
- ***/
- public boolean sendNoOp() throws IOException
- {
- return FTPReply.isPositiveCompletion(noop());
+ return false;
+ }
+
+ /***
+ * Fetches the system type name from the server and returns the string. This
+ * value is cached for the duration of the connection after the first call to
+ * this method. In other words, only the first time that you invoke this
+ * method will it issue a SYST command to the FTP server. FTPClient will
+ * remember the value and return the cached value until a call to disconnect.
+ * <p>
+ *
+ * @return The system type name obtained from the server. null if the
+ * information could not be obtained.
+ * @exception FTPConnectionClosedException
+ * If the FTP server prematurely closes the connection as a
+ * result of the client being idle or some other reason causing
+ * the server to send FTP reply code 421. This exception may be
+ * caught either as an IOException or independently as itself.
+ * @exception IOException
+ * If an I/O error occurs while either sending a command to the
+ * server or receiving a reply from the server.
+ ***/
+ public String getSystemName() throws IOException, FtpExceptionBadSystResponse {
+ // if (syst() == FTPReply.NAME_SYSTEM_TYPE)
+ // Technically, we should expect a NAME_SYSTEM_TYPE response, but
+ // in practice FTP servers deviate, so we soften the condition to
+ // a positive completion.
+ if (__systemName == null && FTPReply.isPositiveCompletion(syst())) {
+ __systemName = (getReplyStrings()[0]).substring(4);
+ } else {
+ throw new FtpExceptionBadSystResponse("Bad response of SYST: "
+ + getReplyString());
}
-// client.stat(path);
-// client.sendCommand("STAT");
-// client.sendCommand("STAT",path);
-// client.sendCommand("MDTM",path);
-// client.sendCommand("SIZE",path);
-// client.sendCommand("HELP","SITE");
-// client.sendCommand("SYST");
-// client.setRestartOffset(120);
+ return __systemName;
+ }
+
+ /***
+ * Sends a NOOP command to the FTP server. This is useful for preventing
+ * server timeouts.
+ * <p>
+ *
+ * @return True if successfully completed, false if not.
+ * @exception FTPConnectionClosedException
+ * If the FTP server prematurely closes the connection as a
+ * result of the client being idle or some other reason causing
+ * the server to send FTP reply code 421. This exception may be
+ * caught either as an IOException or independently as itself.
+ * @exception IOException
+ * If an I/O error occurs while either sending a command to the
+ * server or receiving a reply from the server.
+ ***/
+ public boolean sendNoOp() throws IOException {
+ return FTPReply.isPositiveCompletion(noop());
+ }
+
+ // client.stat(path);
+ // client.sendCommand("STAT");
+ // client.sendCommand("STAT",path);
+ // client.sendCommand("MDTM",path);
+ // client.sendCommand("SIZE",path);
+ // client.sendCommand("HELP","SITE");
+ // client.sendCommand("SYST");
+ // client.setRestartOffset(120);
}
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 351aa0c4c..9c16539eb 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
@@ -39,13 +39,12 @@ import java.net.URL;
import java.io.IOException;
/**
- * This class is a protocol plugin used for ftp: scheme.
- * It creates {@link FtpResponse} object and gets the content of the url from it.
+ * This class is a protocol plugin used for ftp: scheme. It creates
+ * {@link FtpResponse} object and gets the content of the url from it.
* Configurable parameters are {@code ftp.username}, {@code ftp.password},
- * {@code ftp.content.limit}, {@code ftp.timeout},
- * {@code ftp.server.timeout}, {@code ftp.password},
- * {@code ftp.keep.connection} and {@code ftp.follow.talk}.
- * For details see "FTP properties" section in {@code nutch-default.xml}.
+ * {@code ftp.content.limit}, {@code ftp.timeout}, {@code ftp.server.timeout},
+ * {@code ftp.password}, {@code ftp.keep.connection} and {@code ftp.follow.talk}
+ * . For details see "FTP properties" section in {@code nutch-default.xml}.
*/
public class Ftp implements Protocol {
@@ -60,7 +59,7 @@ public class Ftp implements Protocol {
int maxContentLength;
String userName;
- String passWord;
+ String passWord;
// typical/default server timeout is 120*1000 millisec.
// better be conservative here
@@ -107,12 +106,14 @@ public class Ftp implements Protocol {
this.keepConnection = keepConnection;
}
- /**
- * Creates a {@link FtpResponse} object corresponding to the url and
- * returns a {@link ProtocolOutput} object as per the content received
+ /**
+ * Creates a {@link FtpResponse} object corresponding to the url and returns a
+ * {@link ProtocolOutput} object as per the content received
*
- * @param url Text containing the ftp url
- * @param datum The CrawlDatum object corresponding to the url
+ * @param url
+ * Text containing the ftp url
+ * @param datum
+ * The CrawlDatum object corresponding to the url
*
* @return {@link ProtocolOutput} object for the url
*/
@@ -120,36 +121,36 @@ public class Ftp implements Protocol {
String urlString = url.toString();
try {
URL u = new URL(urlString);
-
+
int redirects = 0;
-
+
while (true) {
FtpResponse response;
- response = new FtpResponse(u, datum, this, getConf()); // make a request
-
+ response = new FtpResponse(u, datum, this, getConf()); // make a request
+
int code = response.getCode();
-
- if (code == 200) { // got a good response
- return new ProtocolOutput(response.toContent()); // return it
-
- } else if (code >= 300 && code < 400) { // handle redirect
+
+ if (code == 200) { // got a good response
+ return new ProtocolOutput(response.toContent()); // return it
+
+ } else if (code >= 300 && code < 400) { // handle redirect
if (redirects == MAX_REDIRECTS)
throw new FtpException("Too many redirects: " + url);
u = new URL(response.getHeader("Location"));
- redirects++;
+ redirects++;
if (LOG.isTraceEnabled()) {
- LOG.trace("redirect to " + u);
+ LOG.trace("redirect to " + u);
}
- } else { // convert to exception
+ } else { // convert to exception
throw new FtpError(code);
}
- }
+ }
} catch (Exception e) {
return new ProtocolOutput(null, new ProtocolStatus(e));
}
}
- protected void finalize () {
+ protected void finalize() {
try {
if (this.client != null && this.client.isConnected()) {
this.client.logout();
@@ -176,7 +177,7 @@ public class Ftp implements Protocol {
System.err.println(usage);
System.exit(-1);
}
-
+
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-logLevel")) {
logLevel = args[++i];
@@ -190,7 +191,7 @@ public class Ftp implements Protocol {
maxContentLength = Integer.parseInt(args[++i]);
} else if (args[i].equals("-dumpContent")) {
dumpContent = true;
- } else if (i != args.length-1) {
+ } else if (i != args.length - 1) {
System.err.println(usage);
System.exit(-1);
} else {
@@ -210,15 +211,16 @@ public class Ftp implements Protocol {
ftp.setMaxContentLength(maxContentLength);
// set log level
- //LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));
+ // LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));
- Content content = ftp.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
+ Content content = ftp.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
System.err.println("Content-Type: " + content.getContentType());
- System.err.println("Content-Length: " +
- content.getMetadata().get(Response.CONTENT_LENGTH));
- System.err.println("Last-Modified: " +
- content.getMetadata().get(Response.LAST_MODIFIED));
+ System.err.println("Content-Length: "
+ + content.getMetadata().get(Response.CONTENT_LENGTH));
+ System.err.println("Last-Modified: "
+ + content.getMetadata().get(Response.LAST_MODIFIED));
if (dumpContent) {
System.out.print(new String(content.getContent()));
}
@@ -248,7 +250,7 @@ public class Ftp implements Protocol {
return this.conf;
}
- /**
+ /**
* Get the robots rules for a given url
*/
public BaseRobotRules getRobotRules(Text url, CrawlDatum datum) {
@@ -259,4 +261,3 @@ public class Ftp implements Protocol {
return BUFFER_SIZE;
}
}
-
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpError.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpError.java
index c171dda54..b63a67ed5 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpError.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpError.java
@@ -17,13 +17,16 @@
package org.apache.nutch.protocol.ftp;
-/** Thrown for Ftp error codes.
+/**
+ * Thrown for Ftp error codes.
*/
public class FtpError extends FtpException {
private int code;
-
- public int getCode(int code) { return code; }
+
+ public int getCode(int code) {
+ return code;
+ }
public FtpError(int code) {
super("Ftp Error: " + code);
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpException.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpException.java
index 96d4cb991..5a29668fc 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpException.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpException.java
@@ -20,9 +20,9 @@ package org.apache.nutch.protocol.ftp;
import org.apache.nutch.protocol.ProtocolException;
/***
- * Superclass for important exceptions thrown during FTP talk,
- * that must be handled with care.
- *
+ * Superclass for important exceptions thrown during FTP talk, that must be
+ * handled with care.
+ *
* @author John Xing
*/
public class FtpException extends ProtocolException {
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionBadSystResponse.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionBadSystResponse.java
index 264df18b4..689ac8e69 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionBadSystResponse.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionBadSystResponse.java
@@ -19,7 +19,7 @@ package org.apache.nutch.protocol.ftp;
/**
* Exception indicating bad reply of SYST command.
- *
+ *
* @author John Xing
*/
public class FtpExceptionBadSystResponse extends FtpException {
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionCanNotHaveDataConnection.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionCanNotHaveDataConnection.java
index 7f4090600..9f35b740c 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionCanNotHaveDataConnection.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionCanNotHaveDataConnection.java
@@ -19,7 +19,7 @@ package org.apache.nutch.protocol.ftp;
/**
* Exception indicating failure of opening data connection.
- *
+ *
* @author John Xing
*/
public class FtpExceptionCanNotHaveDataConnection extends FtpException {
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionControlClosedByForcedDataClose.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionControlClosedByForcedDataClose.java
index 0d1fdcb1d..c058fcb7d 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionControlClosedByForcedDataClose.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionControlClosedByForcedDataClose.java
@@ -18,9 +18,9 @@
package org.apache.nutch.protocol.ftp;
/**
- * Exception indicating control channel is closed by server end, due to
- * forced closure of data channel at client (our) end.
- *
+ * Exception indicating control channel is closed by server end, due to forced
+ * closure of data channel at client (our) end.
+ *
* @author John Xing
*/
public class FtpExceptionControlClosedByForcedDataClose extends FtpException {
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionUnknownForcedDataClose.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionUnknownForcedDataClose.java
index a3a3f7795..9083d7cb3 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionUnknownForcedDataClose.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpExceptionUnknownForcedDataClose.java
@@ -18,9 +18,9 @@
package org.apache.nutch.protocol.ftp;
/**
- * Exception indicating unrecognizable reply from server after
- * forced closure of data channel by client (our) side.
- *
+ * Exception indicating unrecognizable reply from server after forced closure of
+ * data channel by client (our) side.
+ *
* @author John Xing
*/
public class FtpExceptionUnknownForcedDataClose extends FtpException {
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 283efd1bf..f7c7c6d12 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
@@ -37,15 +37,12 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
- * FtpResponse.java mimics ftp replies as http response.
- * It tries its best to follow http's way for headers, response codes
- * as well as exceptions.
- *
- * Comments:
- * In this class, all FtpException*.java thrown by Client.java
- * and some important commons-net exceptions passed by Client.java
- * must have been properly dealt with. They'd better not be leaked
- * to the caller of this class.
+ * FtpResponse.java mimics ftp replies as http response. It tries its best to
+ * follow http's way for headers, response codes as well as exceptions.
+ *
+ * Comments: In this class, all FtpException*.java thrown by Client.java and
+ * some important commons-net exceptions passed by Client.java must have been
+ * properly dealt with. They'd better not be leaked to the caller of this class.
*/
public class FtpResponse {
@@ -60,23 +57,26 @@ public class FtpResponse {
private Configuration conf;
/** Returns the response code. */
- public int getCode() { return code; }
+ public int getCode() {
+ return code;
+ }
/** Returns the value of a named header. */
public String getHeader(String name) {
return headers.get(name);
}
- public byte[] getContent() { return content; }
+ public byte[] getContent() {
+ return content;
+ }
public Content toContent() {
return new Content(orig, base, (content != null ? content : EMPTY_CONTENT),
- getHeader(Response.CONTENT_TYPE),
- headers, this.conf);
+ getHeader(Response.CONTENT_TYPE), headers, this.conf);
}
public FtpResponse(URL url, CrawlDatum datum, Ftp ftp, Configuration conf)
- throws FtpException, IOException {
+ throws FtpException, IOException {
this.orig = url.toString();
this.base = url.toString();
@@ -98,17 +98,16 @@ public class FtpResponse {
if (ftp.followTalk) {
if (Ftp.LOG.isInfoEnabled()) {
- Ftp.LOG.info("fetching "+url);
+ Ftp.LOG.info("fetching " + url);
}
} else {
if (Ftp.LOG.isTraceEnabled()) {
- Ftp.LOG.trace("fetching "+url);
+ Ftp.LOG.trace("fetching " + url);
}
}
InetAddress addr = InetAddress.getByName(url.getHost());
- if (addr != null
- && conf.getBoolean("store.ip.address", false) == true) {
+ if (addr != null && conf.getBoolean("store.ip.address", false) == true) {
headers.add("_ip_", addr.getHostAddress());
}
@@ -116,7 +115,7 @@ public class FtpResponse {
// should start anew.
if (ftp.client != null && ftp.keepConnection
&& ftp.renewalTime < System.currentTimeMillis()) {
- if (Ftp.LOG.isInfoEnabled()) {
+ if (Ftp.LOG.isInfoEnabled()) {
Ftp.LOG.info("delete client because idled too long");
}
ftp.client = null;
@@ -130,8 +129,9 @@ public class FtpResponse {
// the real client
ftp.client = new Client();
// when to renew, take the lesser
- //ftp.renewalTime = System.currentTimeMillis()
- // + ((ftp.timeout<ftp.serverTimeout) ? ftp.timeout : ftp.serverTimeout);
+ // ftp.renewalTime = System.currentTimeMillis()
+ // + ((ftp.timeout<ftp.serverTimeout) ? ftp.timeout :
+ // ftp.serverTimeout);
// timeout for control connection
ftp.client.setDefaultTimeout(ftp.timeout);
@@ -140,8 +140,8 @@ public class FtpResponse {
// follow ftp talk?
if (ftp.followTalk)
- ftp.client.addProtocolCommandListener(
- new PrintCommandListener(Ftp.LOG));
+ ftp.client.addProtocolCommandListener(new PrintCommandListener(
+ Ftp.LOG));
}
// quit from previous site if at a different site now
@@ -149,8 +149,8 @@ public class FtpResponse {
InetAddress remoteAddress = ftp.client.getRemoteAddress();
if (!addr.equals(remoteAddress)) {
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("disconnect from "+remoteAddress
- +" before connect to "+addr);
+ Ftp.LOG.info("disconnect from " + remoteAddress
+ + " before connect to " + addr);
}
// quit from current site
ftp.client.logout();
@@ -162,22 +162,22 @@ public class FtpResponse {
if (!ftp.client.isConnected()) {
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("connect to "+addr);
+ Ftp.LOG.info("connect to " + addr);
}
ftp.client.connect(addr);
if (!FTPReply.isPositiveCompletion(ftp.client.getReplyCode())) {
ftp.client.disconnect();
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.client.connect() failed: "
- + addr + " " + ftp.client.getReplyString());
+ Ftp.LOG.warn("ftp.client.connect() failed: " + addr + " "
+ + ftp.client.getReplyString());
}
this.code = 500; // http Internal Server Error
return;
}
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("log into "+addr);
+ Ftp.LOG.info("log into " + addr);
}
if (!ftp.client.login(ftp.userName, ftp.passWord)) {
@@ -188,9 +188,9 @@ public class FtpResponse {
// (not dealt with here at all) .
ftp.client.disconnect();
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.client.login() failed: "+addr);
+ Ftp.LOG.warn("ftp.client.login() failed: " + addr);
}
- this.code = 401; // http Unauthorized
+ this.code = 401; // http Unauthorized
return;
}
@@ -199,14 +199,14 @@ public class FtpResponse {
ftp.client.logout();
ftp.client.disconnect();
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.client.setFileType() failed: "+addr);
+ Ftp.LOG.warn("ftp.client.setFileType() failed: " + addr);
}
this.code = 500; // http Internal Server Error
return;
}
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("set parser for "+addr);
+ Ftp.LOG.info("set parser for " + addr);
}
// SYST is valid only after login
@@ -217,17 +217,18 @@ public class FtpResponse {
if (parserKey.startsWith("UNKNOWN Type: L8"))
parserKey = "UNIX Type: L8";
ftp.parser = (new DefaultFTPFileEntryParserFactory())
- .createFileEntryParser(parserKey);
+ .createFileEntryParser(parserKey);
} catch (FtpExceptionBadSystResponse e) {
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.client.getSystemName() failed: "+addr+" "+e);
+ Ftp.LOG
+ .warn("ftp.client.getSystemName() failed: " + addr + " " + e);
}
ftp.parser = null;
} catch (ParserInitializationException e) {
// ParserInitializationException is RuntimeException defined in
// org.apache.commons.net.ftp.parser.ParserInitializationException
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("createFileEntryParser() failed. "+addr+" "+e);
+ Ftp.LOG.warn("createFileEntryParser() failed. " + addr + " " + e);
}
ftp.parser = null;
} finally {
@@ -235,7 +236,7 @@ public class FtpResponse {
// do not log as severe, otherwise
// FetcherThread/RequestScheduler will abort
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.parser is null: "+addr);
+ Ftp.LOG.warn("ftp.parser is null: " + addr);
}
ftp.client.logout();
ftp.client.disconnect();
@@ -261,10 +262,11 @@ public class FtpResponse {
// reset next renewalTime, take the lesser
if (ftp.client != null && ftp.keepConnection) {
ftp.renewalTime = System.currentTimeMillis()
- + ((ftp.timeout<ftp.serverTimeout) ? ftp.timeout : ftp.serverTimeout);
+ + ((ftp.timeout < ftp.serverTimeout) ? ftp.timeout
+ : ftp.serverTimeout);
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
Ftp.LOG.info("reset renewalTime to "
- + HttpDateFormat.toString(ftp.renewalTime));
+ + HttpDateFormat.toString(ftp.renewalTime));
}
}
@@ -272,12 +274,12 @@ public class FtpResponse {
// may have deleted ftp.client
if (ftp.client != null && !ftp.keepConnection) {
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("disconnect from "+addr);
+ Ftp.LOG.info("disconnect from " + addr);
}
ftp.client.logout();
ftp.client.disconnect();
}
-
+
} catch (Exception e) {
if (Ftp.LOG.isWarnEnabled()) {
Ftp.LOG.warn("Error: ", e);
@@ -290,21 +292,21 @@ public class FtpResponse {
ftp.client = null;
// or do explicit garbage collection?
// System.gc();
-// can we be less dramatic, using the following instead?
-// probably unnecessary for our practical purpose here
-// try {
-// ftp.client.logout();
-// ftp.client.disconnect();
-// }
+ // can we be less dramatic, using the following instead?
+ // probably unnecessary for our practical purpose here
+ // try {
+ // ftp.client.logout();
+ // ftp.client.disconnect();
+ // }
throw new FtpException(e);
- //throw e;
+ // throw e;
}
}
// get ftp file as http response
private void getFileAsHttpResponse(String path, long lastModified)
- throws IOException {
+ throws IOException {
ByteArrayOutputStream os = null;
List<FTPFile> list = null;
@@ -316,9 +318,9 @@ public class FtpResponse {
FTPFile ftpFile = (FTPFile) list.get(0);
this.headers.set(Response.CONTENT_LENGTH,
- new Long(ftpFile.getSize()).toString());
+ new Long(ftpFile.getSize()).toString());
this.headers.set(Response.LAST_MODIFIED,
- HttpDateFormat.toString(ftpFile.getTimestamp()));
+ HttpDateFormat.toString(ftpFile.getTimestamp()));
// don't retrieve the file if not changed.
if (ftpFile.getTimestamp().getTimeInMillis() <= lastModified) {
code = 304;
@@ -329,11 +331,11 @@ public class FtpResponse {
this.content = os.toByteArray();
-// // approximate bytes sent and read
-// if (this.httpAccounting != null) {
-// this.httpAccounting.incrementBytesSent(path.length());
-// this.httpAccounting.incrementBytesRead(this.content.length);
-// }
+ // // approximate bytes sent and read
+ // if (this.httpAccounting != null) {
+ // this.httpAccounting.incrementBytesSent(path.length());
+ // this.httpAccounting.incrementBytesRead(this.content.length);
+ // }
this.code = 200; // http OK
@@ -342,64 +344,64 @@ public class FtpResponse {
// control connection is off, clean up
// ftp.client.disconnect();
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("delete client because server cut off control channel: "+e);
+ Ftp.LOG.info("delete client because server cut off control channel: "
+ + e);
}
ftp.client = null;
// in case this FtpExceptionControlClosedByForcedDataClose is
// thrown by retrieveList() (not retrieveFile()) above,
if (os == null) { // indicating throwing by retrieveList()
- //throw new FtpException("fail to get attibutes: "+path);
+ // throw new FtpException("fail to get attibutes: "+path);
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn(
- "Please try larger maxContentLength for ftp.client.retrieveList(). "
- + e);
+ Ftp.LOG
+ .warn("Please try larger maxContentLength for ftp.client.retrieveList(). "
+ + e);
}
// in a way, this is our request fault
- this.code = 400; // http Bad request
+ this.code = 400; // http Bad request
return;
}
FTPFile ftpFile = (FTPFile) list.get(0);
this.headers.set(Response.CONTENT_LENGTH,
- new Long(ftpFile.getSize()).toString());
- //this.headers.put("content-type", "text/html");
+ new Long(ftpFile.getSize()).toString());
+ // this.headers.put("content-type", "text/html");
this.headers.set(Response.LAST_MODIFIED,
- HttpDateFormat.toString(ftpFile.getTimestamp()));
+ HttpDateFormat.toString(ftpFile.getTimestamp()));
this.content = os.toByteArray();
if (ftpFile.getTimestamp().getTimeInMillis() <= lastModified) {
code = 304;
return;
}
-// // approximate bytes sent and read
-// if (this.httpAccounting != null) {
-// this.httpAccounting.incrementBytesSent(path.length());
-// this.httpAccounting.incrementBytesRead(this.content.length);
-// }
+ // // approximate bytes sent and read
+ // if (this.httpAccounting != null) {
+ // this.httpAccounting.incrementBytesSent(path.length());
+ // this.httpAccounting.incrementBytesRead(this.content.length);
+ // }
this.code = 200; // http OK
} catch (FtpExceptionCanNotHaveDataConnection e) {
if (FTPReply.isPositiveCompletion(ftp.client.cwd(path))) {
- // it is not a file, but dir, so redirect as a dir
+ // it is not a file, but dir, so redirect as a dir
this.headers.set(Response.LOCATION, path + "/");
- this.code = 300; // http redirect
+ this.code = 300; // http redirect
// fixme, should we do ftp.client.cwd("/"), back to top dir?
} else {
- // it is not a dir either
- this.code = 404; // http Not Found
+ // it is not a dir either
+ this.code = 404; // http Not Found
}
} catch (FtpExceptionUnknownForcedDataClose e) {
// Please note control channel is still live.
// in a way, this is our request fault
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn(
- "Unrecognized reply after forced close of data channel. "
- + "If this is acceptable, please modify Client.java accordingly. "
- + e);
+ Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
+ + "If this is acceptable, please modify Client.java accordingly. "
+ + e);
}
this.code = 400; // http Bad Request
}
@@ -408,14 +410,14 @@ public class FtpResponse {
// get ftp dir list as http response
private void getDirAsHttpResponse(String path, long lastModified)
- throws IOException {
+ throws IOException {
List<FTPFile> list = new LinkedList<FTPFile>();
try {
// change to that dir first
if (!FTPReply.isPositiveCompletion(ftp.client.cwd(path))) {
- this.code = 404; // http Not Found
+ this.code = 404; // http Not Found
return;
}
@@ -424,15 +426,15 @@ public class FtpResponse {
ftp.client.retrieveList(null, list, ftp.maxContentLength, ftp.parser);
this.content = list2html(list, path, "/".equals(path) ? false : true);
this.headers.set(Response.CONTENT_LENGTH,
- new Integer(this.content.length).toString());
+ new Integer(this.content.length).toString());
this.headers.set(Response.CONTENT_TYPE, "text/html");
// this.headers.put("Last-Modified", null);
-// // approximate bytes sent and read
-// if (this.httpAccounting != null) {
-// this.httpAccounting.incrementBytesSent(path.length());
-// this.httpAccounting.incrementBytesRead(this.content.length);
-// }
+ // // approximate bytes sent and read
+ // if (this.httpAccounting != null) {
+ // this.httpAccounting.incrementBytesSent(path.length());
+ // this.httpAccounting.incrementBytesRead(this.content.length);
+ // }
this.code = 200; // http OK
@@ -441,21 +443,22 @@ public class FtpResponse {
// control connection is off, clean up
// ftp.client.disconnect();
if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("delete client because server cut off control channel: "+e);
+ Ftp.LOG.info("delete client because server cut off control channel: "
+ + e);
}
ftp.client = null;
this.content = list2html(list, path, "/".equals(path) ? false : true);
this.headers.set(Response.CONTENT_LENGTH,
- new Integer(this.content.length).toString());
+ new Integer(this.content.length).toString());
this.headers.set(Response.CONTENT_TYPE, "text/html");
// this.headers.put("Last-Modified", null);
-// // approximate bytes sent and read
-// if (this.httpAccounting != null) {
-// this.httpAccounting.incrementBytesSent(path.length());
-// this.httpAccounting.incrementBytesRead(this.content.length);
-// }
+ // // approximate bytes sent and read
+ // if (this.httpAccounting != null) {
+ // this.httpAccounting.incrementBytesSent(path.length());
+ // this.httpAccounting.incrementBytesRead(this.content.length);
+ // }
this.code = 200; // http OK
@@ -463,32 +466,35 @@ public class FtpResponse {
// Please note control channel is still live.
// in a way, this is our request fault
if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn(
- "Unrecognized reply after forced close of data channel. "
- + "If this is acceptable, please modify Client.java accordingly. "
- + e);
+ Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
+ + "If this is acceptable, please modify Client.java accordingly. "
+ + e);
}
this.code = 400; // http Bad Request
} catch (FtpExceptionCanNotHaveDataConnection e) {
- if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn(""+ e); }
+ if (Ftp.LOG.isWarnEnabled()) {
+ Ftp.LOG.warn("" + e);
+ }
this.code = 500; // http Iternal Server Error
}
}
// generate html page from ftp dir list
- private byte[] list2html(List<FTPFile> list, String path, boolean includeDotDot) {
+ private byte[] list2html(List<FTPFile> list, String path,
+ boolean includeDotDot) {
- //StringBuffer x = new StringBuffer("<!doctype html public \"-//ietf//dtd html//en\"><html><head>");
+ // StringBuffer x = new
+ // StringBuffer("<!doctype html public \"-//ietf//dtd html//en\"><html><head>");
StringBuffer x = new StringBuffer("<html><head>");
- x.append("<title>Index of "+path+"</title></head>\n");
- x.append("<body><h1>Index of "+path+"</h1><pre>\n");
+ x.append("<title>Index of " + path + "</title></head>\n");
+ x.append("<body><h1>Index of " + path + "</h1><pre>\n");
if (includeDotDot) {
x.append("<a href='../'>../</a>\t-\t-\t-\n");
}
- for (int i=0; i<list.size(); i++) {
+ for (int i = 0; i < list.size(); i++) {
FTPFile f = (FTPFile) list.get(i);
String name = f.getName();
String time = HttpDateFormat.toString(f.getTimestamp());
@@ -496,11 +502,11 @@ public class FtpResponse {
// some ftp server LIST "." and "..", we skip them here
if (name.equals(".") || name.equals(".."))
continue;
- x.append("<a href='"+name+"/"+"'>"+name+"/</a>\t");
- x.append(time+"\t-\n");
+ x.append("<a href='" + name + "/" + "'>" + name + "/</a>\t");
+ x.append(time + "\t-\n");
} else if (f.isFile()) {
- x.append("<a href='"+name+ "'>"+name+"</a>\t");
- x.append(time+"\t"+f.getSize()+"\n");
+ x.append("<a href='" + name + "'>" + name + "</a>\t");
+ x.append(time + "\t" + f.getSize() + "\n");
} else {
// ignore isSymbolicLink()
// ignore isUnknown()
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
index 7a78bf8a3..93e375249 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
@@ -33,55 +33,62 @@ import crawlercommons.robots.BaseRobotRules;
import crawlercommons.robots.SimpleRobotRules;
/**
- * This class is used for parsing robots for urls belonging to FTP protocol.
- * It extends the generic {@link RobotRulesParser} class and contains
- * Ftp protocol specific implementation for obtaining the robots file.
+ * This class is used for parsing robots for urls belonging to FTP protocol. It
+ * extends the generic {@link RobotRulesParser} class and contains Ftp protocol
+ * specific implementation for obtaining the robots file.
*/
public class FtpRobotRulesParser extends RobotRulesParser {
private static final String CONTENT_TYPE = "text/plain";
- public static final Logger LOG = LoggerFactory.getLogger(FtpRobotRulesParser.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(FtpRobotRulesParser.class);
- FtpRobotRulesParser() { }
+ FtpRobotRulesParser() {
+ }
public FtpRobotRulesParser(Configuration conf) {
super(conf);
}
/**
- * The hosts for which the caching of robots rules is yet to be done,
- * it sends a Ftp request to the host corresponding to the {@link URL}
- * passed, gets robots file, parses the rules and caches the rules object
- * to avoid re-work in future.
+ * The hosts for which the caching of robots rules is yet to be done, it sends
+ * a Ftp request to the host corresponding to the {@link URL} passed, gets
+ * robots file, parses the rules and caches the rules object to avoid re-work
+ * in future.
+ *
+ * @param ftp
+ * The {@link Protocol} object
+ * @param url
+ * URL
*
- * @param ftp The {@link Protocol} object
- * @param url URL
- *
- * @return robotRules A {@link BaseRobotRules} object for the rules
+ * @return robotRules A {@link BaseRobotRules} object for the rules
*/
public BaseRobotRules getRobotRulesSet(Protocol ftp, URL url) {
- String protocol = url.getProtocol().toLowerCase(); // normalize to lower case
- String host = url.getHost().toLowerCase(); // normalize to lower case
+ String protocol = url.getProtocol().toLowerCase(); // normalize to lower
+ // case
+ String host = url.getHost().toLowerCase(); // normalize to lower case
- BaseRobotRules robotRules = (SimpleRobotRules) CACHE.get(protocol + ":" + host);
+ BaseRobotRules robotRules = (SimpleRobotRules) CACHE.get(protocol + ":"
+ + host);
boolean cacheRule = true;
- if (robotRules == null) { // cache miss
+ if (robotRules == null) { // cache miss
if (LOG.isTraceEnabled())
LOG.trace("cache miss " + url);
try {
Text robotsUrl = new Text(new URL(url, "/robots.txt").toString());
- ProtocolOutput output = ((Ftp)ftp).getProtocolOutput(robotsUrl, new CrawlDatum());
+ ProtocolOutput output = ((Ftp) ftp).getProtocolOutput(robotsUrl,
+ new CrawlDatum());
ProtocolStatus status = output.getStatus();
if (status.getCode() == ProtocolStatus.SUCCESS) {
- robotRules = parseRules(url.toString(), output.getContent().getContent(),
- CONTENT_TYPE, agentNames);
- } else {
- robotRules = EMPTY_RULES; // use default rules
+ robotRules = parseRules(url.toString(), output.getContent()
+ .getContent(), CONTENT_TYPE, agentNames);
+ } else {
+ robotRules = EMPTY_RULES; // use default rules
}
} catch (Throwable t) {
if (LOG.isInfoEnabled()) {
@@ -92,7 +99,7 @@ public class FtpRobotRulesParser extends RobotRulesParser {
}
if (cacheRule)
- CACHE.put(protocol + ":" + host, robotRules); // cache rules for host
+ CACHE.put(protocol + ":" + host, robotRules); // cache rules for host
}
return robotRules;
}
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/PrintCommandListener.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/PrintCommandListener.java
index af1e7b2af..c68eac85f 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/PrintCommandListener.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/PrintCommandListener.java
@@ -28,45 +28,44 @@ import org.apache.commons.net.ProtocolCommandListener;
/***
* This is a support class for logging all ftp command/reply traffic.
- *
+ *
* @author John Xing
***/
-public class PrintCommandListener implements ProtocolCommandListener
-{
- private Logger __logger;
+public class PrintCommandListener implements ProtocolCommandListener {
+ private Logger __logger;
- public PrintCommandListener(Logger logger)
- {
- __logger = logger;
- }
+ public PrintCommandListener(Logger logger) {
+ __logger = logger;
+ }
- public void protocolCommandSent(ProtocolCommandEvent event) {
- try {
- __logIt(event);
- } catch (IOException e) {
- if (__logger.isInfoEnabled()) {
- __logger.info("PrintCommandListener.protocolCommandSent(): "+e);
- }
+ public void protocolCommandSent(ProtocolCommandEvent event) {
+ try {
+ __logIt(event);
+ } catch (IOException e) {
+ if (__logger.isInfoEnabled()) {
+ __logger.info("PrintCommandListener.protocolCommandSent(): " + e);
}
}
+ }
- public void protocolReplyReceived(ProtocolCommandEvent event) {
- try {
- __logIt(event);
- } catch (IOException e) {
- if (__logger.isInfoEnabled()) {
- __logger.info("PrintCommandListener.protocolReplyReceived(): "+e);
- }
+ public void protocolReplyReceived(ProtocolCommandEvent event) {
+ try {
+ __logIt(event);
+ } catch (IOException e) {
+ if (__logger.isInfoEnabled()) {
+ __logger.info("PrintCommandListener.protocolReplyReceived(): " + e);
}
}
+ }
- private void __logIt(ProtocolCommandEvent event) throws IOException {
- if (!__logger.isInfoEnabled()) { return; }
- BufferedReader br =
- new BufferedReader(new StringReader(event.getMessage()));
- String line;
- while ((line = br.readLine()) != null) {
- __logger.info("ftp> "+line);
- }
+ private void __logIt(ProtocolCommandEvent event) throws IOException {
+ if (!__logger.isInfoEnabled()) {
+ return;
+ }
+ BufferedReader br = new BufferedReader(new StringReader(event.getMessage()));
+ String line;
+ while ((line = br.readLine()) != null) {
+ __logger.info("ftp> " + line);
}
+ }
}
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 d96ee3a5d..56f9f4f80 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
@@ -34,12 +34,10 @@ import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.protocol.http.api.HttpBase;
import org.apache.nutch.util.NutchConfiguration;
-
public class Http extends HttpBase {
public static final Logger LOG = LoggerFactory.getLogger(Http.class);
-
/**
* Public default constructor.
*/
@@ -48,17 +46,17 @@ public class Http extends HttpBase {
}
/**
- * Set the {@link org.apache.hadoop.conf.Configuration}
- * object.
+ * Set the {@link org.apache.hadoop.conf.Configuration} object.
+ *
* @param conf
*/
public void setConf(Configuration conf) {
super.setConf(conf);
-// Level logLevel = Level.WARNING;
-// if (conf.getBoolean("http.verbose", false)) {
-// logLevel = Level.FINE;
-// }
-// LOG.setLevel(logLevel);
+ // Level logLevel = Level.WARNING;
+ // if (conf.getBoolean("http.verbose", false)) {
+ // logLevel = Level.FINE;
+ // }
+ // LOG.setLevel(logLevel);
}
public static void main(String[] args) throws Exception {
@@ -68,7 +66,7 @@ public class Http extends HttpBase {
}
protected Response getResponse(URL url, CrawlDatum datum, boolean redirect)
- throws ProtocolException, IOException {
+ throws ProtocolException, IOException {
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 5bb5aec4d..e3298028d 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
@@ -45,23 +45,23 @@ import org.apache.nutch.protocol.http.api.HttpException;
/** An HTTP response. */
public class HttpResponse implements Response {
-
+
private Configuration conf;
- private HttpBase http;
+ private HttpBase http;
private URL url;
private String orig;
private String base;
private byte[] content;
private int code;
private Metadata headers = new SpellCheckedMetadata();
-
+
protected enum Scheme {
- HTTP,
- HTTPS,
+ HTTP, HTTPS,
}
/**
* Default public constructor.
+ *
* @param http
* @param url
* @param datum
@@ -69,15 +69,15 @@ public class HttpResponse implements Response {
* @throws IOException
*/
public HttpResponse(HttpBase http, URL url, CrawlDatum datum)
- throws ProtocolException, IOException {
+ throws ProtocolException, IOException {
this.http = http;
this.url = url;
this.orig = url.toString();
this.base = url.toString();
-
+
Scheme scheme = null;
-
+
if ("http".equals(url.getProtocol())) {
scheme = Scheme.HTTP;
} else if ("https".equals(url.getProtocol())) {
@@ -105,44 +105,49 @@ public class HttpResponse implements Response {
} else {
port = 443;
}
- portString= "";
+ portString = "";
} else {
- port= url.getPort();
- portString= ":" + port;
+ port = url.getPort();
+ portString = ":" + port;
}
Socket socket = null;
try {
- socket = new Socket(); // create the socket
+ socket = new Socket(); // create the socket
socket.setSoTimeout(http.getTimeout());
-
// connect
String sockHost = http.useProxy() ? http.getProxyHost() : host;
int sockPort = http.useProxy() ? http.getProxyPort() : port;
- InetSocketAddress sockAddr= new InetSocketAddress(sockHost, sockPort);
+ InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
socket.connect(sockAddr, http.getTimeout());
-
+
if (scheme == Scheme.HTTPS) {
- SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
- SSLSocket sslsocket = (SSLSocket)factory.createSocket(socket, sockHost, sockPort, true);
+ SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory
+ .getDefault();
+ SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket,
+ sockHost, sockPort, true);
sslsocket.setUseClientMode(true);
-
- // Get the protocols and ciphers supported by this JVM
- Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
- Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));
-
+
+ // Get the protocols and ciphers supported by this JVM
+ Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket
+ .getSupportedProtocols()));
+ Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket
+ .getSupportedCipherSuites()));
+
// Intersect with preferred protocols and ciphers
protocols.retainAll(http.getTlsPreferredProtocols());
ciphers.retainAll(http.getTlsPreferredCipherSuites());
-
- sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
- sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));
-
+
+ sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols
+ .size()]));
+ sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers
+ .size()]));
+
sslsocket.startHandshake();
socket = sslsocket;
}
-
+
this.conf = http.getConf();
if (sockAddr != null
&& conf.getBoolean("store.ip.address", false) == true) {
@@ -154,9 +159,9 @@ public class HttpResponse implements Response {
StringBuffer reqStr = new StringBuffer("GET ");
if (http.useProxy()) {
- reqStr.append(url.getProtocol()+"://"+host+portString+path);
+ reqStr.append(url.getProtocol() + "://" + host + portString + path);
} else {
- reqStr.append(path);
+ reqStr.append(path);
}
reqStr.append(" HTTP/1.0\r\n");
@@ -170,7 +175,9 @@ public class HttpResponse implements Response {
String userAgent = http.getUserAgent();
if ((userAgent == null) || (userAgent.length() == 0)) {
- if (Http.LOG.isErrorEnabled()) { Http.LOG.error("User-agent is not set!"); }
+ if (Http.LOG.isErrorEnabled()) {
+ Http.LOG.error("User-agent is not set!");
+ }
} else {
reqStr.append("User-Agent: ");
reqStr.append(userAgent);
@@ -186,30 +193,30 @@ public class HttpResponse implements Response {
reqStr.append("\r\n");
if (datum.getModifiedTime() > 0) {
- reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(datum.getModifiedTime()));
+ reqStr.append("If-Modified-Since: "
+ + HttpDateFormat.toString(datum.getModifiedTime()));
reqStr.append("\r\n");
}
reqStr.append("\r\n");
-
- byte[] reqBytes= reqStr.toString().getBytes();
+
+ byte[] reqBytes = reqStr.toString().getBytes();
req.write(reqBytes);
req.flush();
-
- PushbackInputStream in = // process response
- new PushbackInputStream(
- new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE),
- Http.BUFFER_SIZE) ;
+
+ PushbackInputStream in = // process response
+ new PushbackInputStream(new BufferedInputStream(socket.getInputStream(),
+ Http.BUFFER_SIZE), Http.BUFFER_SIZE);
StringBuffer line = new StringBuffer();
- boolean haveSeenNonContinueStatus= false;
+ boolean haveSeenNonContinueStatus = false;
while (!haveSeenNonContinueStatus) {
// parse status code line
- this.code = parseStatusLine(in, line);
+ this.code = parseStatusLine(in, line);
// parse headers
parseHeaders(in, line);
- haveSeenNonContinueStatus= code != 100; // 100 is "Continue"
+ haveSeenNonContinueStatus = code != 100; // 100 is "Continue"
}
String transferEncoding = getHeader(Response.TRANSFER_ENCODING);
if (transferEncoding != null
@@ -223,7 +230,7 @@ public class HttpResponse implements Response {
if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
content = http.processGzipEncoded(content, url);
} else if ("deflate".equals(contentEncoding)) {
- content = http.processDeflateEncoded(content, url);
+ content = http.processDeflateEncoded(content, url);
} else {
if (Http.LOG.isTraceEnabled()) {
Http.LOG.trace("fetched " + content.length + " bytes from " + url);
@@ -237,15 +244,15 @@ public class HttpResponse implements Response {
}
-
- /* ------------------------- *
- * <implementation:Response> *
- * ------------------------- */
-
+ /*
+ * ------------------------- * <implementation:Response> *
+ * -------------------------
+ */
+
public URL getUrl() {
return url;
}
-
+
public int getCode() {
return code;
}
@@ -253,7 +260,7 @@ public class HttpResponse implements Response {
public String getHeader(String name) {
return headers.get(name);
}
-
+
public Metadata getHeaders() {
return headers;
}
@@ -262,39 +269,40 @@ public class HttpResponse implements Response {
return content;
}
- /* ------------------------- *
- * <implementation:Response> *
- * ------------------------- */
-
+ /*
+ * ------------------------- * <implementation:Response> *
+ * -------------------------
+ */
- private void readPlainContent(InputStream in)
- throws HttpException, IOException {
+ private void readPlainContent(InputStream in) throws HttpException,
+ IOException {
- int contentLength = Integer.MAX_VALUE; // get content length
+ int contentLength = Integer.MAX_VALUE; // get content length
String contentLengthString = headers.get(Response.CONTENT_LENGTH);
if (contentLengthString != null) {
contentLengthString = contentLengthString.trim();
try {
- if (!contentLengthString.isEmpty())
+ if (!contentLengthString.isEmpty())
contentLength = Integer.parseInt(contentLengthString);
} catch (NumberFormatException e) {
- throw new HttpException("bad content length: "+contentLengthString);
+ throw new HttpException("bad content length: " + contentLengthString);
}
}
- if (http.getMaxContent() >= 0
- && contentLength > http.getMaxContent()) // limit download size
- contentLength = http.getMaxContent();
+ 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];
int length = 0;
-
+
// do not try to read if the contentLength is 0
- if (contentLength == 0){
+ if (contentLength == 0) {
content = new byte[0];
return;
}
-
+
// read content
int i = in.read(bytes);
while (i != -1) {
@@ -322,11 +330,10 @@ public class HttpResponse implements Response {
* @throws IOException
*/
@SuppressWarnings("unused")
- private void readChunkedContent(PushbackInputStream in,
- StringBuffer line)
- throws HttpException, IOException {
- boolean doneChunks= false;
- int contentBytesRead= 0;
+ private void readChunkedContent(PushbackInputStream in, StringBuffer line)
+ throws HttpException, IOException {
+ boolean doneChunks = false;
+ int contentBytesRead = 0;
byte[] bytes = new byte[Http.BUFFER_SIZE];
ByteArrayOutputStream out = new ByteArrayOutputStream(Http.BUFFER_SIZE);
@@ -338,51 +345,54 @@ public class HttpResponse implements Response {
readLine(in, line, false);
String chunkLenStr;
- // if (LOG.isTraceEnabled()) { LOG.trace("chunk-header: '" + line + "'"); }
+ // if (LOG.isTraceEnabled()) { LOG.trace("chunk-header: '" + line + "'");
+ // }
- int pos= line.indexOf(";");
+ int pos = line.indexOf(";");
if (pos < 0) {
- chunkLenStr= line.toString();
+ chunkLenStr = line.toString();
} else {
- chunkLenStr= line.substring(0, pos);
- // if (LOG.isTraceEnabled()) { LOG.trace("got chunk-ext: " + line.substring(pos+1)); }
+ chunkLenStr = line.substring(0, pos);
+ // if (LOG.isTraceEnabled()) { LOG.trace("got chunk-ext: " +
+ // line.substring(pos+1)); }
}
- chunkLenStr= chunkLenStr.trim();
+ chunkLenStr = chunkLenStr.trim();
int chunkLen;
try {
- chunkLen= Integer.parseInt(chunkLenStr, 16);
- } catch (NumberFormatException e){
- throw new HttpException("bad chunk length: "+line.toString());
+ chunkLen = Integer.parseInt(chunkLenStr, 16);
+ } catch (NumberFormatException e) {
+ throw new HttpException("bad chunk length: " + line.toString());
}
if (chunkLen == 0) {
- doneChunks= true;
+ doneChunks = true;
break;
}
- if ( http.getMaxContent() >= 0 && (contentBytesRead + chunkLen) > http.getMaxContent() )
- chunkLen= http.getMaxContent() - contentBytesRead;
+ if (http.getMaxContent() >= 0
+ && (contentBytesRead + chunkLen) > http.getMaxContent())
+ chunkLen = http.getMaxContent() - contentBytesRead;
// read one chunk
- int chunkBytesRead= 0;
+ int chunkBytesRead = 0;
while (chunkBytesRead < chunkLen) {
- int toRead= (chunkLen - chunkBytesRead) < Http.BUFFER_SIZE ?
- (chunkLen - chunkBytesRead) : Http.BUFFER_SIZE;
- int len= in.read(bytes, 0, toRead);
+ int toRead = (chunkLen - chunkBytesRead) < Http.BUFFER_SIZE ? (chunkLen - chunkBytesRead)
+ : Http.BUFFER_SIZE;
+ int len = in.read(bytes, 0, toRead);
- if (len == -1)
+ if (len == -1)
throw new HttpException("chunk eof after " + contentBytesRead
- + " bytes in successful chunks"
- + " and " + chunkBytesRead
- + " in current chunk");
+ + " bytes in successful chunks" + " and " + chunkBytesRead
+ + " in current chunk");
// DANGER!!! Will printed GZIPed stuff right to your
// terminal!
- // if (LOG.isTraceEnabled()) { LOG.trace("read: " + new String(bytes, 0, len)); }
+ // if (LOG.isTraceEnabled()) { LOG.trace("read: " + new String(bytes, 0,
+ // len)); }
out.write(bytes, 0, len);
- chunkBytesRead+= len;
+ chunkBytesRead += len;
}
readLine(in, line, false);
@@ -390,7 +400,7 @@ public class HttpResponse implements Response {
}
if (!doneChunks) {
- if (contentBytesRead != http.getMaxContent())
+ if (contentBytesRead != http.getMaxContent())
throw new HttpException("chunk eof: !doneChunk && didn't max out");
return;
}
@@ -401,36 +411,35 @@ public class HttpResponse implements Response {
}
private int parseStatusLine(PushbackInputStream in, StringBuffer line)
- throws IOException, HttpException {
+ throws IOException, HttpException {
readLine(in, line, false);
int codeStart = line.indexOf(" ");
- int codeEnd = line.indexOf(" ", codeStart+1);
+ int codeEnd = line.indexOf(" ", codeStart + 1);
// handle lines with no plaintext result code, ie:
// "HTTP/1.1 200" vs "HTTP/1.1 200 OK"
- if (codeEnd == -1)
- codeEnd= line.length();
+ if (codeEnd == -1)
+ codeEnd = line.length();
int code;
try {
- code= Integer.parseInt(line.substring(codeStart+1, codeEnd));
+ code = Integer.parseInt(line.substring(codeStart + 1, codeEnd));
} catch (NumberFormatException e) {
- throw new HttpException("bad status line '" + line
- + "': " + e.getMessage(), e);
+ throw new HttpException("bad status line '" + line + "': "
+ + e.getMessage(), e);
}
return code;
}
+ private void processHeaderLine(StringBuffer line) throws IOException,
+ HttpException {
- private void processHeaderLine(StringBuffer line)
- throws IOException, HttpException {
-
- int colonIndex = line.indexOf(":"); // key is up to colon
+ int colonIndex = line.indexOf(":"); // key is up to colon
if (colonIndex == -1) {
int i;
- for (i= 0; i < line.length(); i++)
+ for (i = 0; i < line.length(); i++)
if (!Character.isWhitespace(line.charAt(i)))
break;
if (i == line.length())
@@ -439,7 +448,7 @@ public class HttpResponse implements Response {
}
String key = line.substring(0, colonIndex);
- int valueStart = colonIndex+1; // skip whitespace
+ int valueStart = colonIndex + 1; // skip whitespace
while (valueStart < line.length()) {
int c = line.charAt(valueStart);
if (c != ' ' && c != '\t')
@@ -450,28 +459,27 @@ public class HttpResponse implements Response {
headers.set(key, value);
}
-
// Adds headers to our headers Metadata
private void parseHeaders(PushbackInputStream in, StringBuffer line)
- throws IOException, HttpException {
+ throws IOException, HttpException {
while (readLine(in, line, true) != 0) {
// handle HTTP responses with missing blank line after headers
int pos;
- if ( ((pos= line.indexOf("<!DOCTYPE")) != -1)
- || ((pos= line.indexOf("<HTML")) != -1)
- || ((pos= line.indexOf("<html")) != -1) ) {
+ if (((pos = line.indexOf("<!DOCTYPE")) != -1)
+ || ((pos = line.indexOf("<HTML")) != -1)
+ || ((pos = line.indexOf("<html")) != -1)) {
in.unread(line.substring(pos).getBytes("UTF-8"));
line.setLength(pos);
try {
- //TODO: (CM) We don't know the header names here
- //since we're just handling them generically. It would
- //be nice to provide some sort of mapping function here
- //for the returned header names to the standard metadata
- //names in the ParseData class
+ // TODO: (CM) We don't know the header names here
+ // since we're just handling them generically. It would
+ // be nice to provide some sort of mapping function here
+ // for the returned header names to the standard metadata
+ // names in the ParseData class
processHeaderLine(line);
} catch (Exception e) {
// fixme:
@@ -485,29 +493,29 @@ public class HttpResponse implements Response {
}
private static int readLine(PushbackInputStream in, StringBuffer line,
- boolean allowContinuedLine)
- throws IOException {
+ boolean allowContinuedLine) throws IOException {
line.setLength(0);
for (int c = in.read(); c != -1; c = in.read()) {
switch (c) {
- case '\r':
- if (peek(in) == '\n') {
- in.read();
- }
- case '\n':
- if (line.length() > 0) {
- // at EOL -- check for continued line if the current
- // (possibly continued) line wasn't blank
- if (allowContinuedLine)
- switch (peek(in)) {
- case ' ' : case '\t': // line is continued
- in.read();
- continue;
- }
- }
- return line.length(); // else complete
- default :
- line.append((char)c);
+ case '\r':
+ if (peek(in) == '\n') {
+ in.read();
+ }
+ case '\n':
+ if (line.length() > 0) {
+ // at EOL -- check for continued line if the current
+ // (possibly continued) line wasn't blank
+ if (allowContinuedLine)
+ switch (peek(in)) {
+ case ' ':
+ case '\t': // line is continued
+ in.read();
+ continue;
+ }
+ }
+ return line.length(); // else complete
+ default:
+ line.append((char) c);
}
}
throw new EOFException();
diff --git a/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestProtocolHttp.java b/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestProtocolHttp.java
index 4c79f6ca5..39246ed45 100644
--- a/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestProtocolHttp.java
+++ b/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestProtocolHttp.java
@@ -93,7 +93,7 @@ public class TestProtocolHttp {
/**
* Starts the Jetty server at a specified port and redirection parameter.
- *
+ *
* @param portno
* Port number.
* @param redirection
@@ -114,7 +114,7 @@ public class TestProtocolHttp {
* Fetches the specified <code>page</code> from the local Jetty server and
* checks whether the HTTP response status code matches with the expected
* code. Also use jsp pages for redirection.
- *
+ *
* @param page
* Page to be fetched.
* @param expectedCode
@@ -138,4 +138,3 @@ public class TestProtocolHttp {
}
}
}
-
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java
index c51d15589..afcf24aa3 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java
@@ -1,19 +1,19 @@
/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You 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.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
/*
* Based on EasySSLProtocolSocketFactory from commons-httpclient:
*
@@ -41,10 +41,12 @@ import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
-public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactory {
+public class DummySSLProtocolSocketFactory implements
+ SecureProtocolSocketFactory {
/** Logger object for this class. */
- private static final Logger LOG = LoggerFactory.getLogger(DummySSLProtocolSocketFactory.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DummySSLProtocolSocketFactory.class);
private SSLContext sslcontext = null;
@@ -58,10 +60,13 @@ public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactor
private static SSLContext createEasySSLContext() {
try {
SSLContext context = SSLContext.getInstance("SSL");
- context.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null);
+ context.init(null,
+ new TrustManager[] { new DummyX509TrustManager(null) }, null);
return context;
} catch (Exception e) {
- if (LOG.isErrorEnabled()) { LOG.error(e.getMessage(), e); }
+ if (LOG.isErrorEnabled()) {
+ LOG.error(e.getMessage(), e);
+ }
throw new HttpClientError(e.toString());
}
}
@@ -76,10 +81,11 @@ public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactor
/**
* @see org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory#createSocket(String,int,InetAddress,int)
*/
- public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException,
- UnknownHostException {
+ public Socket createSocket(String host, int port, InetAddress clientHost,
+ int clientPort) throws IOException, UnknownHostException {
- return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
+ return getSSLContext().getSocketFactory().createSocket(host, port,
+ clientHost, clientPort);
}
/**
@@ -93,20 +99,28 @@ public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactor
* throws an {@link ConnectTimeoutException}
* </p>
*
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- * @param params {@link HttpConnectionParams Http connection parameters}
+ * @param host
+ * the host name/IP
+ * @param port
+ * the port on the host
+ * @param localAddress
+ * the local host name/IP to bind the socket to
+ * @param localPort
+ * the port on the local machine
+ * @param params
+ * {@link HttpConnectionParams Http connection parameters}
*
* @return Socket a new socket
*
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
+ * @throws IOException
+ * if an I/O error occurs while creating the socket
+ * @throws UnknownHostException
+ * if the IP address of the host cannot be determined
*/
- public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort,
- final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
+ public Socket createSocket(final String host, final int port,
+ final InetAddress localAddress, final int localPort,
+ final HttpConnectionParams params) throws IOException,
+ UnknownHostException, ConnectTimeoutException {
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
@@ -115,27 +129,31 @@ public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactor
return createSocket(host, port, localAddress, localPort);
} else {
// To be eventually deprecated when migrated to Java 1.4 or above
- return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout);
+ return ControllerThreadSocketFactory.createSocket(this, host, port,
+ localAddress, localPort, timeout);
}
}
/**
* @see org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory#createSocket(String,int)
*/
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
+ public Socket createSocket(String host, int port) throws IOException,
+ UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(host, port);
}
/**
* @see org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory#createSocket(Socket,String,int,boolean)
*/
- public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException,
- UnknownHostException {
- return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
+ public Socket createSocket(Socket socket, String host, int port,
+ boolean autoClose) throws IOException, UnknownHostException {
+ return getSSLContext().getSocketFactory().createSocket(socket, host, port,
+ autoClose);
}
public boolean equals(Object obj) {
- return ((obj != null) && obj.getClass().equals(DummySSLProtocolSocketFactory.class));
+ return ((obj != null) && obj.getClass().equals(
+ DummySSLProtocolSocketFactory.class));
}
public int hashCode() {
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummyX509TrustManager.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummyX509TrustManager.java
index 65152ff7e..b5509cc49 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummyX509TrustManager.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummyX509TrustManager.java
@@ -1,19 +1,19 @@
/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You 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.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
/*
* Based on EasyX509TrustManager from commons-httpclient.
*/
@@ -29,59 +29,64 @@ import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
-import org.slf4j.Logger;
+import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class DummyX509TrustManager implements X509TrustManager
-{
- private X509TrustManager standardTrustManager = null;
+public class DummyX509TrustManager implements X509TrustManager {
+ private X509TrustManager standardTrustManager = null;
- /** Logger object for this class. */
- private static final Logger LOG = LoggerFactory.getLogger(DummyX509TrustManager.class);
+ /** Logger object for this class. */
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DummyX509TrustManager.class);
- /**
- * Constructor for DummyX509TrustManager.
- */
- public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
- super();
- String algo = TrustManagerFactory.getDefaultAlgorithm();
- TrustManagerFactory factory = TrustManagerFactory.getInstance(algo);
- factory.init(keystore);
- TrustManager[] trustmanagers = factory.getTrustManagers();
- if (trustmanagers.length == 0) {
- throw new NoSuchAlgorithmException(algo + " trust manager not supported");
- }
- this.standardTrustManager = (X509TrustManager)trustmanagers[0];
+ /**
+ * Constructor for DummyX509TrustManager.
+ */
+ public DummyX509TrustManager(KeyStore keystore)
+ throws NoSuchAlgorithmException, KeyStoreException {
+ super();
+ String algo = TrustManagerFactory.getDefaultAlgorithm();
+ TrustManagerFactory factory = TrustManagerFactory.getInstance(algo);
+ factory.init(keystore);
+ TrustManager[] trustmanagers = factory.getTrustManagers();
+ if (trustmanagers.length == 0) {
+ throw new NoSuchAlgorithmException(algo + " trust manager not supported");
}
+ this.standardTrustManager = (X509TrustManager) trustmanagers[0];
+ }
- /**
- * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[], String)
- */
- public boolean isClientTrusted(X509Certificate[] certificates) {
- return true;
- }
+ /**
+ * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
+ * String)
+ */
+ public boolean isClientTrusted(X509Certificate[] certificates) {
+ return true;
+ }
- /**
- * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], String)
- */
- public boolean isServerTrusted(X509Certificate[] certificates) {
- return true;
- }
+ /**
+ * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
+ * String)
+ */
+ public boolean isServerTrusted(X509Certificate[] certificates) {
+ return true;
+ }
- /**
- * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
- */
- public X509Certificate[] getAcceptedIssuers() {
- return this.standardTrustManager.getAcceptedIssuers();
- }
+ /**
+ * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
+ */
+ public X509Certificate[] getAcceptedIssuers() {
+ return this.standardTrustManager.getAcceptedIssuers();
+ }
- public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
- // do nothing
-
- }
+ public void checkClientTrusted(X509Certificate[] arg0, String arg1)
+ throws CertificateException {
+ // do nothing
- public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
- // do nothing
-
- }
+ }
+
+ public void checkServerTrusted(X509Certificate[] arg0, String arg1)
+ throws CertificateException {
+ // do nothing
+
+ }
}
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 86830772b..c04bfb4cb 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
@@ -54,19 +54,18 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.util.NutchConfiguration;
/**
- * This class is a protocol plugin that configures an HTTP client for
- * Basic, Digest and NTLM authentication schemes for web server as well
- * as proxy server. It takes care of HTTPS protocol as well as cookies
- * in a single fetch session.
- *
+ * This class is a protocol plugin that configures an HTTP client for Basic,
+ * Digest and NTLM authentication schemes for web server as well as proxy
+ * server. It takes care of HTTPS protocol as well as cookies in a single fetch
+ * session.
+ *
* @author Susam Pal
*/
public class Http extends HttpBase {
public static final Logger LOG = LoggerFactory.getLogger(Http.class);
- private static MultiThreadedHttpConnectionManager connectionManager =
- new MultiThreadedHttpConnectionManager();
+ private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
// Since the Configuration has not yet been set,
// then an unconfigured client is returned.
@@ -86,10 +85,9 @@ public class Http extends HttpBase {
private String proxyPassword;
private String proxyRealm;
-
/**
* Returns the configured HTTP client.
- *
+ *
* @return HTTP client
*/
static synchronized HttpClient getClient() {
@@ -104,10 +102,11 @@ public class Http extends HttpBase {
}
/**
- * Reads the configuration from the Nutch configuration files and sets
- * the configuration.
- *
- * @param conf Configuration
+ * Reads the configuration from the Nutch configuration files and sets the
+ * configuration.
+ *
+ * @param conf
+ * Configuration
*/
public void setConf(Configuration conf) {
super.setConf(conf);
@@ -130,8 +129,9 @@ public class Http extends HttpBase {
/**
* Main method.
- *
- * @param args Command line arguments
+ *
+ * @param args
+ * Command line arguments
*/
public static void main(String[] args) throws Exception {
Http http = new Http();
@@ -140,16 +140,19 @@ public class Http extends HttpBase {
}
/**
- * Fetches the <code>url</code> with a configured HTTP client and
- * gets the response.
- *
- * @param url URL to be fetched
- * @param datum Crawl data
- * @param redirect Follow redirects if and only if true
- * @return HTTP response
+ * Fetches the <code>url</code> with a configured HTTP client and gets the
+ * response.
+ *
+ * @param url
+ * URL to be fetched
+ * @param datum
+ * Crawl data
+ * @param redirect
+ * Follow redirects if and only if true
+ * @return HTTP response
*/
protected Response getResponse(URL url, CrawlDatum datum, boolean redirect)
- throws ProtocolException, IOException {
+ throws ProtocolException, IOException {
resolveCredentials(url);
return new HttpResponse(this, url, datum, redirect);
}
@@ -170,12 +173,14 @@ public class Http extends HttpBase {
params.setSendBufferSize(BUFFER_SIZE);
params.setReceiveBufferSize(BUFFER_SIZE);
params.setMaxTotalConnections(maxThreadsTotal);
-
- //Also set max connections per host to maxThreadsTotal since all threads
- //might be used to fetch from the same host - otherwise timeout errors can occur
+
+ // Also set max connections per host to maxThreadsTotal since all threads
+ // might be used to fetch from the same host - otherwise timeout errors can
+ // occur
params.setDefaultMaxConnectionsPerHost(maxThreadsTotal);
- // executeMethod(HttpMethod) seems to ignore the connection timeout on the connection manager.
+ // executeMethod(HttpMethod) seems to ignore the connection timeout on the
+ // connection manager.
// set it explicitly on the HttpClient.
client.getParams().setConnectionManagerTimeout(timeout);
@@ -188,7 +193,9 @@ public class Http extends HttpBase {
// prefer UTF-8
headers.add(new Header("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.7"));
// prefer understandable formats
- headers.add(new Header("Accept",
+ 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"));
// accept gzipped content
headers.add(new Header("Accept-Encoding", "x-gzip, gzip, deflate"));
@@ -200,43 +207,42 @@ public class Http extends HttpBase {
if (proxyUsername.length() > 0) {
- AuthScope proxyAuthScope = getAuthScope(
- this.proxyHost, this.proxyPort, this.proxyRealm);
+ AuthScope proxyAuthScope = getAuthScope(this.proxyHost, this.proxyPort,
+ this.proxyRealm);
- NTCredentials proxyCredentials = new NTCredentials(
- this.proxyUsername, this.proxyPassword,
- Http.agentHost, this.proxyRealm);
+ NTCredentials proxyCredentials = new NTCredentials(this.proxyUsername,
+ this.proxyPassword, Http.agentHost, this.proxyRealm);
- client.getState().setProxyCredentials(
- proxyAuthScope, proxyCredentials);
+ client.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
}
}
}
/**
- * Reads authentication configuration file (defined as
- * 'http.auth.file' in Nutch configuration file) and sets the
- * credentials for the configured authentication scopes in the HTTP
- * client object.
- *
- * @throws ParserConfigurationException If a document builder can not
- * be created.
- * @throws SAXException If any parsing error occurs.
- * @throws IOException If any I/O error occurs.
+ * Reads authentication configuration file (defined as 'http.auth.file' in
+ * Nutch configuration file) and sets the credentials for the configured
+ * authentication scopes in the HTTP client object.
+ *
+ * @throws ParserConfigurationException
+ * If a document builder can not be created.
+ * @throws SAXException
+ * If any parsing error occurs.
+ * @throws IOException
+ * If any I/O error occurs.
*/
- private static synchronized void setCredentials() throws
- ParserConfigurationException, SAXException, IOException {
+ private static synchronized void setCredentials()
+ throws ParserConfigurationException, SAXException, IOException {
if (authRulesRead)
return;
authRulesRead = true; // Avoid re-attempting to read
- InputStream is = conf.getConfResourceAsInputStream(authFile);
+ InputStream is = conf.getConfResourceAsInputStream(authFile);
if (is != null) {
- Document doc = DocumentBuilderFactory.newInstance()
- .newDocumentBuilder().parse(is);
+ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
+ .parse(is);
Element rootElement = doc.getDocumentElement();
if (!"auth-configuration".equals(rootElement.getTagName())) {
@@ -251,14 +257,14 @@ public class Http extends HttpBase {
for (int i = 0; i < credList.getLength(); i++) {
Node credNode = credList.item(i);
if (!(credNode instanceof Element))
- continue;
+ continue;
Element credElement = (Element) credNode;
if (!"credentials".equals(credElement.getTagName())) {
if (LOG.isWarnEnabled())
- LOG.warn("Bad auth conf file: Element <"
- + credElement.getTagName() + "> not recognized in "
- + authFile + " - expected <credentials>");
+ LOG.warn("Bad auth conf file: Element <" + credElement.getTagName()
+ + "> not recognized in " + authFile
+ + " - expected <credentials>");
continue;
}
@@ -271,7 +277,7 @@ public class Http extends HttpBase {
Node scopeNode = scopeList.item(j);
if (!(scopeNode instanceof Element))
continue;
-
+
Element scopeElement = (Element) scopeNode;
if ("default".equals(scopeElement.getTagName())) {
@@ -287,9 +293,9 @@ public class Http extends HttpBase {
defaultScheme = scheme;
if (LOG.isTraceEnabled()) {
- LOG.trace("Credentials - username: " + username
- + "; set as default"
- + " for realm: " + realm + "; scheme: " + scheme);
+ LOG.trace("Credentials - username: " + username
+ + "; set as default" + " for realm: " + realm + "; scheme: "
+ + scheme);
}
} else if ("authscope".equals(scopeElement.getTagName())) {
@@ -298,8 +304,7 @@ public class Http extends HttpBase {
String host = scopeElement.getAttribute("host");
int port = -1; // For setting port to AuthScope.ANY_PORT
try {
- port = Integer.parseInt(
- scopeElement.getAttribute("port"));
+ port = Integer.parseInt(scopeElement.getAttribute("port"));
} catch (Exception ex) {
// do nothing, port is already set to any port
}
@@ -308,16 +313,15 @@ public class Http extends HttpBase {
// Set credentials for the determined scope
AuthScope authScope = getAuthScope(host, port, realm, scheme);
- NTCredentials credentials = new NTCredentials(
- username, password, agentHost, realm);
+ NTCredentials credentials = new NTCredentials(username, password,
+ agentHost, realm);
client.getState().setCredentials(authScope, credentials);
if (LOG.isTraceEnabled()) {
LOG.trace("Credentials - username: " + username
- + "; set for AuthScope - " + "host: " + host
- + "; port: " + port + "; realm: " + realm
- + "; scheme: " + scheme);
+ + "; set for AuthScope - " + "host: " + host + "; port: "
+ + port + "; realm: " + realm + "; scheme: " + scheme);
}
} else {
@@ -333,14 +337,14 @@ public class Http extends HttpBase {
}
/**
- * If credentials for the authentication scope determined from the
- * specified <code>url</code> is not already set in the HTTP client,
- * then this method sets the default credentials to fetch the
- * specified <code>url</code>. If credentials are found for the
- * authentication scope, the method returns without altering the
- * client.
- *
- * @param url URL to be fetched
+ * If credentials for the authentication scope determined from the specified
+ * <code>url</code> is not already set in the HTTP client, then this method
+ * sets the default credentials to fetch the specified <code>url</code>. If
+ * credentials are found for the authentication scope, the method returns
+ * without altering the client.
+ *
+ * @param url
+ * URL to be fetched
*/
private void resolveCredentials(URL url) {
@@ -359,43 +363,42 @@ public class Http extends HttpBase {
if (client.getState().getCredentials(scope) != null) {
if (LOG.isTraceEnabled())
LOG.trace("Pre-configured credentials with scope - host: "
- + url.getHost() + "; port: " + port
- + "; found for url: " + url);
+ + url.getHost() + "; port: " + port + "; found for url: " + url);
// Credentials are already configured, so do nothing and return
return;
}
if (LOG.isTraceEnabled())
- LOG.trace("Pre-configured credentials with scope - host: "
- + url.getHost() + "; port: " + port
- + "; not found for url: " + url);
+ LOG.trace("Pre-configured credentials with scope - host: "
+ + url.getHost() + "; port: " + port + "; not found for url: " + url);
- AuthScope serverAuthScope = getAuthScope(
- url.getHost(), port, defaultRealm, defaultScheme);
+ AuthScope serverAuthScope = getAuthScope(url.getHost(), port,
+ defaultRealm, defaultScheme);
- NTCredentials serverCredentials = new NTCredentials(
- defaultUsername, defaultPassword,
- agentHost, defaultRealm);
+ NTCredentials serverCredentials = new NTCredentials(defaultUsername,
+ defaultPassword, agentHost, defaultRealm);
- client.getState().setCredentials(
- serverAuthScope, serverCredentials);
+ client.getState().setCredentials(serverAuthScope, serverCredentials);
}
}
/**
- * Returns an authentication scope for the specified
- * <code>host</code>, <code>port</code>, <code>realm</code> and
- * <code>scheme</code>.
- *
- * @param host Host name or address.
- * @param port Port number.
- * @param realm Authentication realm.
- * @param scheme Authentication scheme.
+ * Returns an authentication scope for the specified <code>host</code>,
+ * <code>port</code>, <code>realm</code> and <code>scheme</code>.
+ *
+ * @param host
+ * Host name or address.
+ * @param port
+ * Port number.
+ * @param realm
+ * Authentication realm.
+ * @param scheme
+ * Authentication scheme.
*/
- private static AuthScope getAuthScope(String host, int port,
- String realm, String scheme) {
-
+ private static AuthScope getAuthScope(String host, int port, String realm,
+ String scheme) {
+
if (host.length() == 0)
host = null;
@@ -412,17 +415,18 @@ public class Http extends HttpBase {
}
/**
- * Returns an authentication scope for the specified
- * <code>host</code>, <code>port</code> and <code>realm</code>.
- *
- * @param host Host name or address.
- * @param port Port number.
- * @param realm Authentication realm.
+ * Returns an authentication scope for the specified <code>host</code>,
+ * <code>port</code> and <code>realm</code>.
+ *
+ * @param host
+ * Host name or address.
+ * @param port
+ * Port number.
+ * @param realm
+ * Authentication realm.
*/
- private static AuthScope getAuthScope(String host, int port,
- String realm) {
+ private static AuthScope getAuthScope(String host, int port, String realm) {
- return getAuthScope(host, port, realm, "");
+ return getAuthScope(host, port, realm, "");
}
}
-
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthentication.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthentication.java
index 3561e0764..54dc905c6 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthentication.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthentication.java
@@ -15,32 +15,31 @@
* limitations under the License.
*/
package org.apache.nutch.protocol.httpclient;
-
+
import java.util.List;
/**
- * The base level of services required for Http Authentication
- *
+ * The base level of services required for Http Authentication
+ *
* @see HttpAuthenticationFactory
*
- * @author Matt Tencati
+ * @author Matt Tencati
*/
public interface HttpAuthentication {
- /**
- * Gets the credentials generated by the HttpAuthentication
- * object. May return null.
- *
- * @return The credentials value
- */
- public List<String> getCredentials();
+ /**
+ * Gets the credentials generated by the HttpAuthentication object. May return
+ * null.
+ *
+ * @return The credentials value
+ */
+ public List<String> getCredentials();
- /**
- * Gets the realm used by the HttpAuthentication object during creation.
- *
- * @return The realm value
- */
- public String getRealm();
+ /**
+ * Gets the realm used by the HttpAuthentication object during creation.
+ *
+ * @return The realm value
+ */
+ public String getRealm();
}
-
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationException.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationException.java
index eb4c68dd0..daff5ec61 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationException.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationException.java
@@ -26,40 +26,46 @@ package org.apache.nutch.protocol.httpclient;
*/
public class HttpAuthenticationException extends Exception {
- /**
- * Constructs a new exception with null as its detail message.
- */
- public HttpAuthenticationException() {
- super();
- }
+ /**
+ * Constructs a new exception with null as its detail message.
+ */
+ public HttpAuthenticationException() {
+ super();
+ }
- /**
- * Constructs a new exception with the specified detail message.
- *
- * @param message the detail message. The detail message is saved for later retrieval by the {@link Throwable#getMessage()} method.
- */
- public HttpAuthenticationException(String message) {
- super(message);
- }
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message
+ * the detail message. The detail message is saved for later
+ * retrieval by the {@link Throwable#getMessage()} method.
+ */
+ public HttpAuthenticationException(String message) {
+ super(message);
+ }
- /**
- * Constructs a new exception with the specified message and cause.
- *
- * @param message the detail message. The detail message is saved for later retrieval by the {@link Throwable#getMessage()} method.
- * @param cause the cause (use {@link #getCause()} to retrieve the cause)
- */
- public HttpAuthenticationException(String message, Throwable cause) {
- super(message, cause);
- }
+ /**
+ * Constructs a new exception with the specified message and cause.
+ *
+ * @param message
+ * the detail message. The detail message is saved for later
+ * retrieval by the {@link Throwable#getMessage()} method.
+ * @param cause
+ * the cause (use {@link #getCause()} to retrieve the cause)
+ */
+ public HttpAuthenticationException(String message, Throwable cause) {
+ super(message, cause);
+ }
- /**
- * Constructs a new exception with the specified cause and detail message from
- * given clause if it is not null.
- *
- * @param cause the cause (use {@link #getCause()} to retrieve the cause)
- */
- public HttpAuthenticationException(Throwable cause) {
- super(cause);
- }
+ /**
+ * Constructs a new exception with the specified cause and detail message from
+ * given clause if it is not null.
+ *
+ * @param cause
+ * the cause (use {@link #getCause()} to retrieve the cause)
+ */
+ public HttpAuthenticationException(Throwable cause) {
+ super(cause);
+ }
}
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 d0b17df99..064a6d08c 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
@@ -31,28 +31,27 @@ import org.apache.hadoop.conf.Configurable;
// Nutch imports
import org.apache.nutch.metadata.Metadata;
-
/**
- * Provides the Http protocol implementation
- * with the ability to authenticate when prompted. The goal is to provide
- * multiple authentication types but for now just the {@link HttpBasicAuthentication} authentication
- * type is provided.
- *
+ * Provides the Http protocol implementation with the ability to authenticate
+ * when prompted. The goal is to provide multiple authentication types but for
+ * now just the {@link HttpBasicAuthentication} authentication type is provided.
+ *
* @see HttpBasicAuthentication
* @see Http
* @see HttpResponse
- *
+ *
* @author Matt Tencati
*/
public class HttpAuthenticationFactory implements Configurable {
/**
- * The HTTP Authentication (WWW-Authenticate) header which is returned
- * by a webserver requiring authentication.
+ * The HTTP Authentication (WWW-Authenticate) header which is returned by a
+ * webserver requiring authentication.
*/
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
- public static final Logger LOG = LoggerFactory.getLogger(HttpAuthenticationFactory.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(HttpAuthenticationFactory.class);
private Configuration conf = null;
@@ -63,29 +62,33 @@ public class HttpAuthenticationFactory implements Configurable {
public void setConf(Configuration conf) {
this.conf = conf;
}
+
public Configuration getConf() {
return conf;
}
public HttpAuthentication findAuthentication(Metadata header) {
- if (header == null) return null;
+ if (header == null)
+ return null;
try {
Collection<String> challenge = new ArrayList<String>();
challenge.add(header.get(WWW_AUTHENTICATE));
- for(String challengeString: challenge) {
+ for (String challengeString : challenge) {
if (challengeString.equals("NTLM"))
- challengeString="Basic realm=techweb";
+ challengeString = "Basic realm=techweb";
if (LOG.isTraceEnabled())
LOG.trace("Checking challengeString=" + challengeString);
- HttpAuthentication auth = HttpBasicAuthentication.getAuthentication(challengeString, conf);
- if (auth != null) return auth;
+ HttpAuthentication auth = HttpBasicAuthentication.getAuthentication(
+ challengeString, conf);
+ if (auth != null)
+ return auth;
- //TODO Add additional Authentication lookups here
+ // TODO Add additional Authentication lookups here
}
} catch (Exception e) {
LOG.error("Error: ", e);
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 866ce0621..0cc2de5be 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
@@ -35,156 +35,165 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configurable;
-
/**
- * Implementation of RFC 2617 Basic Authentication. Usernames and passwords are stored
- * in standard Nutch configuration files using the following properties:
- * http.auth.basic.<realm>.user
- * http.auth.basic.<realm>.pass
- *
- * @author Matt Tencati
+ * Implementation of RFC 2617 Basic Authentication. Usernames and passwords are
+ * stored in standard Nutch configuration files using the following properties:
+ * http.auth.basic.<realm>.user http.auth.basic.<realm>.pass
+ *
+ * @author Matt Tencati
*/
-public class HttpBasicAuthentication implements HttpAuthentication, Configurable {
-
- public static final Logger LOG = LoggerFactory.getLogger(HttpBasicAuthentication.class);
-
- private static Pattern basic = Pattern.compile("[bB][aA][sS][iI][cC] [rR][eE][aA][lL][mM]=\"(\\w*)\"");
-
- private static Map<String, HttpBasicAuthentication> authMap = new TreeMap<String, HttpBasicAuthentication>();
-
- private Configuration conf = null;
- private String challenge = null;
- private ArrayList<String> credentials = null;
- private String realm = null;
-
-
- /**
- * Construct an HttpBasicAuthentication for the given challenge
- * parameters. The challenge parameters are returned by the web
- * server using a WWW-Authenticate header. This will typically be
- * represented by single line of the form <code>WWW-Authenticate: Basic realm="myrealm"</code>
- *
- * @param challenge WWW-Authenticate header from web server
- */
- protected HttpBasicAuthentication(String challenge, Configuration conf) throws HttpAuthenticationException {
-
- setConf(conf);
- this.challenge = challenge;
- credentials = new ArrayList<String>();
-
- String username = this.conf.get("http.auth.basic." + challenge + ".user");
- String password = this.conf.get("http.auth.basic." + challenge + ".password");
-
- if (LOG.isTraceEnabled()) {
- LOG.trace("BasicAuthentication challenge is " + challenge);
- LOG.trace("BasicAuthentication username=" + username);
- LOG.trace("BasicAuthentication password=" + password);
- }
-
- if (username == null) {
- throw new HttpAuthenticationException("Username for " + challenge + " is null");
- }
-
- if (password == null) {
- throw new HttpAuthenticationException("Password for " + challenge + " is null");
- }
-
- byte[] credBytes = (username + ":" + password).getBytes();
- credentials.add("Authorization: Basic " + new String(Base64.encodeBase64(credBytes)));
- if (LOG.isTraceEnabled()) {
- LOG.trace("Basic credentials: " + credentials);
- }
- }
-
-
- /* ---------------------------------- *
- * <implementation:Configurable> *
- * ---------------------------------- */
-
- public void setConf(Configuration conf) {
- this.conf = conf;
- //if (conf.getBoolean("http.auth.verbose", false)) {
- // LOG.setLevel(Level.FINE);
- //} else {
- // LOG.setLevel(Level.WARNING);
- //}
+public class HttpBasicAuthentication implements HttpAuthentication,
+ Configurable {
+
+ public static final Logger LOG = LoggerFactory
+ .getLogger(HttpBasicAuthentication.class);
+
+ private static Pattern basic = Pattern
+ .compile("[bB][aA][sS][iI][cC] [rR][eE][aA][lL][mM]=\"(\\w*)\"");
+
+ private static Map<String, HttpBasicAuthentication> authMap = new TreeMap<String, HttpBasicAuthentication>();
+
+ private Configuration conf = null;
+ private String challenge = null;
+ private ArrayList<String> credentials = null;
+ private String realm = null;
+
+ /**
+ * Construct an HttpBasicAuthentication for the given challenge parameters.
+ * The challenge parameters are returned by the web server using a
+ * WWW-Authenticate header. This will typically be represented by single line
+ * of the form <code>WWW-Authenticate: Basic realm="myrealm"</code>
+ *
+ * @param challenge
+ * WWW-Authenticate header from web server
+ */
+ protected HttpBasicAuthentication(String challenge, Configuration conf)
+ throws HttpAuthenticationException {
+
+ setConf(conf);
+ this.challenge = challenge;
+ credentials = new ArrayList<String>();
+
+ String username = this.conf.get("http.auth.basic." + challenge + ".user");
+ String password = this.conf.get("http.auth.basic." + challenge
+ + ".password");
+
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("BasicAuthentication challenge is " + challenge);
+ LOG.trace("BasicAuthentication username=" + username);
+ LOG.trace("BasicAuthentication password=" + password);
}
- public Configuration getConf() {
- return this.conf;
+ if (username == null) {
+ throw new HttpAuthenticationException("Username for " + challenge
+ + " is null");
}
- /* ---------------------------------- *
- * <implementation:Configurable> *
- * ---------------------------------- */
-
-
- /**
- * Gets the Basic credentials generated by this
- * HttpBasicAuthentication object
- *
- * @return Credentials in the form of <code>Authorization: Basic &lt;Base64 encoded userid:password&gt;
- *
- */
- public List<String> getCredentials() {
- return credentials;
+ if (password == null) {
+ throw new HttpAuthenticationException("Password for " + challenge
+ + " is null");
}
-
- /**
- * Gets the realm attribute of the HttpBasicAuthentication object.
- * This should have been supplied to the {@link #getAuthentication(String, Configuration)}
- * static method
- *
- * @return The realm
- */
- public String getRealm() {
- return realm;
+ byte[] credBytes = (username + ":" + password).getBytes();
+ credentials.add("Authorization: Basic "
+ + new String(Base64.encodeBase64(credBytes)));
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Basic credentials: " + credentials);
}
-
- /**
- * This method is responsible for providing Basic authentication information. The
- * method caches authentication information for each realm so that the required
- * authentication information does not need to be regenerated for every request.
- *
- * @param challenge The challenge string provided by the webserver. This is the
- * text which follows the WWW-Authenticate header, including the Basic tag.
- * @return An HttpBasicAuthentication object or null
- * if unable to generate appropriate credentials.
- */
- public static HttpBasicAuthentication getAuthentication(String challenge, Configuration conf) {
- if (challenge == null) return null;
- Matcher basicMatcher = basic.matcher(challenge);
- if (basicMatcher.matches()) {
- String realm = basicMatcher.group(1);
- Object auth = authMap.get(realm);
- if (auth == null) {
- HttpBasicAuthentication newAuth = null;
- try {
- newAuth = new HttpBasicAuthentication(realm, conf);
- } catch (HttpAuthenticationException hae) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("HttpBasicAuthentication failed for " + challenge);
- }
- }
- authMap.put(realm, newAuth);
- return newAuth;
- } else {
- return (HttpBasicAuthentication) auth;
- }
+ }
+
+ /*
+ * ---------------------------------- * <implementation:Configurable> *
+ * ----------------------------------
+ */
+
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ // if (conf.getBoolean("http.auth.verbose", false)) {
+ // LOG.setLevel(Level.FINE);
+ // } else {
+ // LOG.setLevel(Level.WARNING);
+ // }
+ }
+
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ /*
+ * ---------------------------------- * <implementation:Configurable> *
+ * ----------------------------------
+ */
+
+ /**
+ * Gets the Basic credentials generated by this HttpBasicAuthentication object
+ *
+ * @return Credentials in the form of
+ * <code>Authorization: Basic &lt;Base64 encoded userid:password&gt;
+ *
+ */
+ public List<String> getCredentials() {
+ return credentials;
+ }
+
+ /**
+ * Gets the realm attribute of the HttpBasicAuthentication object. This should
+ * have been supplied to the {@link #getAuthentication(String, Configuration)}
+ * static method
+ *
+ * @return The realm
+ */
+ public String getRealm() {
+ return realm;
+ }
+
+ /**
+ * This method is responsible for providing Basic authentication information.
+ * The method caches authentication information for each realm so that the
+ * required authentication information does not need to be regenerated for
+ * every request.
+ *
+ * @param challenge
+ * The challenge string provided by the webserver. This is the text
+ * which follows the WWW-Authenticate header, including the Basic
+ * tag.
+ * @return An HttpBasicAuthentication object or null if unable to generate
+ * appropriate credentials.
+ */
+ public static HttpBasicAuthentication getAuthentication(String challenge,
+ Configuration conf) {
+ if (challenge == null)
+ return null;
+ Matcher basicMatcher = basic.matcher(challenge);
+ if (basicMatcher.matches()) {
+ String realm = basicMatcher.group(1);
+ Object auth = authMap.get(realm);
+ if (auth == null) {
+ HttpBasicAuthentication newAuth = null;
+ try {
+ newAuth = new HttpBasicAuthentication(realm, conf);
+ } catch (HttpAuthenticationException hae) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("HttpBasicAuthentication failed for " + challenge);
+ }
}
- return null;
+ authMap.put(realm, newAuth);
+ return newAuth;
+ } else {
+ return (HttpBasicAuthentication) auth;
+ }
}
-
- /**
- * Provides a pattern which can be used by an outside resource to determine if
- * this class can provide credentials based on simple header information. It does
- * not calculate any information regarding realms or challenges.
- *
- * @return Returns a Pattern which will match a Basic WWW-Authenticate header.
- */
- public static final Pattern getBasicPattern() {
- return basic;
- }
+ return null;
+ }
+
+ /**
+ * Provides a pattern which can be used by an outside resource to determine if
+ * this class can provide credentials based on simple header information. It
+ * does not calculate any information regarding realms or challenges.
+ *
+ * @return Returns a Pattern which will match a Basic WWW-Authenticate header.
+ */
+ public static final Pattern getBasicPattern() {
+ return basic;
+ }
}
-
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 def5959c5..b6ec45124 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
@@ -40,7 +40,7 @@ import org.apache.nutch.protocol.http.api.HttpBase;
/**
* An HTTP response.
- *
+ *
* @author Susam Pal
*/
public class HttpResponse implements Response {
@@ -52,18 +52,22 @@ public class HttpResponse implements Response {
/**
* Fetches the given <code>url</code> and prepares HTTP response.
- *
- * @param http An instance of the implementation class
- * of this plugin
- * @param url URL to be fetched
- * @param datum Crawl data
- * @param followRedirects Whether to follow redirects; follows
- * redirect if and only if this is true
- * @return HTTP response
- * @throws IOException When an error occurs
+ *
+ * @param http
+ * An instance of the implementation class of this plugin
+ * @param url
+ * URL to be fetched
+ * @param datum
+ * Crawl data
+ * @param followRedirects
+ * Whether to follow redirects; follows redirect if and only if this
+ * is true
+ * @return HTTP response
+ * @throws IOException
+ * When an error occurs
*/
- HttpResponse(Http http, URL url, CrawlDatum datum,
- boolean followRedirects) throws IOException {
+ HttpResponse(Http http, URL url, CrawlDatum datum, boolean followRedirects)
+ throws IOException {
// Prepare GET method for HTTP request
this.url = url;
@@ -98,7 +102,7 @@ public class HttpResponse implements Response {
for (int i = 0; i < heads.length; i++) {
headers.set(heads[i].getName(), heads[i].getValue());
}
-
+
// Limit download size
int contentLength = Integer.MAX_VALUE;
String contentLengthString = headers.get(Response.CONTENT_LENGTH);
@@ -106,12 +110,10 @@ public class HttpResponse implements Response {
try {
contentLength = Integer.parseInt(contentLengthString.trim());
} catch (NumberFormatException ex) {
- throw new HttpException("bad content length: " +
- contentLengthString);
+ throw new HttpException("bad content length: " + contentLengthString);
}
}
- if (http.getMaxContent() >= 0 &&
- contentLength > http.getMaxContent()) {
+ if (http.getMaxContent() >= 0 && contentLength > http.getMaxContent()) {
contentLength = http.getMaxContent();
}
@@ -131,7 +133,8 @@ public class HttpResponse implements Response {
content = out.toByteArray();
} catch (Exception e) {
- if (code == 200) throw new IOException(e.toString());
+ if (code == 200)
+ throw new IOException(e.toString());
// for codes other than 200 OK, we are fine with empty content
} finally {
if (in != null) {
@@ -139,16 +142,15 @@ public class HttpResponse implements Response {
}
get.abort();
}
-
+
StringBuilder fetchTrace = null;
if (Http.LOG.isTraceEnabled()) {
// Trace message
- fetchTrace = new StringBuilder("url: " + url +
- "; status code: " + code +
- "; bytes received: " + content.length);
+ fetchTrace = new StringBuilder("url: " + url + "; status code: " + code
+ + "; bytes received: " + content.length);
if (getHeader(Response.CONTENT_LENGTH) != null)
- fetchTrace.append("; Content-Length: " +
- getHeader(Response.CONTENT_LENGTH));
+ fetchTrace.append("; Content-Length: "
+ + getHeader(Response.CONTENT_LENGTH));
if (getHeader(Response.LOCATION) != null)
fetchTrace.append("; Location: " + getHeader(Response.LOCATION));
}
@@ -158,8 +160,7 @@ public class HttpResponse implements Response {
String contentEncoding = headers.get(Response.CONTENT_ENCODING);
if (contentEncoding != null && Http.LOG.isTraceEnabled())
fetchTrace.append("; Content-Encoding: " + contentEncoding);
- if ("gzip".equals(contentEncoding) ||
- "x-gzip".equals(contentEncoding)) {
+ if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
content = http.processGzipEncoded(content, url);
if (Http.LOG.isTraceEnabled())
fetchTrace.append("; extracted to " + content.length + " bytes");
@@ -179,15 +180,15 @@ public class HttpResponse implements Response {
}
}
-
- /* ------------------------- *
- * <implementation:Response> *
- * ------------------------- */
-
+ /*
+ * ------------------------- * <implementation:Response> *
+ * -------------------------
+ */
+
public URL getUrl() {
return url;
}
-
+
public int getCode() {
return code;
}
@@ -195,7 +196,7 @@ public class HttpResponse implements Response {
public String getHeader(String name) {
return headers.get(name);
}
-
+
public Metadata getHeaders() {
return headers;
}
@@ -204,8 +205,8 @@ public class HttpResponse implements Response {
return content;
}
- /* -------------------------- *
- * </implementation:Response> *
- * -------------------------- */
+ /*
+ * -------------------------- * </implementation:Response> *
+ * --------------------------
+ */
}
-
diff --git a/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java b/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java
index 6e566fdfe..2463947ea 100644
--- a/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java
+++ b/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java
@@ -60,7 +60,7 @@ public class TestProtocolHttpClient {
conf = new Configuration();
conf.addResource("nutch-default.xml");
conf.addResource("nutch-site-test.xml");
-
+
http = new Http();
http.setConf(conf);
}
@@ -72,8 +72,9 @@ public class TestProtocolHttpClient {
/**
* Tests whether the client can remember cookies.
- *
- * @throws Exception If an error occurs or the test case fails.
+ *
+ * @throws Exception
+ * If an error occurs or the test case fails.
*/
@Test
public void testCookies() throws Exception {
@@ -83,10 +84,10 @@ public class TestProtocolHttpClient {
}
/**
- * Tests that no pre-emptive authorization headers are sent by the
- * client.
- *
- * @throws Exception If an error occurs or the test case fails.
+ * Tests that no pre-emptive authorization headers are sent by the client.
+ *
+ * @throws Exception
+ * If an error occurs or the test case fails.
*/
@Test
public void testNoPreemptiveAuth() throws Exception {
@@ -96,8 +97,9 @@ public class TestProtocolHttpClient {
/**
* Tests default credentials.
- *
- * @throws Exception If an error occurs or the test case fails.
+ *
+ * @throws Exception
+ * If an error occurs or the test case fails.
*/
@Test
public void testDefaultCredentials() throws Exception {
@@ -108,7 +110,8 @@ public class TestProtocolHttpClient {
/**
* Tests basic authentication scheme for various realms.
*
- * @throws Exception If an error occurs or the test case fails.
+ * @throws Exception
+ * If an error occurs or the test case fails.
*/
@Test
public void testBasicAuth() throws Exception {
@@ -120,11 +123,12 @@ public class TestProtocolHttpClient {
}
/**
- * Tests that authentication happens for a defined realm and not for
- * other realms for a host:port when an extra <code>authscope</code>
- * tag is not defined to match all other realms.
- *
- * @throws Exception If an error occurs or the test case fails.
+ * Tests that authentication happens for a defined realm and not for other
+ * realms for a host:port when an extra <code>authscope</code> tag is not
+ * defined to match all other realms.
+ *
+ * @throws Exception
+ * If an error occurs or the test case fails.
*/
@Test
public void testOtherRealmsNoAuth() throws Exception {
@@ -136,8 +140,9 @@ public class TestProtocolHttpClient {
/**
* Tests Digest authentication scheme.
- *
- * @throws Exception If an error occurs or the test case fails.
+ *
+ * @throws Exception
+ * If an error occurs or the test case fails.
*/
@Test
public void testDigestAuth() throws Exception {
@@ -147,8 +152,9 @@ public class TestProtocolHttpClient {
/**
* Tests NTLM authentication scheme.
- *
- * @throws Exception If an error occurs or the test case fails.
+ *
+ * @throws Exception
+ * If an error occurs or the test case fails.
*/
@Test
public void testNtlmAuth() throws Exception {
@@ -158,9 +164,11 @@ public class TestProtocolHttpClient {
/**
* Starts the Jetty server at a specified port.
- *
- * @param portno Port number.
- * @throws Exception When an error occurs.
+ *
+ * @param portno
+ * Port number.
+ * @throws Exception
+ * When an error occurs.
*/
private void startServer(int portno) throws Exception {
port = portno;
@@ -172,17 +180,18 @@ public class TestProtocolHttpClient {
}
/**
- * Fetches the specified <code>page</code> from the local Jetty server
- * and checks whether the HTTP response status code matches with the
- * expected code.
- *
- * @param page Page to be fetched.
- * @param expectedCode HTTP response status code expected while
- * fetching the page.
- * @throws Exception When an error occurs or test case fails.
+ * Fetches the specified <code>page</code> from the local Jetty server and
+ * checks whether the HTTP response status code matches with the expected
+ * code.
+ *
+ * @param page
+ * Page to be fetched.
+ * @param expectedCode
+ * HTTP response status code expected while fetching the page.
+ * @throws Exception
+ * When an error occurs or test case fails.
*/
- private void fetchPage(String page, int expectedCode)
- throws Exception {
+ private void fetchPage(String page, int expectedCode) throws Exception {
URL url = new URL("http", "127.0.0.1", port, page);
Response response = null;
response = http.getResponse(url, new CrawlDatum(), true);
diff --git a/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java b/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java
index 1cb09fd7b..0a0dd27d3 100644
--- a/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java
+++ b/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java
@@ -28,33 +28,34 @@ import org.apache.nutch.scoring.ScoringFilterException;
*/
public class DepthScoringFilter extends Configured implements ScoringFilter {
private static final Log LOG = LogFactory.getLog(DepthScoringFilter.class);
-
+
public static final String DEPTH_KEY = "_depth_";
public static final Text DEPTH_KEY_W = new Text(DEPTH_KEY);
public static final String MAX_DEPTH_KEY = "_maxdepth_";
public static final Text MAX_DEPTH_KEY_W = new Text(MAX_DEPTH_KEY);
-
+
// maximum value that we are never likely to reach
// because the depth of the Web graph is that high only
// for spam cliques.
public static final int DEFAULT_MAX_DEPTH = 1000;
-
+
private int defaultMaxDepth;
-
+
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
- if (conf == null) return;
+ if (conf == null)
+ return;
defaultMaxDepth = conf.getInt("scoring.depth.max", DEFAULT_MAX_DEPTH);
if (defaultMaxDepth <= 0) {
defaultMaxDepth = DEFAULT_MAX_DEPTH;
}
}
-
+
@Override
public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
- ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
- CrawlDatum adjust, int allCount) throws ScoringFilterException {
+ ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
+ CrawlDatum adjust, int allCount) throws ScoringFilterException {
String depthString = parseData.getMeta(DEPTH_KEY);
if (depthString == null) {
LOG.warn("Missing depth, removing all outlinks from url " + fromUrl);
@@ -72,15 +73,17 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
}
if (curDepth >= curMaxDepth) {
// depth exceeded - throw away
- LOG.info("Depth limit (" + curMaxDepth + ") reached, ignoring outlinks for " + fromUrl);
+ LOG.info("Depth limit (" + curMaxDepth
+ + ") reached, ignoring outlinks for " + fromUrl);
targets.clear();
return adjust;
}
- Iterator<Entry<Text,CrawlDatum>> it = targets.iterator();
+ Iterator<Entry<Text, CrawlDatum>> it = targets.iterator();
while (it.hasNext()) {
- Entry<Text,CrawlDatum> e = it.next();
+ Entry<Text, CrawlDatum> e = it.next();
// record increased depth
- e.getValue().getMetaData().put(DEPTH_KEY_W, new IntWritable(curDepth + 1));
+ e.getValue().getMetaData()
+ .put(DEPTH_KEY_W, new IntWritable(curDepth + 1));
// record maxDepth if any
if (customMaxDepth != null) {
e.getValue().getMetaData().put(MAX_DEPTH_KEY_W, customMaxDepth);
@@ -92,16 +95,17 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
// prioritize by smaller values of depth
@Override
public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
- throws ScoringFilterException {
+ throws ScoringFilterException {
// boost up by current depth
int curDepth, curMaxDepth;
- IntWritable maxDepth = (IntWritable)datum.getMetaData().get(MAX_DEPTH_KEY_W);
+ IntWritable maxDepth = (IntWritable) datum.getMetaData().get(
+ MAX_DEPTH_KEY_W);
if (maxDepth != null) {
curMaxDepth = maxDepth.get();
} else {
curMaxDepth = defaultMaxDepth;
}
- IntWritable depth = (IntWritable)datum.getMetaData().get(DEPTH_KEY_W);
+ IntWritable depth = (IntWritable) datum.getMetaData().get(DEPTH_KEY_W);
if (depth == null) {
// penalize
curDepth = curMaxDepth;
@@ -113,27 +117,28 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
}
public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
- CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
- throws ScoringFilterException {
+ CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
+ throws ScoringFilterException {
return initScore;
}
@Override
public void initialScore(Text url, CrawlDatum datum)
- throws ScoringFilterException {
+ throws ScoringFilterException {
// the datum might already have some values set
// e.g. obtained from redirection
// in which case we don't want to override them
- if (datum.getMetaData().get(MAX_DEPTH_KEY_W) == null) datum.getMetaData()
- .put(MAX_DEPTH_KEY_W, new IntWritable(defaultMaxDepth));
+ if (datum.getMetaData().get(MAX_DEPTH_KEY_W) == null)
+ datum.getMetaData()
+ .put(MAX_DEPTH_KEY_W, new IntWritable(defaultMaxDepth));
// initial depth is 1
- if (datum.getMetaData().get(DEPTH_KEY_W) == null) datum.getMetaData().put(
- DEPTH_KEY_W, new IntWritable(1));
+ if (datum.getMetaData().get(DEPTH_KEY_W) == null)
+ datum.getMetaData().put(DEPTH_KEY_W, new IntWritable(1));
}
@Override
public void injectedScore(Text url, CrawlDatum datum)
- throws ScoringFilterException {
+ throws ScoringFilterException {
// check for the presence of the depth limit key
if (datum.getMetaData().get(MAX_DEPTH_KEY_W) != null) {
@@ -143,7 +148,8 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
int depth = Integer.parseInt(depthString);
datum.getMetaData().put(MAX_DEPTH_KEY_W, new IntWritable(depth));
} else { // put the default
- datum.getMetaData().put(MAX_DEPTH_KEY_W, new IntWritable(defaultMaxDepth));
+ datum.getMetaData()
+ .put(MAX_DEPTH_KEY_W, new IntWritable(defaultMaxDepth));
}
// initial depth is 1
datum.getMetaData().put(DEPTH_KEY_W, new IntWritable(1));
@@ -151,7 +157,7 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
@Override
public void passScoreAfterParsing(Text url, Content content, Parse parse)
- throws ScoringFilterException {
+ throws ScoringFilterException {
String depth = content.getMetadata().get(DEPTH_KEY);
if (depth != null) {
parse.getData().getParseMeta().set(DEPTH_KEY, depth);
@@ -164,12 +170,13 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
@Override
public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content)
- throws ScoringFilterException {
- IntWritable depth = (IntWritable)datum.getMetaData().get(DEPTH_KEY_W);
+ throws ScoringFilterException {
+ IntWritable depth = (IntWritable) datum.getMetaData().get(DEPTH_KEY_W);
if (depth != null) {
content.getMetadata().set(DEPTH_KEY, depth.toString());
}
- IntWritable maxdepth = (IntWritable)datum.getMetaData().get(MAX_DEPTH_KEY_W);
+ IntWritable maxdepth = (IntWritable) datum.getMetaData().get(
+ MAX_DEPTH_KEY_W);
if (maxdepth != null) {
content.getMetadata().set(MAX_DEPTH_KEY, maxdepth.toString());
}
@@ -177,7 +184,7 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
@Override
public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
- List<CrawlDatum> inlinked) throws ScoringFilterException {
+ List<CrawlDatum> inlinked) throws ScoringFilterException {
// find a minimum of all depths
int newDepth = DEFAULT_MAX_DEPTH;
if (old != null) {
@@ -190,7 +197,7 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
}
}
for (CrawlDatum lnk : inlinked) {
- IntWritable depth = (IntWritable)lnk.getMetaData().get(DEPTH_KEY_W);
+ IntWritable depth = (IntWritable) lnk.getMetaData().get(DEPTH_KEY_W);
if (depth != null && depth.get() < newDepth) {
newDepth = depth.get();
}
diff --git a/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/package-info.java b/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/package-info.java
index c6c58aaab..aa897974c 100644
--- a/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/package-info.java
+++ b/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/package-info.java
@@ -20,3 +20,4 @@
* (number of "hops" from seed URLs).
*/
package org.apache.nutch.scoring.depth;
+
diff --git a/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/LinkAnalysisScoringFilter.java b/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/LinkAnalysisScoringFilter.java
index ae4360c24..a143f46a9 100644
--- a/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/LinkAnalysisScoringFilter.java
+++ b/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/LinkAnalysisScoringFilter.java
@@ -32,8 +32,7 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.scoring.ScoringFilter;
import org.apache.nutch.scoring.ScoringFilterException;
-public class LinkAnalysisScoringFilter
- implements ScoringFilter {
+public class LinkAnalysisScoringFilter implements ScoringFilter {
private Configuration conf;
private float normalizedScore = 1.00f;
@@ -52,46 +51,44 @@ public class LinkAnalysisScoringFilter
}
public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
- ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
- CrawlDatum adjust, int allCount)
- throws ScoringFilterException {
+ ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
+ CrawlDatum adjust, int allCount) throws ScoringFilterException {
return adjust;
}
public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
- throws ScoringFilterException {
+ throws ScoringFilterException {
return datum.getScore() * initSort;
}
public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
- CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
- throws ScoringFilterException {
+ CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
+ throws ScoringFilterException {
return (normalizedScore * dbDatum.getScore());
}
public void initialScore(Text url, CrawlDatum datum)
- throws ScoringFilterException {
+ throws ScoringFilterException {
datum.setScore(0.0f);
}
public void injectedScore(Text url, CrawlDatum datum)
- throws ScoringFilterException {
+ throws ScoringFilterException {
}
public void passScoreAfterParsing(Text url, Content content, Parse parse)
- throws ScoringFilterException {
- parse.getData().getContentMeta().set(Nutch.SCORE_KEY,
- content.getMetadata().get(Nutch.SCORE_KEY));
+ throws ScoringFilterException {
+ parse.getData().getContentMeta()
+ .set(Nutch.SCORE_KEY, content.getMetadata().get(Nutch.SCORE_KEY));
}
public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content)
- throws ScoringFilterException {
+ throws ScoringFilterException {
content.getMetadata().set(Nutch.SCORE_KEY, "" + datum.getScore());
}
public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
- List<CrawlDatum> inlinked)
- throws ScoringFilterException {
+ List<CrawlDatum> inlinked) throws ScoringFilterException {
// nothing to do
}
diff --git a/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/package-info.java b/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/package-info.java
index 3931a58df..9dc0c3582 100644
--- a/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/package-info.java
+++ b/src/plugin/scoring-link/src/java/org/apache/nutch/scoring/link/package-info.java
@@ -20,3 +20,4 @@
* {@link org.apache.nutch.scoring.webgraph.WebGraph}.
*/
package org.apache.nutch.scoring.link;
+
diff --git a/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java b/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java
index 8e740f725..e943d06f4 100644
--- a/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java
+++ b/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/OPICScoringFilter.java
@@ -41,17 +41,17 @@ import org.apache.nutch.scoring.ScoringFilterException;
/**
* This plugin implements a variant of an Online Page Importance Computation
- * (OPIC) score, described in this paper:
- * <a href="http://www2003.org/cdrom/papers/refereed/p007/p7-abiteboul.html"/>
- * Abiteboul, Serge and Preda, Mihai and Cobena, Gregory (2003),
- * Adaptive On-Line Page Importance Computation
- * </a>.
+ * (OPIC) score, described in this paper: <a
+ * href="http://www2003.org/cdrom/papers/refereed/p007/p7-abiteboul.html"/>
+ * Abiteboul, Serge and Preda, Mihai and Cobena, Gregory (2003), Adaptive
+ * On-Line Page Importance Computation </a>.
*
* @author Andrzej Bialecki
*/
public class OPICScoringFilter implements ScoringFilter {
- private final static Logger LOG = LoggerFactory.getLogger(OPICScoringFilter.class);
+ private final static Logger LOG = LoggerFactory
+ .getLogger(OPICScoringFilter.class);
private Configuration conf;
private float scoreInjected;
@@ -72,28 +72,35 @@ public class OPICScoringFilter implements ScoringFilter {
countFiltered = conf.getBoolean("db.score.count.filtered", false);
}
- public void injectedScore(Text url, CrawlDatum datum) throws ScoringFilterException {
+ public void injectedScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
}
- /** Set to 0.0f (unknown value) - inlink contributions will bring it to
- * a correct level. Newly discovered pages have at least one inlink. */
- public void initialScore(Text url, CrawlDatum datum) throws ScoringFilterException {
+ /**
+ * Set to 0.0f (unknown value) - inlink contributions will bring it to a
+ * correct level. Newly discovered pages have at least one inlink.
+ */
+ public void initialScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
datum.setScore(0.0f);
}
/** Use {@link CrawlDatum#getScore()}. */
- public float generatorSortValue(Text url, CrawlDatum datum, float initSort) throws ScoringFilterException {
+ public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
+ throws ScoringFilterException {
return datum.getScore() * initSort;
}
/** Increase the score by a sum of inlinked scores. */
- public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum, List<CrawlDatum> inlinked) throws ScoringFilterException {
+ public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
+ List<CrawlDatum> inlinked) throws ScoringFilterException {
float adjust = 0.0f;
for (int i = 0; i < inlinked.size(); i++) {
CrawlDatum linked = inlinked.get(i);
adjust += linked.getScore();
}
- if (old == null) old = datum;
+ if (old == null)
+ old = datum;
datum.setScore(old.getScore() + adjust);
}
@@ -104,11 +111,17 @@ public class OPICScoringFilter implements ScoringFilter {
/** Copy the value from Content metadata under Fetcher.SCORE_KEY to parseData. */
public void passScoreAfterParsing(Text url, Content content, Parse parse) {
- parse.getData().getContentMeta().set(Nutch.SCORE_KEY, content.getMetadata().get(Nutch.SCORE_KEY));
+ parse.getData().getContentMeta()
+ .set(Nutch.SCORE_KEY, content.getMetadata().get(Nutch.SCORE_KEY));
}
- /** Get a float value from Fetcher.SCORE_KEY, divide it by the number of outlinks and apply. */
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl, ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets, CrawlDatum adjust, int allCount) throws ScoringFilterException {
+ /**
+ * Get a float value from Fetcher.SCORE_KEY, divide it by the number of
+ * outlinks and apply.
+ */
+ public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
+ ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
+ CrawlDatum adjust, int allCount) throws ScoringFilterException {
float score = scoreInjected;
String scoreString = parseData.getContentMeta().get(Nutch.SCORE_KEY);
if (scoreString != null) {
@@ -135,7 +148,7 @@ public class OPICScoringFilter implements ScoringFilter {
try {
String toHost = new URL(target.getKey().toString()).getHost();
String fromHost = new URL(fromUrl.toString()).getHost();
- if(toHost.equalsIgnoreCase(fromHost)){
+ if (toHost.equalsIgnoreCase(fromHost)) {
target.getValue().setScore(internalScore);
} else {
target.getValue().setScore(externalScore);
@@ -151,8 +164,10 @@ public class OPICScoringFilter implements ScoringFilter {
return adjust;
}
- /** Dampen the boost value by scorePower.*/
- public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum, CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore) throws ScoringFilterException {
- return (float)Math.pow(dbDatum.getScore(), scorePower) * initScore;
+ /** Dampen the boost value by scorePower. */
+ public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
+ CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
+ throws ScoringFilterException {
+ return (float) Math.pow(dbDatum.getScore(), scorePower) * initScore;
}
}
diff --git a/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/package-info.java b/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/package-info.java
index 49c325df7..26f6cbeb1 100644
--- a/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/package-info.java
+++ b/src/plugin/scoring-opic/src/java/org/apache/nutch/scoring/opic/package-info.java
@@ -20,3 +20,4 @@
* (OPIC) algorithm.
*/
package org.apache.nutch.scoring.opic;
+
diff --git a/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java b/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java
index efa322b3c..0dff3f827 100644
--- a/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java
+++ b/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java
@@ -52,22 +52,24 @@ public class CollectionManager extends Configured {
transient Map<String, Subcollection> collectionMap = new HashMap<String, Subcollection>();
transient URL configfile;
-
+
public CollectionManager(Configuration conf) {
super(conf);
init();
}
-
- /**
+
+ /**
* Used for testing
*/
- protected CollectionManager(){
+ protected CollectionManager() {
super(NutchConfiguration.create());
}
- protected void init(){
+ protected void init() {
try {
- if (LOG.isInfoEnabled()) { LOG.info("initializing CollectionManager"); }
+ if (LOG.isInfoEnabled()) {
+ LOG.info("initializing CollectionManager");
+ }
// initialize known subcollections
configfile = getConf().getResource(
getConf().get("subcollections.config", DEFAULT_FILE_NAME));
@@ -92,7 +94,7 @@ public class CollectionManager extends Configured {
if (LOG.isInfoEnabled()) {
LOG.info("file has " + nodeList.getLength() + " elements");
}
-
+
for (int i = 0; i < nodeList.getLength(); i++) {
Element scElem = (Element) nodeList.item(i);
Subcollection subCol = new Subcollection(getConf());
@@ -103,18 +105,18 @@ public class CollectionManager extends Configured {
LOG.info("Cannot find collections");
}
}
-
+
public static CollectionManager getCollectionManager(Configuration conf) {
String key = "collectionmanager";
ObjectCache objectCache = ObjectCache.get(conf);
- CollectionManager impl = (CollectionManager)objectCache.getObject(key);
+ CollectionManager impl = (CollectionManager) objectCache.getObject(key);
if (impl == null) {
try {
if (LOG.isInfoEnabled()) {
LOG.info("Instantiating CollectionManager");
}
- impl=new CollectionManager(conf);
- objectCache.setObject(key,impl);
+ impl = new CollectionManager(conf);
+ objectCache.setObject(key, impl);
} catch (Exception e) {
throw new RuntimeException("Couldn't create CollectionManager", e);
}
@@ -165,7 +167,7 @@ public class CollectionManager extends Configured {
/**
* Return names of collections url is part of
- *
+ *
* @param url
* The url to test against Collections
* @return Subcollections
@@ -203,8 +205,8 @@ public class CollectionManager extends Configured {
*/
public void save() throws IOException {
try {
- final FileOutputStream fos = new FileOutputStream(new File(configfile
- .getFile()));
+ final FileOutputStream fos = new FileOutputStream(new File(
+ configfile.getFile()));
final Document doc = new DocumentImpl();
final Element collections = doc
.createElement(Subcollection.TAG_COLLECTIONS);
diff --git a/src/plugin/subcollection/src/java/org/apache/nutch/collection/Subcollection.java b/src/plugin/subcollection/src/java/org/apache/nutch/collection/Subcollection.java
index 1d096ced1..13064eb4c 100644
--- a/src/plugin/subcollection/src/java/org/apache/nutch/collection/Subcollection.java
+++ b/src/plugin/subcollection/src/java/org/apache/nutch/collection/Subcollection.java
@@ -32,20 +32,20 @@ import org.w3c.dom.NodeList;
* SubCollection represents a subset of index, you can define url patterns that
* will indicate that particular page (url) is part of SubCollection.
*/
-public class Subcollection extends Configured implements URLFilter{
-
- public static final String TAG_COLLECTIONS="subcollections";
- public static final String TAG_COLLECTION="subcollection";
- public static final String TAG_WHITELIST="whitelist";
- public static final String TAG_BLACKLIST="blacklist";
- public static final String TAG_NAME="name";
- public static final String TAG_KEY="key";
- public static final String TAG_ID="id";
+public class Subcollection extends Configured implements URLFilter {
+
+ public static final String TAG_COLLECTIONS = "subcollections";
+ public static final String TAG_COLLECTION = "subcollection";
+ public static final String TAG_WHITELIST = "whitelist";
+ public static final String TAG_BLACKLIST = "blacklist";
+ public static final String TAG_NAME = "name";
+ public static final String TAG_KEY = "key";
+ public static final String TAG_ID = "id";
List<String> blackList = new ArrayList<String>();
List<String> whiteList = new ArrayList<String>();
- /**
+ /**
* SubCollection identifier
*/
String id;
@@ -55,12 +55,12 @@ public class Subcollection extends Configured implements URLFilter{
*/
String key;
- /**
+ /**
* SubCollection name
*/
String name;
- /**
+ /**
* SubCollection whitelist as String
*/
String wlString;
@@ -70,31 +70,37 @@ public class Subcollection extends Configured implements URLFilter{
*/
String blString;
- /** public Constructor
+ /**
+ * public Constructor
*
- * @param id id of SubCollection
- * @param name name of SubCollection
+ * @param id
+ * id of SubCollection
+ * @param name
+ * name of SubCollection
*/
public Subcollection(String id, String name, Configuration conf) {
this(id, name, null, conf);
}
- /** public Constructor
- *
- * @param id id of SubCollection
- * @param name name of SubCollection
+ /**
+ * public Constructor
+ *
+ * @param id
+ * id of SubCollection
+ * @param name
+ * name of SubCollection
*/
public Subcollection(String id, String name, String key, Configuration conf) {
this(conf);
- this.id=id;
+ this.id = id;
this.key = key;
this.name = name;
}
- public Subcollection(Configuration conf){
+ public Subcollection(Configuration conf) {
super(conf);
}
-
+
/**
* @return Returns the name
*/
@@ -232,7 +238,8 @@ public class Subcollection extends Configured implements URLFilter{
/**
* Set contents of blacklist from String
*
- * @param list the blacklist contents
+ * @param list
+ * the blacklist contents
*/
public void setBlackList(String list) {
this.blString = list;
@@ -242,7 +249,8 @@ public class Subcollection extends Configured implements URLFilter{
/**
* Set contents of whitelist from String
*
- * @param list the whitelist contents
+ * @param list
+ * the whitelist contents
*/
public void setWhiteList(String list) {
this.wlString = list;
diff --git a/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java b/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java
index be39a4a28..2946d9e32 100644
--- a/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java
+++ b/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java
@@ -35,21 +35,22 @@ import org.apache.nutch.collection.Subcollection;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
-
-public class SubcollectionIndexingFilter extends Configured implements IndexingFilter {
+public class SubcollectionIndexingFilter extends Configured implements
+ IndexingFilter {
private Configuration conf;
- public SubcollectionIndexingFilter(){
+ public SubcollectionIndexingFilter() {
super(NutchConfiguration.create());
}
-
+
public SubcollectionIndexingFilter(Configuration conf) {
super(conf);
}
-
+
/**
- * @param Configuration conf
+ * @param Configuration
+ * conf
*/
public void setConf(Configuration conf) {
this.conf = conf;
@@ -63,7 +64,6 @@ public class SubcollectionIndexingFilter extends Configured implements IndexingF
return this.conf;
}
-
/**
* Doc field name
*/
@@ -72,7 +72,8 @@ public class SubcollectionIndexingFilter extends Configured implements IndexingF
/**
* Logger
*/
- public static final Logger LOG = LoggerFactory.getLogger(SubcollectionIndexingFilter.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(SubcollectionIndexingFilter.class);
/**
* "Mark" document to be a part of subcollection
@@ -81,7 +82,8 @@ public class SubcollectionIndexingFilter extends Configured implements IndexingF
* @param url
*/
private void addSubCollectionField(NutchDocument doc, String url) {
- for (Subcollection coll : CollectionManager.getCollectionManager(getConf()).getSubCollections(url)) {
+ for (Subcollection coll : CollectionManager.getCollectionManager(getConf())
+ .getSubCollections(url)) {
if (coll.getKey() == null) {
doc.add(fieldName, coll.getName());
} else {
@@ -90,7 +92,8 @@ public class SubcollectionIndexingFilter extends Configured implements IndexingF
}
}
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException {
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
String sUrl = url.toString();
addSubCollectionField(doc, sUrl);
return doc;
diff --git a/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/package-info.java b/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/package-info.java
index 277aed3e5..1c6ba7295 100644
--- a/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/package-info.java
+++ b/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/package-info.java
@@ -22,3 +22,4 @@
* {@link org.apache.nutch.collection}.
*/
package org.apache.nutch.indexer.subcollection;
+
diff --git a/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java b/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java
index c625f2328..a2d277276 100644
--- a/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java
+++ b/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java
@@ -25,31 +25,34 @@ import org.junit.Assert;
import org.junit.Test;
public class TestSubcollection {
-
- /**Test filtering logic
+
+ /**
+ * Test filtering logic
*
* @throws Exception
*/
@Test
public void testFilter() throws Exception {
- Subcollection sc=new Subcollection(NutchConfiguration.create());
+ Subcollection sc = new Subcollection(NutchConfiguration.create());
sc.setWhiteList("www.nutch.org\nwww.apache.org");
sc.setBlackList("jpg\nwww.apache.org/zecret/");
-
- //matches whitelist
- Assert.assertEquals("http://www.apache.org/index.html", sc.filter("http://www.apache.org/index.html"));
-
- //matches blacklist
- Assert.assertEquals(null, sc.filter("http://www.apache.org/zecret/index.html"));
+
+ // matches whitelist
+ Assert.assertEquals("http://www.apache.org/index.html",
+ sc.filter("http://www.apache.org/index.html"));
+
+ // matches blacklist
+ Assert.assertEquals(null,
+ sc.filter("http://www.apache.org/zecret/index.html"));
Assert.assertEquals(null, sc.filter("http://www.apache.org/img/image.jpg"));
-
- //no match
+
+ // no match
Assert.assertEquals(null, sc.filter("http://www.google.com/"));
}
-
+
@Test
- public void testInput(){
- StringBuffer xml=new StringBuffer();
+ public void testInput() {
+ StringBuffer xml = new StringBuffer();
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xml.append("<!-- just a comment -->");
xml.append("<subcollections>");
@@ -65,44 +68,45 @@ public class TestSubcollection {
xml.append("</blacklist>");
xml.append("</subcollection>");
xml.append("</subcollections>");
-
- InputStream is=new ByteArrayInputStream(xml.toString().getBytes());
-
- CollectionManager cm=new CollectionManager();
+
+ InputStream is = new ByteArrayInputStream(xml.toString().getBytes());
+
+ CollectionManager cm = new CollectionManager();
cm.parse(is);
-
- Collection<?> c=cm.getAll();
-
+
+ Collection<?> c = cm.getAll();
+
// test that size matches
- Assert.assertEquals(1,c.size());
-
- Subcollection collection=(Subcollection)c.toArray()[0];
-
- //test collection id
+ Assert.assertEquals(1, c.size());
+
+ Subcollection collection = (Subcollection) c.toArray()[0];
+
+ // test collection id
Assert.assertEquals("nutch", collection.getId());
-
- //test collection name
+
+ // test collection name
Assert.assertEquals("nutch collection", collection.getName());
- //test whitelist
- Assert.assertEquals(2,collection.whiteList.size());
-
- String wlUrl=(String)collection.whiteList.get(0);
+ // test whitelist
+ Assert.assertEquals(2, collection.whiteList.size());
+
+ String wlUrl = (String) collection.whiteList.get(0);
Assert.assertEquals("http://lucene.apache.org/nutch/", wlUrl);
- wlUrl=(String)collection.whiteList.get(1);
+ wlUrl = (String) collection.whiteList.get(1);
Assert.assertEquals("http://wiki.apache.org/nutch/", wlUrl);
-
- //matches whitelist
- Assert.assertEquals("http://lucene.apache.org/nutch/", collection.filter("http://lucene.apache.org/nutch/"));
- //test blacklist
- Assert.assertEquals(1,collection.blackList.size());
+ // matches whitelist
+ Assert.assertEquals("http://lucene.apache.org/nutch/",
+ collection.filter("http://lucene.apache.org/nutch/"));
+
+ // test blacklist
+ Assert.assertEquals(1, collection.blackList.size());
- String blUrl=(String)collection.blackList.get(0);
+ String blUrl = (String) collection.blackList.get(0);
Assert.assertEquals("http://www.xxx.yyy", blUrl);
- //no match
+ // no match
Assert.assertEquals(null, collection.filter("http://www.google.com/"));
}
}
diff --git a/src/plugin/tld/src/java/org/apache/nutch/indexer/tld/TLDIndexingFilter.java b/src/plugin/tld/src/java/org/apache/nutch/indexer/tld/TLDIndexingFilter.java
index 30e424937..cd7e19455 100644
--- a/src/plugin/tld/src/java/org/apache/nutch/indexer/tld/TLDIndexingFilter.java
+++ b/src/plugin/tld/src/java/org/apache/nutch/indexer/tld/TLDIndexingFilter.java
@@ -34,23 +34,25 @@ import org.apache.nutch.util.domain.DomainSuffix;
/**
* Adds the Top level domain extensions to the index
+ *
* @author Enis Soztutar &lt;[email protected]&gt;
*/
public class TLDIndexingFilter implements IndexingFilter {
- public static final Logger LOG = LoggerFactory.getLogger(TLDIndexingFilter.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(TLDIndexingFilter.class);
private Configuration conf;
- public NutchDocument filter(NutchDocument doc, Parse parse, Text urlText, CrawlDatum datum, Inlinks inlinks)
- throws IndexingException {
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text urlText,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
try {
URL url = new URL(urlText.toString());
DomainSuffix d = URLUtil.getDomainSuffix(url);
-
+
doc.add("tld", d.getDomain());
-
- }catch (Exception ex) {
+
+ } catch (Exception ex) {
LOG.warn(ex.toString());
}
diff --git a/src/plugin/tld/src/java/org/apache/nutch/scoring/tld/TLDScoringFilter.java b/src/plugin/tld/src/java/org/apache/nutch/scoring/tld/TLDScoringFilter.java
index d86a88698..b7f496374 100644
--- a/src/plugin/tld/src/java/org/apache/nutch/scoring/tld/TLDScoringFilter.java
+++ b/src/plugin/tld/src/java/org/apache/nutch/scoring/tld/TLDScoringFilter.java
@@ -35,9 +35,9 @@ import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.util.domain.DomainSuffix;
import org.apache.nutch.util.domain.DomainSuffixes;
-
/**
* Scoring filter to boost tlds.
+ *
* @author Enis Soztutar &lt;[email protected]&gt;
*/
public class TLDScoringFilter implements ScoringFilter {
@@ -56,10 +56,10 @@ public class TLDScoringFilter implements ScoringFilter {
NutchField tlds = doc.getField("tld");
float boost = 1.0f;
- if(tlds != null) {
- for(Object tld : tlds.getValues()) {
+ if (tlds != null) {
+ for (Object tld : tlds.getValues()) {
DomainSuffix entry = tldEntries.get(tld.toString());
- if(entry != null)
+ if (entry != null)
boost *= entry.getBoost();
}
}
@@ -93,9 +93,8 @@ public class TLDScoringFilter implements ScoringFilter {
throws ScoringFilterException {
}
- public void updateDbScore(Text url, CrawlDatum old,
- CrawlDatum datum, List<CrawlDatum> inlinked)
- throws ScoringFilterException {
+ public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
+ List<CrawlDatum> inlinked) throws ScoringFilterException {
}
public Configuration getConf() {
@@ -105,9 +104,10 @@ public class TLDScoringFilter implements ScoringFilter {
public void setConf(Configuration conf) {
this.conf = conf;
}
- public CrawlDatum distributeScoreToOutlinks(Text fromUrl, ParseData parseData,
- Collection<Entry<Text, CrawlDatum>> targets, CrawlDatum adjust,
- int allCount) throws ScoringFilterException {
+
+ public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
+ ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
+ CrawlDatum adjust, int allCount) throws ScoringFilterException {
return adjust;
}
diff --git a/src/plugin/urlfilter-automaton/src/java/org/apache/nutch/urlfilter/automaton/AutomatonURLFilter.java b/src/plugin/urlfilter-automaton/src/java/org/apache/nutch/urlfilter/automaton/AutomatonURLFilter.java
index 850ddfb2b..979822563 100644
--- a/src/plugin/urlfilter-automaton/src/java/org/apache/nutch/urlfilter/automaton/AutomatonURLFilter.java
+++ b/src/plugin/urlfilter-automaton/src/java/org/apache/nutch/urlfilter/automaton/AutomatonURLFilter.java
@@ -32,12 +32,11 @@ import org.apache.nutch.net.*;
import org.apache.nutch.urlfilter.api.RegexRule;
import org.apache.nutch.urlfilter.api.RegexURLFilterBase;
-
/**
- * RegexURLFilterBase implementation based on the
- * <a href="http://www.brics.dk/automaton/">dk.brics.automaton</a>
- * Finite-State Automata for Java<sup>TM</sup>.
- *
+ * RegexURLFilterBase implementation based on the <a
+ * href="http://www.brics.dk/automaton/">dk.brics.automaton</a> Finite-State
+ * Automata for Java<sup>TM</sup>.
+ *
* @author J&eacute;r&ocirc;me Charron
* @see <a href="http://www.brics.dk/automaton/">dk.brics.automaton</a>
*/
@@ -49,24 +48,24 @@ public class AutomatonURLFilter extends RegexURLFilterBase {
super();
}
- public AutomatonURLFilter(String filename)
- throws IOException, PatternSyntaxException {
+ public AutomatonURLFilter(String filename) throws IOException,
+ PatternSyntaxException {
super(filename);
}
- AutomatonURLFilter(Reader reader)
- throws IOException, IllegalArgumentException {
+ AutomatonURLFilter(Reader reader) throws IOException,
+ IllegalArgumentException {
super(reader);
}
-
- /* ----------------------------------- *
- * <implementation:RegexURLFilterBase> *
- * ----------------------------------- */
-
+ /*
+ * ----------------------------------- * <implementation:RegexURLFilterBase> *
+ * -----------------------------------
+ */
+
/**
- * Rules specified as a config property will override rules specified
- * as a config file.
+ * Rules specified as a config property will override rules specified as a
+ * config file.
*/
protected Reader getRulesReader(Configuration conf) throws IOException {
String stringRules = conf.get(URLFILTER_AUTOMATON_RULES);
@@ -81,21 +80,20 @@ public class AutomatonURLFilter extends RegexURLFilterBase {
protected RegexRule createRule(boolean sign, String regex) {
return new Rule(sign, regex);
}
-
- /* ------------------------------------ *
- * </implementation:RegexURLFilterBase> *
- * ------------------------------------ */
-
+ /*
+ * ------------------------------------ * </implementation:RegexURLFilterBase>
+ * * ------------------------------------
+ */
+
public static void main(String args[]) throws IOException {
main(new AutomatonURLFilter(), args);
}
-
private class Rule extends RegexRule {
-
+
private RunAutomaton automaton;
-
+
Rule(boolean sign, String regex) {
super(sign, regex);
automaton = new RunAutomaton(new RegExp(regex, RegExp.ALL).toAutomaton());
@@ -105,5 +103,5 @@ public class AutomatonURLFilter extends RegexURLFilterBase {
return automaton.run(url);
}
}
-
+
}
diff --git a/src/plugin/urlfilter-automaton/src/test/org/apache/nutch/urlfilter/automaton/TestAutomatonURLFilter.java b/src/plugin/urlfilter-automaton/src/test/org/apache/nutch/urlfilter/automaton/TestAutomatonURLFilter.java
index ac104e025..a70a6b6f7 100644
--- a/src/plugin/urlfilter-automaton/src/test/org/apache/nutch/urlfilter/automaton/TestAutomatonURLFilter.java
+++ b/src/plugin/urlfilter-automaton/src/test/org/apache/nutch/urlfilter/automaton/TestAutomatonURLFilter.java
@@ -26,10 +26,9 @@ import org.apache.nutch.urlfilter.api.RegexURLFilterBaseTest;
import org.junit.Assert;
import org.junit.Test;
-
/**
* JUnit based test of class <code>AutomatonURLFilter</code>.
- *
+ *
* @author J&eacute;r&ocirc;me Charron
*/
public class TestAutomatonURLFilter extends RegexURLFilterBaseTest {
@@ -42,7 +41,7 @@ public class TestAutomatonURLFilter extends RegexURLFilterBaseTest {
return null;
}
}
-
+
@Test
public void test() {
test("WholeWebCrawling");
diff --git a/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java b/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
index d83830005..230eaa32c 100644
--- a/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
+++ b/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
@@ -35,35 +35,48 @@ import org.apache.nutch.util.URLUtil;
import org.apache.nutch.util.domain.DomainSuffix;
/**
- * <p>Filters URLs based on a file containing domain suffixes, domain names, and
+ * <p>
+ * Filters URLs based on a file containing domain suffixes, domain names, and
* hostnames. Only a url that matches one of the suffixes, domains, or hosts
- * present in the file is allowed.</p>
+ * present in the file is allowed.
+ * </p>
*
- * <p>Urls are checked in order of domain suffix, domain name, and hostname
- * against entries in the domain file. The domain file would be setup as follows
- * with one entry per line:
+ * <p>
+ * Urls are checked in order of domain suffix, domain name, and hostname against
+ * entries in the domain file. The domain file would be setup as follows with
+ * one entry per line:
*
- * <pre> com apache.org www.apache.org </pre>
+ * <pre>
+ * com apache.org www.apache.org
+ * </pre>
*
- * <p>The first line is an example of a filter that would allow all .com
- * domains. The second line allows all urls from apache.org and all of its
- * subdomains such as lucene.apache.org and hadoop.apache.org. The third line
- * would allow only urls from www.apache.org. There is no specific ordering to
- * entries. The entries are from more general to more specific with the more
- * general overridding the more specific.</p>
+ * <p>
+ * The first line is an example of a filter that would allow all .com domains.
+ * The second line allows all urls from apache.org and all of its subdomains
+ * such as lucene.apache.org and hadoop.apache.org. The third line would allow
+ * only urls from www.apache.org. There is no specific ordering to entries. The
+ * entries are from more general to more specific with the more general
+ * overridding the more specific.
+ * </p>
*
* The domain file defaults to domain-urlfilter.txt in the classpath but can be
* overridden using the:
*
- * <ul> <ol>property "urlfilter.domain.file" in ./conf/nutch-*.xml, and</ol>
- * <ol>attribute "file" in plugin.xml of this plugin</ol> </ul>
+ * <ul>
+ * <ol>
+ * property "urlfilter.domain.file" in ./conf/nutch-*.xml, and
+ * </ol>
+ * <ol>
+ * attribute "file" in plugin.xml of this plugin
+ * </ol>
+ * </ul>
*
* the attribute "file" has higher precedence if defined.
*/
-public class DomainURLFilter
- implements URLFilter {
+public class DomainURLFilter implements URLFilter {
- private static final Logger LOG = LoggerFactory.getLogger(DomainURLFilter.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DomainURLFilter.class);
// read in attribute "file" of this plugin.
private static String attributeFile = null;
@@ -71,8 +84,7 @@ public class DomainURLFilter
private String domainFile = null;
private Set<String> domainSet = new LinkedHashSet<String>();
- private void readConfiguration(Reader configReader)
- throws IOException {
+ private void readConfiguration(Reader configReader) throws IOException {
// read the configuration file, line by line
BufferedReader reader = new BufferedReader(configReader);
@@ -95,7 +107,8 @@ public class DomainURLFilter
/**
* Constructor that specifies the domain file to use.
*
- * @param domainFile The domain file, overrides domain-urlfilter.text default.
+ * @param domainFile
+ * The domain file, overrides domain-urlfilter.text default.
*
* @throws IOException
*/
@@ -111,8 +124,8 @@ public class DomainURLFilter
// get the extensions for domain urlfilter
String pluginName = "urlfilter-domain";
- Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(
- URLFilter.class.getName()).getExtensions();
+ Extension[] extensions = PluginRepository.get(conf)
+ .getExtensionPoint(URLFilter.class.getName()).getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
if (extension.getDescriptor().getPluginId().equals(pluginName)) {
@@ -120,32 +133,30 @@ public class DomainURLFilter
break;
}
}
-
+
// handle blank non empty input
if (attributeFile != null && attributeFile.trim().equals("")) {
attributeFile = null;
}
-
+
if (attributeFile != null) {
if (LOG.isInfoEnabled()) {
LOG.info("Attribute \"file\" is defined for plugin " + pluginName
- + " as " + attributeFile);
+ + " as " + attributeFile);
}
- }
- else {
+ } else {
if (LOG.isWarnEnabled()) {
LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin "
- + pluginName);
+ + pluginName);
}
}
// domain file and attribute "file" take precedence if defined
- String file = conf.get("urlfilter.domain.file");
+ String file = conf.get("urlfilter.domain.file");
String stringRules = conf.get("urlfilter.domain.rules");
if (domainFile != null) {
file = domainFile;
- }
- else if (attributeFile != null) {
+ } else if (attributeFile != null) {
file = attributeFile;
}
Reader reader = null;
@@ -159,8 +170,7 @@ public class DomainURLFilter
reader = new FileReader(file);
}
readConfiguration(reader);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e));
}
}
@@ -173,7 +183,7 @@ public class DomainURLFilter
try {
- // match for suffix, domain, and host in that order. more general will
+ // match for suffix, domain, and host in that order. more general will
// override more specific
String domain = URLUtil.getDomainName(url).toLowerCase().trim();
String host = URLUtil.getHost(url);
@@ -182,20 +192,19 @@ public class DomainURLFilter
if (domainSuffix != null) {
suffix = domainSuffix.getDomain();
}
-
+
if (domainSet.contains(suffix) || domainSet.contains(domain)
- || domainSet.contains(host)) {
+ || domainSet.contains(host)) {
return url;
}
// doesn't match, don't allow
return null;
- }
- catch (Exception e) {
-
+ } catch (Exception e) {
+
// if an error happens, allow the url to pass
LOG.error("Could not apply filter on url: " + url + "\n"
- + org.apache.hadoop.util.StringUtils.stringifyException(e));
+ + org.apache.hadoop.util.StringUtils.stringifyException(e));
return null;
}
}
diff --git a/src/plugin/urlfilter-domain/src/test/org/apache/nutch/urlfilter/domain/TestDomainURLFilter.java b/src/plugin/urlfilter-domain/src/test/org/apache/nutch/urlfilter/domain/TestDomainURLFilter.java
index e10bb8e29..466fd78b6 100644
--- a/src/plugin/urlfilter-domain/src/test/org/apache/nutch/urlfilter/domain/TestDomainURLFilter.java
+++ b/src/plugin/urlfilter-domain/src/test/org/apache/nutch/urlfilter/domain/TestDomainURLFilter.java
@@ -23,13 +23,11 @@ import org.junit.Test;
public class TestDomainURLFilter {
-
private final static String SEPARATOR = System.getProperty("file.separator");
private final static String SAMPLES = System.getProperty("test.data", ".");
@Test
- public void testFilter()
- throws Exception {
+ public void testFilter() throws Exception {
String domainFile = SAMPLES + SEPARATOR + "hosts.txt";
Configuration conf = NutchConfiguration.create();
diff --git a/src/plugin/urlfilter-domainblacklist/src/java/org/apache/nutch/urlfilter/domainblacklist/DomainBlacklistURLFilter.java b/src/plugin/urlfilter-domainblacklist/src/java/org/apache/nutch/urlfilter/domainblacklist/DomainBlacklistURLFilter.java
index 110083e5c..37b1cdc7c 100644
--- a/src/plugin/urlfilter-domainblacklist/src/java/org/apache/nutch/urlfilter/domainblacklist/DomainBlacklistURLFilter.java
+++ b/src/plugin/urlfilter-domainblacklist/src/java/org/apache/nutch/urlfilter/domainblacklist/DomainBlacklistURLFilter.java
@@ -35,35 +35,48 @@ import org.apache.nutch.util.URLUtil;
import org.apache.nutch.util.domain.DomainSuffix;
/**
- * <p>Filters URLs based on a file containing domain suffixes, domain names, and
- * hostnames. A url that matches one of the suffixes, domains, or hosts
- * present in the file is filtered out.</p>
+ * <p>
+ * Filters URLs based on a file containing domain suffixes, domain names, and
+ * hostnames. A url that matches one of the suffixes, domains, or hosts present
+ * in the file is filtered out.
+ * </p>
*
- * <p>Urls are checked in order of domain suffix, domain name, and hostname
- * against entries in the domain file. The domain file would be setup as follows
- * with one entry per line:
+ * <p>
+ * Urls are checked in order of domain suffix, domain name, and hostname against
+ * entries in the domain file. The domain file would be setup as follows with
+ * one entry per line:
*
- * <pre> com apache.org www.apache.org </pre>
+ * <pre>
+ * com apache.org www.apache.org
+ * </pre>
*
- * <p>The first line is an example of a filter that would allow all .com
- * domains. The second line allows all urls from apache.org and all of its
- * subdomains such as lucene.apache.org and hadoop.apache.org. The third line
- * would allow only urls from www.apache.org. There is no specific ordering to
- * entries. The entries are from more general to more specific with the more
- * general overridding the more specific.</p>
+ * <p>
+ * The first line is an example of a filter that would allow all .com domains.
+ * The second line allows all urls from apache.org and all of its subdomains
+ * such as lucene.apache.org and hadoop.apache.org. The third line would allow
+ * only urls from www.apache.org. There is no specific ordering to entries. The
+ * entries are from more general to more specific with the more general
+ * overridding the more specific.
+ * </p>
*
- * The domain file defaults to domainblacklist-urlfilter.txt in the classpath but can be
- * overridden using the:
+ * The domain file defaults to domainblacklist-urlfilter.txt in the classpath
+ * but can be overridden using the:
*
- * <ul> <ol>property "urlfilter.domainblacklist.file" in ./conf/nutch-*.xml, and</ol>
- * <ol>attribute "file" in plugin.xml of this plugin</ol> </ul>
+ * <ul>
+ * <ol>
+ * property "urlfilter.domainblacklist.file" in ./conf/nutch-*.xml, and
+ * </ol>
+ * <ol>
+ * attribute "file" in plugin.xml of this plugin
+ * </ol>
+ * </ul>
*
* the attribute "file" has higher precedence if defined.
*/
-public class DomainBlacklistURLFilter
- implements URLFilter {
+public class DomainBlacklistURLFilter implements URLFilter {
- private static final Logger LOG = LoggerFactory.getLogger(DomainBlacklistURLFilter.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DomainBlacklistURLFilter.class);
// read in attribute "file" of this plugin.
private static String attributeFile = null;
@@ -71,8 +84,7 @@ public class DomainBlacklistURLFilter
private String domainFile = null;
private Set<String> domainSet = new LinkedHashSet<String>();
- private void readConfiguration(Reader configReader)
- throws IOException {
+ private void readConfiguration(Reader configReader) throws IOException {
// read the configuration file, line by line
BufferedReader reader = new BufferedReader(configReader);
@@ -95,7 +107,8 @@ public class DomainBlacklistURLFilter
/**
* Constructor that specifies the domain file to use.
*
- * @param domainFile The domain file, overrides domainblacklist-urlfilter.text default.
+ * @param domainFile
+ * The domain file, overrides domainblacklist-urlfilter.text default.
*
* @throws IOException
*/
@@ -111,8 +124,8 @@ public class DomainBlacklistURLFilter
// get the extensions for domain urlfilter
String pluginName = "urlfilter-domainblacklist";
- Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(
- URLFilter.class.getName()).getExtensions();
+ Extension[] extensions = PluginRepository.get(conf)
+ .getExtensionPoint(URLFilter.class.getName()).getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
if (extension.getDescriptor().getPluginId().equals(pluginName)) {
@@ -129,23 +142,21 @@ public class DomainBlacklistURLFilter
if (attributeFile != null) {
if (LOG.isInfoEnabled()) {
LOG.info("Attribute \"file\" is defined for plugin " + pluginName
- + " as " + attributeFile);
+ + " as " + attributeFile);
}
- }
- else {
+ } else {
if (LOG.isWarnEnabled()) {
LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin "
- + pluginName);
+ + pluginName);
}
}
// domain file and attribute "file" take precedence if defined
- String file = conf.get("urlfilter.domainblacklist.file");
+ String file = conf.get("urlfilter.domainblacklist.file");
String stringRules = conf.get("urlfilter.domainblacklist.rules");
if (domainFile != null) {
file = domainFile;
- }
- else if (attributeFile != null) {
+ } else if (attributeFile != null) {
file = attributeFile;
}
Reader reader = null;
@@ -159,8 +170,7 @@ public class DomainBlacklistURLFilter
reader = new FileReader(file);
}
readConfiguration(reader);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e));
}
}
@@ -171,7 +181,7 @@ public class DomainBlacklistURLFilter
public String filter(String url) {
try {
- // match for suffix, domain, and host in that order. more general will
+ // match for suffix, domain, and host in that order. more general will
// override more specific
String domain = URLUtil.getDomainName(url).toLowerCase().trim();
String host = URLUtil.getHost(url);
@@ -182,19 +192,18 @@ public class DomainBlacklistURLFilter
}
if (domainSet.contains(suffix) || domainSet.contains(domain)
- || domainSet.contains(host)) {
+ || domainSet.contains(host)) {
// Matches, filter!
return null;
}
// doesn't match, allow
return url;
- }
- catch (Exception e) {
+ } catch (Exception e) {
// if an error happens, allow the url to pass
LOG.error("Could not apply filter on url: " + url + "\n"
- + org.apache.hadoop.util.StringUtils.stringifyException(e));
+ + org.apache.hadoop.util.StringUtils.stringifyException(e));
return null;
}
}
diff --git a/src/plugin/urlfilter-domainblacklist/src/test/org/apache/nutch/urlfilter/domainblacklist/TestDomainBlacklistURLFilter.java b/src/plugin/urlfilter-domainblacklist/src/test/org/apache/nutch/urlfilter/domainblacklist/TestDomainBlacklistURLFilter.java
index 03aff629f..d25386729 100644
--- a/src/plugin/urlfilter-domainblacklist/src/test/org/apache/nutch/urlfilter/domainblacklist/TestDomainBlacklistURLFilter.java
+++ b/src/plugin/urlfilter-domainblacklist/src/test/org/apache/nutch/urlfilter/domainblacklist/TestDomainBlacklistURLFilter.java
@@ -27,12 +27,12 @@ public class TestDomainBlacklistURLFilter {
private final static String SAMPLES = System.getProperty("test.data", ".");
@Test
- public void testFilter()
- throws Exception {
+ public void testFilter() throws Exception {
String domainBlacklistFile = SAMPLES + SEPARATOR + "hosts.txt";
Configuration conf = NutchConfiguration.create();
- DomainBlacklistURLFilter domainBlacklistFilter = new DomainBlacklistURLFilter(domainBlacklistFile);
+ DomainBlacklistURLFilter domainBlacklistFilter = new DomainBlacklistURLFilter(
+ domainBlacklistFile);
domainBlacklistFilter.setConf(conf);
Assert.assertNull(domainBlacklistFilter.filter("http://lucene.apache.org"));
Assert.assertNull(domainBlacklistFilter.filter("http://hadoop.apache.org"));
diff --git a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
index 212481607..2e955b510 100644
--- a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
+++ b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
@@ -39,16 +39,19 @@ import java.util.List;
import java.util.ArrayList;
/**
- * Filters URLs based on a file of URL prefixes. The file is named by
- * (1) property "urlfilter.prefix.file" in ./conf/nutch-default.xml, and
- * (2) attribute "file" in plugin.xml of this plugin
- * Attribute "file" has higher precedence if defined.
- *
- * <p>The format of this file is one URL prefix per line.</p>
+ * Filters URLs based on a file of URL prefixes. The file is named by (1)
+ * property "urlfilter.prefix.file" in ./conf/nutch-default.xml, and (2)
+ * attribute "file" in plugin.xml of this plugin Attribute "file" has higher
+ * precedence if defined.
+ *
+ * <p>
+ * The format of this file is one URL prefix per line.
+ * </p>
*/
public class PrefixURLFilter implements URLFilter {
- private static final Logger LOG = LoggerFactory.getLogger(PrefixURLFilter.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(PrefixURLFilter.class);
// read in attribute "file" of this plugin.
private static String attributeFile = null;
@@ -58,7 +61,7 @@ public class PrefixURLFilter implements URLFilter {
private Configuration conf;
public PrefixURLFilter() throws IOException {
-
+
}
public PrefixURLFilter(String stringRules) throws IOException {
@@ -72,43 +75,43 @@ public class PrefixURLFilter implements URLFilter {
return url;
}
- private TrieStringMatcher readConfiguration(Reader reader)
- throws IOException {
-
- BufferedReader in=new BufferedReader(reader);
+ private TrieStringMatcher readConfiguration(Reader reader) throws IOException {
+
+ BufferedReader in = new BufferedReader(reader);
List<String> urlprefixes = new ArrayList<String>();
String line;
- while((line=in.readLine())!=null) {
+ while ((line = in.readLine()) != null) {
if (line.length() == 0)
continue;
- char first=line.charAt(0);
+ char first = line.charAt(0);
switch (first) {
- case ' ' : case '\n' : case '#' : // skip blank & comment lines
+ case ' ':
+ case '\n':
+ case '#': // skip blank & comment lines
continue;
- default :
- urlprefixes.add(line);
+ default:
+ urlprefixes.add(line);
}
}
return new PrefixStringMatcher(urlprefixes);
}
- public static void main(String args[])
- throws IOException {
-
+ public static void main(String args[]) throws IOException {
+
PrefixURLFilter filter;
if (args.length >= 1)
filter = new PrefixURLFilter(args[0]);
else
filter = new PrefixURLFilter();
-
- BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
+
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
- while((line=in.readLine())!=null) {
- String out=filter.filter(line);
- if(out!=null) {
+ while ((line = in.readLine()) != null) {
+ String out = filter.filter(line);
+ if (out != null) {
System.out.println(out);
}
}
@@ -118,8 +121,8 @@ public class PrefixURLFilter implements URLFilter {
this.conf = conf;
String pluginName = "urlfilter-prefix";
- Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(
- URLFilter.class.getName()).getExtensions();
+ Extension[] extensions = PluginRepository.get(conf)
+ .getExtensionPoint(URLFilter.class.getName()).getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
if (extension.getDescriptor().getPluginId().equals(pluginName)) {
@@ -136,8 +139,8 @@ public class PrefixURLFilter implements URLFilter {
}
} else {
// if (LOG.isWarnEnabled()) {
- // LOG.warn("Attribute \"file\" is not defined in plugin.xml for
- // plugin "+pluginName);
+ // LOG.warn("Attribute \"file\" is not defined in plugin.xml for
+ // plugin "+pluginName);
// }
}
@@ -159,7 +162,9 @@ public class PrefixURLFilter implements URLFilter {
try {
trie = readConfiguration(reader);
} catch (IOException e) {
- if (LOG.isErrorEnabled()) { LOG.error(e.getMessage()); }
+ if (LOG.isErrorEnabled()) {
+ LOG.error(e.getMessage());
+ }
// TODO [email protected]: throw Exception? Because broken api.
throw new RuntimeException(e.getMessage(), e);
}
@@ -169,5 +174,5 @@ public class PrefixURLFilter implements URLFilter {
public Configuration getConf() {
return this.conf;
}
-
+
}
diff --git a/src/plugin/urlfilter-regex/src/java/org/apache/nutch/urlfilter/regex/RegexURLFilter.java b/src/plugin/urlfilter-regex/src/java/org/apache/nutch/urlfilter/regex/RegexURLFilter.java
index 858734a32..3835c66b6 100644
--- a/src/plugin/urlfilter-regex/src/java/org/apache/nutch/urlfilter/regex/RegexURLFilter.java
+++ b/src/plugin/urlfilter-regex/src/java/org/apache/nutch/urlfilter/regex/RegexURLFilter.java
@@ -28,13 +28,12 @@ import org.apache.nutch.urlfilter.api.RegexRule;
import org.apache.nutch.urlfilter.api.RegexURLFilterBase;
import org.apache.nutch.util.NutchConfiguration;
-
/**
* Filters URLs based on a file of regular expressions using the
* {@link java.util.regex Java Regex implementation}.
*/
public class RegexURLFilter extends RegexURLFilterBase {
-
+
public static final String URLFILTER_REGEX_FILE = "urlfilter.regex.file";
public static final String URLFILTER_REGEX_RULES = "urlfilter.regex.rules";
@@ -42,24 +41,23 @@ public class RegexURLFilter extends RegexURLFilterBase {
super();
}
- public RegexURLFilter(String filename)
- throws IOException, PatternSyntaxException {
+ public RegexURLFilter(String filename) throws IOException,
+ PatternSyntaxException {
super(filename);
}
- RegexURLFilter(Reader reader)
- throws IOException, IllegalArgumentException {
+ RegexURLFilter(Reader reader) throws IOException, IllegalArgumentException {
super(reader);
}
-
- /* ----------------------------------- *
- * <implementation:RegexURLFilterBase> *
- * ----------------------------------- */
-
+ /*
+ * ----------------------------------- * <implementation:RegexURLFilterBase> *
+ * -----------------------------------
+ */
+
/**
- * Rules specified as a config property will override rules specified
- * as a config file.
+ * Rules specified as a config property will override rules specified as a
+ * config file.
*/
protected Reader getRulesReader(Configuration conf) throws IOException {
String stringRules = conf.get(URLFILTER_REGEX_RULES);
@@ -74,23 +72,22 @@ public class RegexURLFilter extends RegexURLFilterBase {
protected RegexRule createRule(boolean sign, String regex) {
return new Rule(sign, regex);
}
-
- /* ------------------------------------ *
- * </implementation:RegexURLFilterBase> *
- * ------------------------------------ */
-
+ /*
+ * ------------------------------------ * </implementation:RegexURLFilterBase>
+ * * ------------------------------------
+ */
+
public static void main(String args[]) throws IOException {
RegexURLFilter filter = new RegexURLFilter();
filter.setConf(NutchConfiguration.create());
main(filter, args);
}
-
private class Rule extends RegexRule {
-
+
private Pattern pattern;
-
+
Rule(boolean sign, String regex) {
super(sign, regex);
pattern = Pattern.compile(regex);
@@ -100,5 +97,5 @@ public class RegexURLFilter extends RegexURLFilterBase {
return pattern.matcher(url).find();
}
}
-
+
}
diff --git a/src/plugin/urlfilter-regex/src/test/org/apache/nutch/urlfilter/regex/TestRegexURLFilter.java b/src/plugin/urlfilter-regex/src/test/org/apache/nutch/urlfilter/regex/TestRegexURLFilter.java
index a0448bf9d..395dc11a5 100644
--- a/src/plugin/urlfilter-regex/src/test/org/apache/nutch/urlfilter/regex/TestRegexURLFilter.java
+++ b/src/plugin/urlfilter-regex/src/test/org/apache/nutch/urlfilter/regex/TestRegexURLFilter.java
@@ -26,15 +26,13 @@ import org.apache.nutch.urlfilter.api.RegexURLFilterBaseTest;
import org.junit.Assert;
import org.junit.Test;
-
/**
* JUnit based test of class <code>RegexURLFilter</code>.
- *
+ *
* @author J&eacute;r&ocirc;me Charron
*/
public class TestRegexURLFilter extends RegexURLFilterBaseTest {
-
protected URLFilter getURLFilter(Reader rules) {
try {
return new RegexURLFilter(rules);
@@ -43,7 +41,7 @@ public class TestRegexURLFilter extends RegexURLFilterBaseTest {
return null;
}
}
-
+
@Test
public void test() {
test("WholeWebCrawling");
diff --git a/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java b/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
index 43bf5f630..6c14e63ce 100644
--- a/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
+++ b/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
@@ -51,14 +51,15 @@ import java.net.MalformedURLException;
* Attribute "file" has higher precedence if defined. If the config file is
* missing, all URLs will be rejected.
*
- * <p>This filter can be configured to work in one of two modes:
+ * <p>
+ * This filter can be configured to work in one of two modes:
* <ul>
- * <li><b>default to reject</b> ('-'): in this mode, only URLs that match suffixes
- * specified in the config file will be accepted, all other URLs will be
- * rejected.</li>
- * <li><b>default to accept</b> ('+'): in this mode, only URLs that match suffixes
- * specified in the config file will be rejected, all other URLs will be
- * accepted.</li>
+ * <li><b>default to reject</b> ('-'): in this mode, only URLs that match
+ * suffixes specified in the config file will be accepted, all other URLs will
+ * be rejected.</li>
+ * <li><b>default to accept</b> ('+'): in this mode, only URLs that match
+ * suffixes specified in the config file will be rejected, all other URLs will
+ * be accepted.</li>
* </ul>
* <p>
* The format of this config file is one URL suffix per line, with no preceding
@@ -67,10 +68,10 @@ import java.net.MalformedURLException;
* </p>
* <p>
* A single '+' or '-' sign not followed by any suffix must be used once, to
- * signify the mode this plugin operates in. An optional single 'I' can be appended,
- * to signify that suffix matches should be case-insensitive. The default, if
- * not specified, is to use case-sensitive matches, i.e. suffix '.JPG'
- * does not match '.jpg'.
+ * signify the mode this plugin operates in. An optional single 'I' can be
+ * appended, to signify that suffix matches should be case-insensitive. The
+ * default, if not specified, is to use case-sensitive matches, i.e. suffix
+ * '.JPG' does not match '.jpg'.
* </p>
* <p>
* NOTE: the format of this file is different from urlfilter-prefix, because
@@ -82,8 +83,8 @@ import java.net.MalformedURLException;
* <h4>Example 1</h4>
* <p>
* The configuration shown below will accept all URLs with '.html' or '.htm'
- * suffixes (case-sensitive - '.HTML' or '.HTM' will be rejected),
- * and prohibit all other suffixes.
+ * suffixes (case-sensitive - '.HTML' or '.HTM' will be rejected), and prohibit
+ * all other suffixes.
* <p>
*
* <pre>
@@ -91,7 +92,7 @@ import java.net.MalformedURLException;
*
* # prohibit all unknown, case-sensitive matching
* -
- *
+ *
* # collect only HTML files.
* .html
* .htm
@@ -119,11 +120,13 @@ import java.net.MalformedURLException;
* </pre>
*
* </p>
+ *
* @author Andrzej Bialecki
*/
public class SuffixURLFilter implements URLFilter {
- private static final Logger LOG = LoggerFactory.getLogger(SuffixURLFilter.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(SuffixURLFilter.class);
// read in attribute "file" of this plugin.
private String attributeFile = null;
@@ -144,11 +147,13 @@ public class SuffixURLFilter implements URLFilter {
}
public String filter(String url) {
- if (url == null) return null;
+ if (url == null)
+ return null;
String _url;
if (ignoreCase)
_url = url.toLowerCase();
- else _url = url;
+ else
+ _url = url;
if (filterFromPath) {
try {
URL pUrl = new URL(_url);
@@ -160,11 +165,15 @@ public class SuffixURLFilter implements URLFilter {
String a = suffixes.shortestMatch(_url);
if (a == null) {
- if (modeAccept) return url;
- else return null;
+ if (modeAccept)
+ return url;
+ else
+ return null;
} else {
- if (modeAccept) return null;
- else return url;
+ if (modeAccept)
+ return null;
+ else
+ return url;
}
}
@@ -187,30 +196,31 @@ public class SuffixURLFilter implements URLFilter {
String line;
while ((line = in.readLine()) != null) {
- if (line.length() == 0) continue;
+ if (line.length() == 0)
+ continue;
char first = line.charAt(0);
switch (first) {
- case ' ':
- case '\n':
- case '#': // skip blank & comment lines
- break;
- case '-':
- allow = false;
- if(line.contains("P"))
- filterFromPath = true;
- if(line.contains("I"))
- ignore = true;
- break;
- case '+':
- allow = true;
- if(line.contains("P"))
- filterFromPath = true;
- if(line.contains("I"))
- ignore = true;
- break;
- default:
- aSuffixes.add(line);
+ case ' ':
+ case '\n':
+ case '#': // skip blank & comment lines
+ break;
+ case '-':
+ allow = false;
+ if (line.contains("P"))
+ filterFromPath = true;
+ if (line.contains("I"))
+ ignore = true;
+ break;
+ case '+':
+ allow = true;
+ if (line.contains("P"))
+ filterFromPath = true;
+ if (line.contains("I"))
+ ignore = true;
+ break;
+ default:
+ aSuffixes.add(line);
}
}
if (ignore) {
@@ -249,7 +259,8 @@ public class SuffixURLFilter implements URLFilter {
this.conf = conf;
String pluginName = "urlfilter-suffix";
- Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(URLFilter.class.getName()).getExtensions();
+ Extension[] extensions = PluginRepository.get(conf)
+ .getExtensionPoint(URLFilter.class.getName()).getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
if (extension.getDescriptor().getPluginId().equals(pluginName)) {
@@ -257,22 +268,25 @@ public class SuffixURLFilter implements URLFilter {
break;
}
}
- if (attributeFile != null && attributeFile.trim().equals("")) attributeFile = null;
+ if (attributeFile != null && attributeFile.trim().equals(""))
+ attributeFile = null;
if (attributeFile != null) {
if (LOG.isInfoEnabled()) {
- LOG.info("Attribute \"file\" is defined for plugin " + pluginName + " as " + attributeFile);
+ LOG.info("Attribute \"file\" is defined for plugin " + pluginName
+ + " as " + attributeFile);
}
} else {
// if (LOG.isWarnEnabled()) {
- // LOG.warn("Attribute \"file\" is not defined in plugin.xml for
- // plugin "+pluginName);
+ // LOG.warn("Attribute \"file\" is not defined in plugin.xml for
+ // plugin "+pluginName);
// }
}
String file = conf.get("urlfilter.suffix.file");
String stringRules = conf.get("urlfilter.suffix.rules");
// attribute "file" takes precedence if defined
- if (attributeFile != null) file = attributeFile;
+ if (attributeFile != null)
+ file = attributeFile;
Reader reader = null;
if (stringRules != null) { // takes precedence over files
reader = new StringReader(stringRules);
@@ -283,7 +297,9 @@ public class SuffixURLFilter implements URLFilter {
try {
readConfiguration(reader);
} catch (IOException e) {
- if (LOG.isErrorEnabled()) { LOG.error(e.getMessage()); }
+ if (LOG.isErrorEnabled()) {
+ LOG.error(e.getMessage());
+ }
throw new RuntimeException(e.getMessage(), e);
}
}
diff --git a/src/plugin/urlfilter-suffix/src/test/org/apache/nutch/urlfilter/suffix/TestSuffixURLFilter.java b/src/plugin/urlfilter-suffix/src/test/org/apache/nutch/urlfilter/suffix/TestSuffixURLFilter.java
index f2a53570c..b09ca2f65 100644
--- a/src/plugin/urlfilter-suffix/src/test/org/apache/nutch/urlfilter/suffix/TestSuffixURLFilter.java
+++ b/src/plugin/urlfilter-suffix/src/test/org/apache/nutch/urlfilter/suffix/TestSuffixURLFilter.java
@@ -25,101 +25,45 @@ import org.junit.Test;
/**
* JUnit test for <code>SuffixURLFilter</code>.
- *
+ *
* @author Andrzej Bialecki
*/
public class TestSuffixURLFilter {
- private static final String suffixes =
- "# this is a comment\n" +
- "\n" +
- ".gif\n" +
- ".jpg\n" +
- ".js\n";
-
+ private static final String suffixes = "# this is a comment\n" + "\n"
+ + ".gif\n" + ".jpg\n" + ".js\n";
+
private static final String[] urls = new String[] {
- "http://www.example.com/test.gif",
- "http://www.example.com/TEST.GIF",
- "http://www.example.com/test.jpg",
- "http://www.example.com/test.JPG",
- "http://www.example.com/test.html",
- "http://www.example.com/test.HTML",
- "http://www.example.com/test.html?q=abc.js",
- "http://www.example.com/test.js?foo=bar&baz=bar#12333",
- };
-
- private static String[] urlsModeAccept = new String[] {
- null,
- urls[1],
- null,
- urls[3],
- urls[4],
- urls[5],
- null,
- urls[7]
- };
-
- private static String[] urlsModeReject = new String[] {
- urls[0],
- null,
- urls[2],
- null,
- null,
- null,
- urls[6],
- null
- };
-
- private static String[] urlsModeAcceptIgnoreCase = new String[] {
- null,
- null,
- null,
- null,
- urls[4],
- urls[5],
- null,
- urls[7]
- };
-
- private static String[] urlsModeRejectIgnoreCase = new String[] {
- urls[0],
- urls[1],
- urls[2],
- urls[3],
- null,
- null,
- urls[6],
- null
- };
-
- private static String[] urlsModeAcceptAndPathFilter = new String[] {
- null,
- urls[1],
- null,
- urls[3],
- urls[4],
- urls[5],
- urls[6],
- null
- };
-
- private static String[] urlsModeAcceptAndNonPathFilter = new String[] {
- null,
- urls[1],
- null,
- urls[3],
- urls[4],
- urls[5],
- null,
- urls[7]
- };
-
+ "http://www.example.com/test.gif", "http://www.example.com/TEST.GIF",
+ "http://www.example.com/test.jpg", "http://www.example.com/test.JPG",
+ "http://www.example.com/test.html", "http://www.example.com/test.HTML",
+ "http://www.example.com/test.html?q=abc.js",
+ "http://www.example.com/test.js?foo=bar&baz=bar#12333", };
+
+ private static String[] urlsModeAccept = new String[] { null, urls[1], null,
+ urls[3], urls[4], urls[5], null, urls[7] };
+
+ private static String[] urlsModeReject = new String[] { urls[0], null,
+ urls[2], null, null, null, urls[6], null };
+
+ private static String[] urlsModeAcceptIgnoreCase = new String[] { null, null,
+ null, null, urls[4], urls[5], null, urls[7] };
+
+ private static String[] urlsModeRejectIgnoreCase = new String[] { urls[0],
+ urls[1], urls[2], urls[3], null, null, urls[6], null };
+
+ private static String[] urlsModeAcceptAndPathFilter = new String[] { null,
+ urls[1], null, urls[3], urls[4], urls[5], urls[6], null };
+
+ private static String[] urlsModeAcceptAndNonPathFilter = new String[] { null,
+ urls[1], null, urls[3], urls[4], urls[5], null, urls[7] };
+
private SuffixURLFilter filter = null;
-
+
@Before
public void setUp() throws IOException {
filter = new SuffixURLFilter(new StringReader(suffixes));
}
-
+
@Test
public void testModeAccept() {
filter.setIgnoreCase(false);
@@ -155,22 +99,24 @@ public class TestSuffixURLFilter {
Assert.assertTrue(urlsModeRejectIgnoreCase[i] == filter.filter(urls[i]));
}
}
-
+
@Test
public void testModeAcceptAndNonPathFilter() {
filter.setModeAccept(true);
filter.setFilterFromPath(false);
for (int i = 0; i < urls.length; i++) {
- Assert.assertTrue(urlsModeAcceptAndNonPathFilter[i] == filter.filter(urls[i]));
+ Assert.assertTrue(urlsModeAcceptAndNonPathFilter[i] == filter
+ .filter(urls[i]));
}
}
-
+
@Test
public void testModeAcceptAndPathFilter() {
filter.setModeAccept(true);
filter.setFilterFromPath(true);
for (int i = 0; i < urls.length; i++) {
- Assert.assertTrue(urlsModeAcceptAndPathFilter[i] == filter.filter(urls[i]));
+ Assert.assertTrue(urlsModeAcceptAndPathFilter[i] == filter
+ .filter(urls[i]));
}
}
diff --git a/src/plugin/urlfilter-validator/src/java/org/apache/nutch/urlfilter/validator/UrlValidator.java b/src/plugin/urlfilter-validator/src/java/org/apache/nutch/urlfilter/validator/UrlValidator.java
index e391a2684..03fca9749 100644
--- a/src/plugin/urlfilter-validator/src/java/org/apache/nutch/urlfilter/validator/UrlValidator.java
+++ b/src/plugin/urlfilter-validator/src/java/org/apache/nutch/urlfilter/validator/UrlValidator.java
@@ -23,12 +23,16 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLFilter;
/**
- * <p>Validates URLs.</p>
- *
- * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b,
- * Date: 03/07/02,
- * http://javascript.internet.com. However, this validation now bears little
- * resemblance to the php original.</p>
+ * <p>
+ * Validates URLs.
+ * </p>
+ *
+ * <p>
+ * Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date:
+ * 03/07/02, http://javascript.internet.com. However, this validation now bears
+ * little resemblance to the php original.
+ * </p>
+ *
* <pre>
* Example of usage:
* UrlValidator urlValidator = UrlValidator.get();
@@ -37,17 +41,17 @@ import org.apache.nutch.net.URLFilter;
* } else {
* System.out.println("url is invalid");
* }
- *
+ *
* prints out "url is valid"
- * </pre>
- *
- * <p>Based on UrlValidator code from Apache commons-validator.</p>
- *
- * @see
- * <a href='http://www.ietf.org/rfc/rfc2396.txt' >
- * Uniform Resource Identifiers (URI): Generic Syntax
- * </a>
- *
+ * </pre>
+ *
+ * <p>
+ * Based on UrlValidator code from Apache commons-validator.
+ * </p>
+ *
+ * @see <a href='http://www.ietf.org/rfc/rfc2396.txt' > Uniform Resource
+ * Identifiers (URI): Generic Syntax </a>
+ *
*/
public class UrlValidator implements URLFilter {
@@ -61,7 +65,7 @@ public class UrlValidator implements URLFilter {
private static final String SCHEME_CHARS = ALPHA_CHARS;
- // Drop numeric, and "+-." for now
+ // Drop numeric, and "+-." for now
private static final String AUTHORITY_CHARS = ALPHA_NUMERIC_CHARS + "\\-\\.";
private static final String ATOM = VALID_CHARS + '+';
@@ -69,9 +73,9 @@ public class UrlValidator implements URLFilter {
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
- private static final Pattern URL_PATTERN =
- Pattern.compile("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)" +
- "(\\?([^#]*))?(#(.*))?");
+ private static final Pattern URL_PATTERN = Pattern
+ .compile("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)"
+ + "(\\?([^#]*))?(#(.*))?");
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
@@ -90,11 +94,11 @@ public class UrlValidator implements URLFilter {
/**
* Protocol (ie. http:, ftp:,https:).
*/
- private static final Pattern SCHEME_PATTERN =
- Pattern.compile("^[" + SCHEME_CHARS + "]+");
+ private static final Pattern SCHEME_PATTERN = Pattern.compile("^["
+ + SCHEME_CHARS + "]+");
- private static final Pattern AUTHORITY_PATTERN =
- Pattern.compile("^([" + AUTHORITY_CHARS + "]*)(:\\d*)?(.*)?");
+ private static final Pattern AUTHORITY_PATTERN = Pattern.compile("^(["
+ + AUTHORITY_CHARS + "]*)(:\\d*)?(.*)?");
private static final int PARSE_AUTHORITY_HOST_IP = 1;
@@ -105,28 +109,26 @@ public class UrlValidator implements URLFilter {
*/
private static final int PARSE_AUTHORITY_EXTRA = 3;
- private static final Pattern PATH_PATTERN =
- Pattern.compile("^(/[-\\w:@&?=+,.!/~*'%$_;\\(\\)]*)?$");
+ private static final Pattern PATH_PATTERN = Pattern
+ .compile("^(/[-\\w:@&?=+,.!/~*'%$_;\\(\\)]*)?$");
private static final Pattern QUERY_PATTERN = Pattern.compile("^(.*)$");
- private static final Pattern LEGAL_ASCII_PATTERN =
- Pattern.compile("^[\\x21-\\x7E]+$");
+ private static final Pattern LEGAL_ASCII_PATTERN = Pattern
+ .compile("^[\\x21-\\x7E]+$");
- private static final Pattern IP_V4_DOMAIN_PATTERN =
- Pattern.compile("^(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})$");
+ private static final Pattern IP_V4_DOMAIN_PATTERN = Pattern
+ .compile("^(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})$");
- private static final Pattern DOMAIN_PATTERN =
- Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*$");
+ private static final Pattern DOMAIN_PATTERN = Pattern.compile("^" + ATOM
+ + "(\\." + ATOM + ")*$");
- private static final Pattern PORT_PATTERN =
- Pattern.compile("^:(\\d{1,5})$");
+ private static final Pattern PORT_PATTERN = Pattern.compile("^:(\\d{1,5})$");
- private static final Pattern ATOM_PATTERN =
- Pattern.compile("(" + ATOM + ")");
+ private static final Pattern ATOM_PATTERN = Pattern.compile("(" + ATOM + ")");
- private static final Pattern ALPHA_PATTERN =
- Pattern.compile("^[" + ALPHA_CHARS + "]");
+ private static final Pattern ALPHA_PATTERN = Pattern.compile("^["
+ + ALPHA_CHARS + "]");
private Configuration conf;
@@ -143,10 +145,13 @@ public class UrlValidator implements URLFilter {
}
/**
- * <p>Checks if a field has a valid url address.</p>
- *
- * @param value The value validation is being performed on.
- * A <code>null</code> value is considered invalid.
+ * <p>
+ * Checks if a field has a valid url address.
+ * </p>
+ *
+ * @param value
+ * The value validation is being performed on. A <code>null</code>
+ * value is considered invalid.
* @return true if the url is valid.
*/
private boolean isValid(String value) {
@@ -184,11 +189,13 @@ public class UrlValidator implements URLFilter {
}
/**
- * Validate scheme. If schemes[] was initialized to a non null,
- * then only those scheme's are allowed. Note this is slightly different
- * than for the constructor.
- * @param scheme The scheme to validate. A <code>null</code> value is
- * considered invalid.
+ * Validate scheme. If schemes[] was initialized to a non null, then only
+ * those scheme's are allowed. Note this is slightly different than for the
+ * constructor.
+ *
+ * @param scheme
+ * The scheme to validate. A <code>null</code> value is considered
+ * invalid.
* @return true if valid.
*/
private boolean isValidScheme(String scheme) {
@@ -200,10 +207,12 @@ public class UrlValidator implements URLFilter {
}
/**
- * Returns true if the authority is properly formatted. An authority is
- * the combination of hostname and port. A <code>null</code> authority
- * value is considered invalid.
- * @param authority Authority value to validate.
+ * Returns true if the authority is properly formatted. An authority is the
+ * combination of hostname and port. A <code>null</code> authority value is
+ * considered invalid.
+ *
+ * @param authority
+ * Authority value to validate.
* @return true if authority (hostname and port) is valid.
*/
private boolean isValidAuthority(String authority) {
@@ -235,7 +244,7 @@ public class UrlValidator implements URLFilter {
if (Integer.parseInt(ipSegment) > 255) {
return false;
}
- } catch(NumberFormatException e) {
+ } catch (NumberFormatException e) {
return false;
}
@@ -251,8 +260,8 @@ public class UrlValidator implements URLFilter {
// TODO: Rewrite to use ArrayList and .add semantics: see VALIDATOR-203
char[] chars = hostIP.toCharArray();
int size = 1;
- for(int i=0; i<chars.length; i++) {
- if(chars[i] == '.') {
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] == '.') {
size++;
}
}
@@ -264,8 +273,7 @@ public class UrlValidator implements URLFilter {
while (atomMatcher.find()) {
domainSegment[segCount] = atomMatcher.group();
segLen = domainSegment[segCount].length() + 1;
- hostIP = (segLen >= hostIP.length()) ? ""
- : hostIP.substring(segLen);
+ hostIP = (segLen >= hostIP.length()) ? "" : hostIP.substring(segLen);
segCount++;
}
String topLevel = domainSegment[segCount - 1];
@@ -300,10 +308,13 @@ public class UrlValidator implements URLFilter {
}
/**
- * <p>Checks if the field isn't null and length of the field is greater
- * than zero not including whitespace.</p>
- *
- * @param value The value validation is being performed on.
+ * <p>
+ * Checks if the field isn't null and length of the field is greater than zero
+ * not including whitespace.
+ * </p>
+ *
+ * @param value
+ * The value validation is being performed on.
* @return true if blank or null.
*/
private boolean isBlankOrNull(String value) {
@@ -311,9 +322,11 @@ public class UrlValidator implements URLFilter {
}
/**
- * Returns true if the path is valid. A <code>null</code> value is
- * considered invalid.
- * @param path Path value to validate.
+ * Returns true if the path is valid. A <code>null</code> value is considered
+ * invalid.
+ *
+ * @param path
+ * Path value to validate.
* @return true if path is valid.
*/
private boolean isValidPath(String path) {
@@ -335,7 +348,9 @@ public class UrlValidator implements URLFilter {
/**
* Returns true if the query is null or it's a properly formatted query
* string.
- * @param query Query value to validate.
+ *
+ * @param query
+ * Query value to validate.
* @return true if query is valid.
*/
private boolean isValidQuery(String query) {
@@ -348,8 +363,11 @@ public class UrlValidator implements URLFilter {
/**
* Returns the number of times the token appears in the target.
- * @param token Token value to be counted.
- * @param target Target value to count tokens in.
+ *
+ * @param token
+ * Token value to be counted.
+ * @param target
+ * Target value to count tokens in.
* @return the number of tokens.
*/
private int countToken(String token, String target) {
diff --git a/src/plugin/urlfilter-validator/src/test/org/apache/nutch/urlfilter/validator/TestUrlValidator.java b/src/plugin/urlfilter-validator/src/test/org/apache/nutch/urlfilter/validator/TestUrlValidator.java
index 852d23545..2e6d695b5 100644
--- a/src/plugin/urlfilter-validator/src/test/org/apache/nutch/urlfilter/validator/TestUrlValidator.java
+++ b/src/plugin/urlfilter-validator/src/test/org/apache/nutch/urlfilter/validator/TestUrlValidator.java
@@ -21,40 +21,59 @@ import org.junit.Assert;
import org.junit.Test;
/**
- * JUnit test case which tests
- * 1. that valid urls are not filtered while invalid ones are filtered.
- * 2. that Urls' scheme, authority, path and query are validated.
+ * JUnit test case which tests 1. that valid urls are not filtered while invalid
+ * ones are filtered. 2. that Urls' scheme, authority, path and query are
+ * validated.
*
* @author tejasp
- *
+ *
*/
public class TestUrlValidator {
/**
- * Test method for {@link org.apache.nutch.urlfilter.validator.UrlValidator#filter(java.lang.String)}.
+ * Test method for
+ * {@link org.apache.nutch.urlfilter.validator.UrlValidator#filter(java.lang.String)}
+ * .
*/
@Test
public void testFilter() {
UrlValidator url_validator = new UrlValidator();
Assert.assertNotNull(url_validator);
- Assert.assertNull("Filtering on a null object should return null", url_validator.filter(null));
- Assert.assertNull("Invalid url: example.com/file[/].html", url_validator.filter("example.com/file[/].html"));
- Assert.assertNull("Invalid url: http://www.example.com/space here.html", url_validator.filter("http://www.example.com/space here.html"));
- Assert.assertNull("Invalid url: /main.html", url_validator.filter("/main.html"));
- Assert.assertNull("Invalid url: www.example.com/main.html", url_validator.filter("www.example.com/main.html"));
- Assert.assertNull("Invalid url: ftp:www.example.com/main.html", url_validator.filter("ftp:www.example.com/main.html"));
- Assert.assertNull("Inalid url: http://999.000.456.32/nutch/trunk/README.txt",
+ Assert.assertNull("Filtering on a null object should return null",
+ url_validator.filter(null));
+ Assert.assertNull("Invalid url: example.com/file[/].html",
+ url_validator.filter("example.com/file[/].html"));
+ Assert.assertNull("Invalid url: http://www.example.com/space here.html",
+ url_validator.filter("http://www.example.com/space here.html"));
+ Assert.assertNull("Invalid url: /main.html",
+ url_validator.filter("/main.html"));
+ Assert.assertNull("Invalid url: www.example.com/main.html",
+ url_validator.filter("www.example.com/main.html"));
+ Assert.assertNull("Invalid url: ftp:www.example.com/main.html",
+ url_validator.filter("ftp:www.example.com/main.html"));
+ Assert.assertNull(
+ "Inalid url: http://999.000.456.32/nutch/trunk/README.txt",
url_validator.filter("http://999.000.456.32/nutch/trunk/README.txt"));
- Assert.assertNull("Invalid url: http://www.example.com/ma|in\\toc.html", url_validator.filter(" http://www.example.com/ma|in\\toc.html"));
+ Assert.assertNull("Invalid url: http://www.example.com/ma|in\\toc.html",
+ url_validator.filter(" http://www.example.com/ma|in\\toc.html"));
- Assert.assertNotNull("Valid url: https://issues.apache.org/jira/NUTCH-1127", url_validator.filter("https://issues.apache.org/jira/NUTCH-1127"));
- Assert.assertNotNull("Valid url: http://domain.tld/function.cgi?url=http://fonzi.com/&amp;name=Fonzi&amp;mood=happy&amp;coat=leather",
- url_validator.filter("http://domain.tld/function.cgi?url=http://fonzi.com/&amp;name=Fonzi&amp;mood=happy&amp;coat=leather"));
- Assert.assertNotNull("Valid url: http://validator.w3.org/feed/check.cgi?url=http%3A%2F%2Ffeeds.feedburner.com%2Fperishablepress",
- url_validator.filter("http://validator.w3.org/feed/check.cgi?url=http%3A%2F%2Ffeeds.feedburner.com%2Fperishablepress"));
- Assert.assertNotNull("Valid url: ftp://alfa.bravo.pi/foo/bar/plan.pdf", url_validator.filter("ftp://alfa.bravo.pi/mike/check/plan.pdf"));
+ Assert.assertNotNull(
+ "Valid url: https://issues.apache.org/jira/NUTCH-1127",
+ url_validator.filter("https://issues.apache.org/jira/NUTCH-1127"));
+ Assert
+ .assertNotNull(
+ "Valid url: http://domain.tld/function.cgi?url=http://fonzi.com/&amp;name=Fonzi&amp;mood=happy&amp;coat=leather",
+ url_validator
+ .filter("http://domain.tld/function.cgi?url=http://fonzi.com/&amp;name=Fonzi&amp;mood=happy&amp;coat=leather"));
+ Assert
+ .assertNotNull(
+ "Valid url: http://validator.w3.org/feed/check.cgi?url=http%3A%2F%2Ffeeds.feedburner.com%2Fperishablepress",
+ url_validator
+ .filter("http://validator.w3.org/feed/check.cgi?url=http%3A%2F%2Ffeeds.feedburner.com%2Fperishablepress"));
+ Assert.assertNotNull("Valid url: ftp://alfa.bravo.pi/foo/bar/plan.pdf",
+ url_validator.filter("ftp://alfa.bravo.pi/mike/check/plan.pdf"));
}
}
diff --git a/src/plugin/urlmeta/src/java/org/apache/nutch/indexer/urlmeta/URLMetaIndexingFilter.java b/src/plugin/urlmeta/src/java/org/apache/nutch/indexer/urlmeta/URLMetaIndexingFilter.java
index b59e47c84..dc673a251 100644
--- a/src/plugin/urlmeta/src/java/org/apache/nutch/indexer/urlmeta/URLMetaIndexingFilter.java
+++ b/src/plugin/urlmeta/src/java/org/apache/nutch/indexer/urlmeta/URLMetaIndexingFilter.java
@@ -67,52 +67,52 @@ import org.apache.nutch.parse.Parse;
*/
public class URLMetaIndexingFilter implements IndexingFilter {
- private static final Logger LOG = LoggerFactory
- .getLogger(URLMetaIndexingFilter.class);
- private static final String CONF_PROPERTY = "urlmeta.tags";
- private static String[] urlMetaTags;
- private Configuration conf;
+ private static final Logger LOG = LoggerFactory
+ .getLogger(URLMetaIndexingFilter.class);
+ private static final String CONF_PROPERTY = "urlmeta.tags";
+ private static String[] urlMetaTags;
+ private Configuration conf;
- /**
- * This will take the metatags that you have listed in your "urlmeta.tags"
- * property, and looks for them inside the CrawlDatum object. If they exist,
- * this will add it as an attribute inside the NutchDocument.
- *
- * @see IndexingFilter#filter
- */
- public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
- CrawlDatum datum, Inlinks inlinks) throws IndexingException {
- if (conf != null)
- this.setConf(conf);
+ /**
+ * This will take the metatags that you have listed in your "urlmeta.tags"
+ * property, and looks for them inside the CrawlDatum object. If they exist,
+ * this will add it as an attribute inside the NutchDocument.
+ *
+ * @see IndexingFilter#filter
+ */
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
+ if (conf != null)
+ this.setConf(conf);
- if (urlMetaTags == null || doc == null)
- return doc;
+ if (urlMetaTags == null || doc == null)
+ return doc;
- for (String metatag : urlMetaTags) {
- Text metadata = (Text) datum.getMetaData().get(new Text(metatag));
+ for (String metatag : urlMetaTags) {
+ Text metadata = (Text) datum.getMetaData().get(new Text(metatag));
- if (metadata != null)
- doc.add(metatag, metadata.toString());
- }
+ if (metadata != null)
+ doc.add(metatag, metadata.toString());
+ }
- return doc;
- }
+ return doc;
+ }
- /** Boilerplate */
- public Configuration getConf() {
- return conf;
- }
+ /** Boilerplate */
+ public Configuration getConf() {
+ return conf;
+ }
- /**
- * handles conf assignment and pulls the value assignment from the
- * "urlmeta.tags" property
- */
- public void setConf(Configuration conf) {
- this.conf = conf;
+ /**
+ * handles conf assignment and pulls the value assignment from the
+ * "urlmeta.tags" property
+ */
+ public void setConf(Configuration conf) {
+ this.conf = conf;
- if (conf == null)
- return;
+ if (conf == null)
+ return;
- urlMetaTags = conf.getStrings(CONF_PROPERTY);
- }
+ urlMetaTags = conf.getStrings(CONF_PROPERTY);
+ }
}
diff --git a/src/plugin/urlmeta/src/java/org/apache/nutch/scoring/urlmeta/URLMetaScoringFilter.java b/src/plugin/urlmeta/src/java/org/apache/nutch/scoring/urlmeta/URLMetaScoringFilter.java
index d455111e4..3965e42c2 100644
--- a/src/plugin/urlmeta/src/java/org/apache/nutch/scoring/urlmeta/URLMetaScoringFilter.java
+++ b/src/plugin/urlmeta/src/java/org/apache/nutch/scoring/urlmeta/URLMetaScoringFilter.java
@@ -43,7 +43,8 @@ import org.apache.nutch.scoring.ScoringFilterException;
*/
public class URLMetaScoringFilter extends Configured implements ScoringFilter {
- private static final Logger LOG = LoggerFactory.getLogger(URLMetaScoringFilter.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(URLMetaScoringFilter.class);
private static final String CONF_PROPERTY = "urlmeta.tags";
private static String[] urlMetaTags;
private Configuration conf;
@@ -73,8 +74,8 @@ public class URLMetaScoringFilter extends Configured implements ScoringFilter {
if (metaFromParse == null)
continue;
- nextTarget.getValue().getMetaData().put(new Text(metatag),
- new Text(metaFromParse));
+ nextTarget.getValue().getMetaData()
+ .put(new Text(metatag), new Text(metaFromParse));
}
}
return adjust;
diff --git a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
index 09f1ebe25..63c4cad41 100644
--- a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
+++ b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
@@ -39,185 +39,180 @@ import org.apache.oro.text.regex.*;
* </ul>
*/
public class BasicURLNormalizer extends Configured implements URLNormalizer {
- public static final Logger LOG = LoggerFactory.getLogger(BasicURLNormalizer.class);
+ public static final Logger LOG = LoggerFactory
+ .getLogger(BasicURLNormalizer.class);
- private Perl5Compiler compiler = new Perl5Compiler();
- private ThreadLocal<Perl5Matcher> matchers = new ThreadLocal<Perl5Matcher>() {
- protected Perl5Matcher initialValue() {
- return new Perl5Matcher();
- }
- };
- private final Rule relativePathRule;
- private final Rule leadingRelativePathRule;
- private final Rule currentPathRule;
- private final Rule adjacentSlashRule;
-
- private final static java.util.regex.Pattern hasNormalizablePattern = java.util.regex.Pattern.compile("/\\.?\\.?/");
-
- private Configuration conf;
-
- 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 "/"
- // (slash) and needs to have at least one char different from "."
- relativePathRule = new Rule();
- relativePathRule.pattern = (Perl5Pattern)
- compiler.compile("(/[^/]*[^/.]{1}[^/]*/\\.\\./)",
- Perl5Compiler.READ_ONLY_MASK);
- relativePathRule.substitution = new Perl5Substitution("/");
-
- // this pattern tries to find spots like leading "/../" in the url,
- // which could be replaced by "/"
- leadingRelativePathRule = new Rule();
- leadingRelativePathRule.pattern = (Perl5Pattern)
- compiler.compile("^(/\\.\\./)+", Perl5Compiler.READ_ONLY_MASK);
- leadingRelativePathRule.substitution = new Perl5Substitution("/");
-
- // this pattern tries to find spots like "/./" in the url,
- // which could be replaced by "/"
- currentPathRule = new Rule();
- currentPathRule.pattern = (Perl5Pattern)
- compiler.compile("(/\\./)", Perl5Compiler.READ_ONLY_MASK);
- currentPathRule.substitution = new Perl5Substitution("/");
-
- // this pattern tries to find spots like "xx//yy" in the url,
- // which could be replaced by a "/"
- adjacentSlashRule = new Rule();
- adjacentSlashRule.pattern = (Perl5Pattern)
- compiler.compile("/{2,}", Perl5Compiler.READ_ONLY_MASK);
- adjacentSlashRule.substitution = new Perl5Substitution("/");
-
- } catch (MalformedPatternException e) {
- throw new RuntimeException(e);
- }
+ private Perl5Compiler compiler = new Perl5Compiler();
+ private ThreadLocal<Perl5Matcher> matchers = new ThreadLocal<Perl5Matcher>() {
+ protected Perl5Matcher initialValue() {
+ return new Perl5Matcher();
}
+ };
+ private final Rule relativePathRule;
+ private final Rule leadingRelativePathRule;
+ private final Rule currentPathRule;
+ private final Rule adjacentSlashRule;
+
+ private final static java.util.regex.Pattern hasNormalizablePattern = java.util.regex.Pattern
+ .compile("/\\.?\\.?/");
+
+ private Configuration conf;
+
+ 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 "/"
+ // (slash) and needs to have at least one char different from "."
+ relativePathRule = new Rule();
+ relativePathRule.pattern = (Perl5Pattern) compiler.compile(
+ "(/[^/]*[^/.]{1}[^/]*/\\.\\./)", Perl5Compiler.READ_ONLY_MASK);
+ relativePathRule.substitution = new Perl5Substitution("/");
+
+ // this pattern tries to find spots like leading "/../" in the url,
+ // which could be replaced by "/"
+ leadingRelativePathRule = new Rule();
+ leadingRelativePathRule.pattern = (Perl5Pattern) compiler.compile(
+ "^(/\\.\\./)+", Perl5Compiler.READ_ONLY_MASK);
+ leadingRelativePathRule.substitution = new Perl5Substitution("/");
+
+ // this pattern tries to find spots like "/./" in the url,
+ // which could be replaced by "/"
+ currentPathRule = new Rule();
+ currentPathRule.pattern = (Perl5Pattern) compiler.compile("(/\\./)",
+ Perl5Compiler.READ_ONLY_MASK);
+ currentPathRule.substitution = new Perl5Substitution("/");
+
+ // this pattern tries to find spots like "xx//yy" in the url,
+ // which could be replaced by a "/"
+ adjacentSlashRule = new Rule();
+ adjacentSlashRule.pattern = (Perl5Pattern) compiler.compile("/{2,}",
+ Perl5Compiler.READ_ONLY_MASK);
+ adjacentSlashRule.substitution = new Perl5Substitution("/");
+
+ } catch (MalformedPatternException e) {
+ throw new RuntimeException(e);
+ }
+ }
- public String normalize(String urlString, String scope)
- throws MalformedURLException {
- if ("".equals(urlString)) // permit empty
- return urlString;
-
- urlString = urlString.trim(); // remove extra spaces
+ public String normalize(String urlString, String scope)
+ throws MalformedURLException {
+ if ("".equals(urlString)) // permit empty
+ return urlString;
- URL url = new URL(urlString);
+ urlString = urlString.trim(); // remove extra spaces
- String protocol = url.getProtocol();
- String host = url.getHost();
- int port = url.getPort();
- String file = url.getFile();
+ URL url = new URL(urlString);
- boolean changed = false;
+ String protocol = url.getProtocol();
+ String host = url.getHost();
+ int port = url.getPort();
+ String file = url.getFile();
- if (!urlString.startsWith(protocol)) // protocol was lowercased
- changed = true;
+ boolean changed = false;
- if ("http".equals(protocol) || "https".equals(protocol) || "ftp".equals(protocol)) {
+ if (!urlString.startsWith(protocol)) // protocol was lowercased
+ changed = true;
- if (host != null) {
- String newHost = host.toLowerCase(); // lowercase host
- if (!host.equals(newHost)) {
- host = newHost;
- changed = true;
- }
- }
+ if ("http".equals(protocol) || "https".equals(protocol)
+ || "ftp".equals(protocol)) {
- if (port == url.getDefaultPort()) { // uses default port
- port = -1; // so don't specify it
- changed = true;
- }
+ if (host != null) {
+ String newHost = host.toLowerCase(); // lowercase host
+ if (!host.equals(newHost)) {
+ host = newHost;
+ changed = true;
+ }
+ }
- if (file == null || "".equals(file)) { // add a slash
- file = "/";
- changed = true;
- }
+ if (port == url.getDefaultPort()) { // uses default port
+ port = -1; // so don't specify it
+ changed = true;
+ }
- if (url.getRef() != null) { // remove the ref
- changed = true;
- }
+ if (file == null || "".equals(file)) { // add a slash
+ file = "/";
+ changed = true;
+ }
- // check for unnecessary use of "/../"
- String file2 = substituteUnnecessaryRelativePaths(file);
+ if (url.getRef() != null) { // remove the ref
+ changed = true;
+ }
- if (!file.equals(file2)) {
- changed = true;
- file = file2;
- }
+ // check for unnecessary use of "/../"
+ String file2 = substituteUnnecessaryRelativePaths(file);
- }
-
- if (changed)
- urlString = new URL(protocol, host, port, file).toString();
+ if (!file.equals(file2)) {
+ changed = true;
+ file = file2;
+ }
- return urlString;
}
- private String substituteUnnecessaryRelativePaths(String file) {
-
- if (!hasNormalizablePattern.matcher(file).find())
- return file;
-
- String fileWorkCopy = file;
- int oldLen = file.length();
- int newLen = oldLen - 1;
-
- // All substitutions will be done step by step, to ensure that certain
- // constellations will be normalized, too
- //
- // For example: "/aa/bb/../../cc/../foo.html will be normalized in the
- // following manner:
- // "/aa/bb/../../cc/../foo.html"
- // "/aa/../cc/../foo.html"
- // "/cc/../foo.html"
- // "/foo.html"
- //
- // The normalization also takes care of leading "/../", which will be
- // replaced by "/", because this is a rather a sign of bad webserver
- // configuration than of a wanted link. For example, urls like
- // "http://www.foo.com/../" should return a http 404 error instead of
- // redirecting to "http://www.foo.com".
- //
- Perl5Matcher matcher = (Perl5Matcher)matchers.get();
-
- while (oldLen != newLen) {
- // substitue first occurence of "/xx/../" by "/"
- oldLen = fileWorkCopy.length();
- fileWorkCopy = Util.substitute
- (matcher, relativePathRule.pattern,
- relativePathRule.substitution, fileWorkCopy, 1);
-
- // remove leading "/../"
- fileWorkCopy = Util.substitute
- (matcher, leadingRelativePathRule.pattern,
- leadingRelativePathRule.substitution, fileWorkCopy, 1);
-
- // remove unnecessary "/./"
- fileWorkCopy = Util.substitute
- (matcher, currentPathRule.pattern,
- currentPathRule.substitution, fileWorkCopy, 1);
-
-
- // collapse adjacent slashes with "/"
- fileWorkCopy = Util.substitute
- (matcher, adjacentSlashRule.pattern,
- adjacentSlashRule.substitution, fileWorkCopy, 1);
-
- newLen = fileWorkCopy.length();
- }
-
- return fileWorkCopy;
- }
+ if (changed)
+ urlString = new URL(protocol, host, port, file).toString();
+ return urlString;
+ }
- /**
- * Class which holds a compiled pattern and its corresponding substition
- * string.
- */
- private static class Rule {
- public Perl5Pattern pattern;
- public Perl5Substitution substitution;
+ private String substituteUnnecessaryRelativePaths(String file) {
+
+ if (!hasNormalizablePattern.matcher(file).find())
+ return file;
+
+ String fileWorkCopy = file;
+ int oldLen = file.length();
+ int newLen = oldLen - 1;
+
+ // All substitutions will be done step by step, to ensure that certain
+ // constellations will be normalized, too
+ //
+ // For example: "/aa/bb/../../cc/../foo.html will be normalized in the
+ // following manner:
+ // "/aa/bb/../../cc/../foo.html"
+ // "/aa/../cc/../foo.html"
+ // "/cc/../foo.html"
+ // "/foo.html"
+ //
+ // The normalization also takes care of leading "/../", which will be
+ // replaced by "/", because this is a rather a sign of bad webserver
+ // configuration than of a wanted link. For example, urls like
+ // "http://www.foo.com/../" should return a http 404 error instead of
+ // redirecting to "http://www.foo.com".
+ //
+ Perl5Matcher matcher = (Perl5Matcher) matchers.get();
+
+ while (oldLen != newLen) {
+ // substitue first occurence of "/xx/../" by "/"
+ oldLen = fileWorkCopy.length();
+ fileWorkCopy = Util.substitute(matcher, relativePathRule.pattern,
+ relativePathRule.substitution, fileWorkCopy, 1);
+
+ // remove leading "/../"
+ fileWorkCopy = Util.substitute(matcher, leadingRelativePathRule.pattern,
+ leadingRelativePathRule.substitution, fileWorkCopy, 1);
+
+ // remove unnecessary "/./"
+ fileWorkCopy = Util.substitute(matcher, currentPathRule.pattern,
+ currentPathRule.substitution, fileWorkCopy, 1);
+
+ // collapse adjacent slashes with "/"
+ fileWorkCopy = Util.substitute(matcher, adjacentSlashRule.pattern,
+ adjacentSlashRule.substitution, fileWorkCopy, 1);
+
+ newLen = fileWorkCopy.length();
}
+ return fileWorkCopy;
+ }
+
+ /**
+ * Class which holds a compiled pattern and its corresponding substition
+ * string.
+ */
+ private static class Rule {
+ public Perl5Pattern pattern;
+ public Perl5Substitution substitution;
+ }
public void setConf(Configuration conf) {
this.conf = conf;
@@ -228,4 +223,3 @@ public class BasicURLNormalizer extends Configured implements URLNormalizer {
}
}
-
diff --git a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/package-info.java b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/package-info.java
index 0a26b5fd9..ae59a843a 100644
--- a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/package-info.java
+++ b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/package-info.java
@@ -20,3 +20,4 @@
* and dot segments in path.
*/
package org.apache.nutch.net.urlnormalizer.basic;
+
diff --git a/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java
index 9119e470c..3231fec87 100644
--- a/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java
+++ b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java
@@ -26,16 +26,15 @@ import org.junit.Test;
/** Unit tests for BasicURLNormalizer. */
public class TestBasicURLNormalizer {
private BasicURLNormalizer normalizer;
-
+
private Configuration conf;
-
+
public TestBasicURLNormalizer() {
normalizer = new BasicURLNormalizer();
conf = NutchConfiguration.create();
normalizer.setConf(conf);
}
-
@Test
public void testNormalizer() throws Exception {
// check that leading and trailing spaces are removed
@@ -58,59 +57,49 @@ public class TestBasicURLNormalizer {
// check that references are removed
normalizeTest("http://foo.com/foo.html#ref", "http://foo.com/foo.html");
- // // check that encoding is normalized
- // normalizeTest("http://foo.com/%66oo.html", "http://foo.com/foo.html");
+ // // check that encoding is normalized
+ // normalizeTest("http://foo.com/%66oo.html", "http://foo.com/foo.html");
// check that unnecessary "../" are removed
- normalizeTest("http://foo.com/aa/./foo.html",
- "http://foo.com/aa/foo.html" );
- normalizeTest("http://foo.com/aa/../",
- "http://foo.com/" );
- normalizeTest("http://foo.com/aa/bb/../",
- "http://foo.com/aa/");
- normalizeTest("http://foo.com/aa/..",
- "http://foo.com/aa/..");
+ normalizeTest("http://foo.com/aa/./foo.html", "http://foo.com/aa/foo.html");
+ normalizeTest("http://foo.com/aa/../", "http://foo.com/");
+ normalizeTest("http://foo.com/aa/bb/../", "http://foo.com/aa/");
+ normalizeTest("http://foo.com/aa/..", "http://foo.com/aa/..");
normalizeTest("http://foo.com/aa/bb/cc/../../foo.html",
- "http://foo.com/aa/foo.html");
+ "http://foo.com/aa/foo.html");
normalizeTest("http://foo.com/aa/bb/../cc/dd/../ee/foo.html",
- "http://foo.com/aa/cc/ee/foo.html");
- normalizeTest("http://foo.com/../foo.html",
- "http://foo.com/foo.html" );
- normalizeTest("http://foo.com/../../foo.html",
- "http://foo.com/foo.html" );
- normalizeTest("http://foo.com/../aa/../foo.html",
- "http://foo.com/foo.html" );
- normalizeTest("http://foo.com/aa/../../foo.html",
- "http://foo.com/foo.html" );
+ "http://foo.com/aa/cc/ee/foo.html");
+ normalizeTest("http://foo.com/../foo.html", "http://foo.com/foo.html");
+ normalizeTest("http://foo.com/../../foo.html", "http://foo.com/foo.html");
+ normalizeTest("http://foo.com/../aa/../foo.html", "http://foo.com/foo.html");
+ normalizeTest("http://foo.com/aa/../../foo.html", "http://foo.com/foo.html");
normalizeTest("http://foo.com/aa/../bb/../foo.html/../../",
- "http://foo.com/" );
- normalizeTest("http://foo.com/../aa/foo.html",
- "http://foo.com/aa/foo.html" );
- normalizeTest("http://foo.com/../aa/../foo.html",
- "http://foo.com/foo.html" );
+ "http://foo.com/");
+ normalizeTest("http://foo.com/../aa/foo.html", "http://foo.com/aa/foo.html");
+ normalizeTest("http://foo.com/../aa/../foo.html", "http://foo.com/foo.html");
normalizeTest("http://foo.com/a..a/foo.html",
- "http://foo.com/a..a/foo.html" );
- normalizeTest("http://foo.com/a..a/../foo.html",
- "http://foo.com/foo.html" );
+ "http://foo.com/a..a/foo.html");
+ normalizeTest("http://foo.com/a..a/../foo.html", "http://foo.com/foo.html");
normalizeTest("http://foo.com/foo.foo/../foo.html",
- "http://foo.com/foo.html" );
+ "http://foo.com/foo.html");
normalizeTest("http://foo.com//aa/bb/foo.html",
- "http://foo.com/aa/bb/foo.html" );
+ "http://foo.com/aa/bb/foo.html");
normalizeTest("http://foo.com/aa//bb/foo.html",
- "http://foo.com/aa/bb/foo.html" );
+ "http://foo.com/aa/bb/foo.html");
normalizeTest("http://foo.com/aa/bb//foo.html",
- "http://foo.com/aa/bb/foo.html" );
+ "http://foo.com/aa/bb/foo.html");
normalizeTest("http://foo.com//aa//bb//foo.html",
- "http://foo.com/aa/bb/foo.html" );
+ "http://foo.com/aa/bb/foo.html");
normalizeTest("http://foo.com////aa////bb////foo.html",
- "http://foo.com/aa/bb/foo.html" );
+ "http://foo.com/aa/bb/foo.html");
}
private void normalizeTest(String weird, String normal) throws Exception {
- Assert.assertEquals(normal, normalizer.normalize(weird, URLNormalizers.SCOPE_DEFAULT));
+ Assert.assertEquals(normal,
+ normalizer.normalize(weird, URLNormalizers.SCOPE_DEFAULT));
}
-
+
public static void main(String[] args) throws Exception {
new TestBasicURLNormalizer().testNormalizer();
}
diff --git a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
index fcb52fbaa..8d5c1104f 100644
--- a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
+++ b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
@@ -35,34 +35,36 @@ import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.URLUtil;
/**
- * URL normalizer for mapping hosts to their desired form. It takes
- * a simple text file as source in the format:
- *
+ * URL normalizer for mapping hosts to their desired form. It takes a simple
+ * text file as source in the format:
+ *
* example.org www.example.org
- *
- * mapping all URL's of example.org the the www sub-domain. It also
- * allows for wildcards to be used to map all sub-domains to another
- * host:
- *
+ *
+ * mapping all URL's of example.org the the www sub-domain. It also allows for
+ * wildcards to be used to map all sub-domains to another host:
+ *
* *.example.org www.example.org
*/
public class HostURLNormalizer implements URLNormalizer {
private Configuration conf;
- private static final Logger LOG = LoggerFactory.getLogger(HostURLNormalizer.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(HostURLNormalizer.class);
private static String attributeFile = null;
private String hostsFile = null;
- private static final HashMap<String,String> hostsMap = new HashMap<String,String>();
+ private static final HashMap<String, String> hostsMap = new HashMap<String, String>();
- public HostURLNormalizer() {}
+ public HostURLNormalizer() {
+ }
public HostURLNormalizer(String hostsFile) {
this.hostsFile = hostsFile;
}
- private synchronized void readConfiguration(Reader configReader) throws IOException {
+ private synchronized void readConfiguration(Reader configReader)
+ throws IOException {
if (hostsMap.size() > 0) {
return;
}
@@ -92,8 +94,8 @@ public class HostURLNormalizer implements URLNormalizer {
// get the extensions for domain urlfilter
String pluginName = "urlnormalizer-host";
- Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(
- URLNormalizer.class.getName()).getExtensions();
+ Extension[] extensions = PluginRepository.get(conf)
+ .getExtensionPoint(URLNormalizer.class.getName()).getExtensions();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
if (extension.getDescriptor().getPluginId().equals(pluginName)) {
@@ -110,13 +112,12 @@ public class HostURLNormalizer implements URLNormalizer {
if (attributeFile != null) {
if (LOG.isInfoEnabled()) {
LOG.info("Attribute \"file\" is defined for plugin " + pluginName
- + " as " + attributeFile);
+ + " as " + attributeFile);
}
- }
- else {
+ } else {
if (LOG.isWarnEnabled()) {
LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin "
- + pluginName);
+ + pluginName);
}
}
@@ -125,8 +126,7 @@ public class HostURLNormalizer implements URLNormalizer {
String stringRules = conf.get("urlnormalizer.hosts.rules");
if (hostsFile != null) {
file = hostsFile;
- }
- else if (attributeFile != null) {
+ } else if (attributeFile != null) {
file = attributeFile;
}
Reader reader = null;
@@ -140,13 +140,13 @@ public class HostURLNormalizer implements URLNormalizer {
reader = new FileReader(file);
}
readConfiguration(reader);
- }
- catch (IOException e) {
+ } catch (IOException e) {
LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e));
}
}
- public String normalize(String urlString, String scope) throws MalformedURLException {
+ public String normalize(String urlString, String scope)
+ throws MalformedURLException {
String host = new URL(urlString).getHost();
// Test static hosts
@@ -164,7 +164,7 @@ public class HostURLNormalizer implements URLNormalizer {
String wildCardHost = new String();
// Add the tld to the buffer
- hostBuffer.append(hostParts[hostParts.length -1]);
+ hostBuffer.append(hostParts[hostParts.length - 1]);
for (int i = hostParts.length - 2; i > 0; i--) {
// Prepend another sub domain
diff --git a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/package-info.java b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/package-info.java
index 43cb8e399..62c97d7dd 100644
--- a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/package-info.java
+++ b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/package-info.java
@@ -20,3 +20,4 @@
* configuration file.
*/
package org.apache.nutch.net.urlnormalizer.host;
+
diff --git a/src/plugin/urlnormalizer-host/src/test/org/apache/nutch/net/urlnormalizer/host/TestHostURLNormalizer.java b/src/plugin/urlnormalizer-host/src/test/org/apache/nutch/net/urlnormalizer/host/TestHostURLNormalizer.java
index 8e0bd602e..c9e1a2ce5 100644
--- a/src/plugin/urlnormalizer-host/src/test/org/apache/nutch/net/urlnormalizer/host/TestHostURLNormalizer.java
+++ b/src/plugin/urlnormalizer-host/src/test/org/apache/nutch/net/urlnormalizer/host/TestHostURLNormalizer.java
@@ -36,14 +36,22 @@ public class TestHostURLNormalizer {
normalizer.setConf(conf);
// Force www. sub domain when hitting link without sub domain
- Assert.assertEquals("http://www.example.org/page.html", normalizer.normalize("http://example.org/page.html", URLNormalizers.SCOPE_DEFAULT));
+ Assert.assertEquals("http://www.example.org/page.html",
+ normalizer.normalize("http://example.org/page.html",
+ URLNormalizers.SCOPE_DEFAULT));
// Force no sub domain to www. URL's
- Assert.assertEquals("http://example.net/path/to/something.html", normalizer.normalize("http://www.example.net/path/to/something.html", URLNormalizers.SCOPE_DEFAULT));
+ Assert.assertEquals("http://example.net/path/to/something.html", normalizer
+ .normalize("http://www.example.net/path/to/something.html",
+ URLNormalizers.SCOPE_DEFAULT));
// Force all sub domains to www.
- Assert.assertEquals("http://example.com/?does=it&still=work", normalizer.normalize("http://example.com/?does=it&still=work", URLNormalizers.SCOPE_DEFAULT));
- Assert.assertEquals("http://example.com/buh", normalizer.normalize("http://http.www.example.com/buh", URLNormalizers.SCOPE_DEFAULT));
- Assert.assertEquals("http://example.com/blaat", normalizer.normalize("http://whatever.example.com/blaat", URLNormalizers.SCOPE_DEFAULT));
+ Assert.assertEquals("http://example.com/?does=it&still=work", normalizer
+ .normalize("http://example.com/?does=it&still=work",
+ URLNormalizers.SCOPE_DEFAULT));
+ Assert.assertEquals("http://example.com/buh", normalizer.normalize(
+ "http://http.www.example.com/buh", URLNormalizers.SCOPE_DEFAULT));
+ Assert.assertEquals("http://example.com/blaat", normalizer.normalize(
+ "http://whatever.example.com/blaat", URLNormalizers.SCOPE_DEFAULT));
}
}
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.java
index bd505b4ff..03d510c67 100644
--- 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.java
@@ -24,15 +24,17 @@ 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.
+ * 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 {
+
+ public String normalize(String urlString, String scope)
+ throws MalformedURLException {
return urlString;
}
@@ -41,7 +43,7 @@ public class PassURLNormalizer implements URLNormalizer {
}
public void setConf(Configuration conf) {
- this.conf = conf;
+ this.conf = conf;
}
}
diff --git a/src/plugin/urlnormalizer-pass/src/java/org/apache/nutch/net/urlnormalizer/pass/package-info.java b/src/plugin/urlnormalizer-pass/src/java/org/apache/nutch/net/urlnormalizer/pass/package-info.java
index e954339ff..eab6c2ecd 100644
--- a/src/plugin/urlnormalizer-pass/src/java/org/apache/nutch/net/urlnormalizer/pass/package-info.java
+++ b/src/plugin/urlnormalizer-pass/src/java/org/apache/nutch/net/urlnormalizer/pass/package-info.java
@@ -20,3 +20,4 @@
* one URL normalizer must be defined in any scope.
*/
package org.apache.nutch.net.urlnormalizer.pass;
+
diff --git a/src/plugin/urlnormalizer-pass/src/test/org/apache/nutch/net/urlnormalizer/pass/TestPassURLNormalizer.java b/src/plugin/urlnormalizer-pass/src/test/org/apache/nutch/net/urlnormalizer/pass/TestPassURLNormalizer.java
index f4643dd51..f470c627e 100644
--- a/src/plugin/urlnormalizer-pass/src/test/org/apache/nutch/net/urlnormalizer/pass/TestPassURLNormalizer.java
+++ b/src/plugin/urlnormalizer-pass/src/test/org/apache/nutch/net/urlnormalizer/pass/TestPassURLNormalizer.java
@@ -29,7 +29,7 @@ public class TestPassURLNormalizer {
@Test
public void testPassURLNormalizer() {
Configuration conf = NutchConfiguration.create();
-
+
PassURLNormalizer normalizer = new PassURLNormalizer();
normalizer.setConf(conf);
String url = "http://www.example.com/test/..//";
@@ -39,7 +39,7 @@ public class TestPassURLNormalizer {
} catch (MalformedURLException mue) {
Assert.fail(mue.toString());
}
-
+
Assert.assertEquals(url, result);
}
}
diff --git a/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/QuerystringURLNormalizer.java b/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/QuerystringURLNormalizer.java
index e2f7b8244..1de03a3b8 100644
--- a/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/QuerystringURLNormalizer.java
+++ b/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/QuerystringURLNormalizer.java
@@ -33,18 +33,20 @@ import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.URLUtil;
/**
- * URL normalizer plugin for normalizing query strings but sorting
- * query string parameters. Not sorting query strings can lead to large
- * amounts of duplicate URL's such as ?a=x&b=y vs b=y&a=x.
- *
+ * URL normalizer plugin for normalizing query strings but sorting query string
+ * parameters. Not sorting query strings can lead to large amounts of duplicate
+ * URL's such as ?a=x&b=y vs b=y&a=x.
+ *
*/
public class QuerystringURLNormalizer implements URLNormalizer {
private Configuration conf;
- private static final Logger LOG = LoggerFactory.getLogger(QuerystringURLNormalizer.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(QuerystringURLNormalizer.class);
- public QuerystringURLNormalizer() {}
+ public QuerystringURLNormalizer() {
+ }
public Configuration getConf() {
return conf;
@@ -54,20 +56,21 @@ public class QuerystringURLNormalizer implements URLNormalizer {
this.conf = conf;
}
- public String normalize(String urlString, String scope) throws MalformedURLException {
+ public String normalize(String urlString, String scope)
+ throws MalformedURLException {
URL url = new URL(urlString);
-
+
String queryString = url.getQuery();
-
+
if (queryString == null) {
return urlString;
}
-
+
List<String> queryStringParts = Arrays.asList(queryString.split("&"));
Collections.sort(queryStringParts);
-
+
StringBuilder sb = new StringBuilder();
-
+
sb.append(url.getProtocol());
sb.append("://");
sb.append(url.getHost());
@@ -82,7 +85,7 @@ public class QuerystringURLNormalizer implements URLNormalizer {
sb.append("#");
sb.append(url.getRef());
}
-
+
return sb.toString();
}
}
diff --git a/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/package-info.java b/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/package-info.java
index c125ccb46..005fbca01 100644
--- a/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/package-info.java
+++ b/src/plugin/urlnormalizer-querystring/src/java/org/apache/nutch/net/urlnormalizer/querystring/package-info.java
@@ -20,3 +20,4 @@
* by permutations.
*/
package org.apache.nutch.net.urlnormalizer.querystring;
+
diff --git a/src/plugin/urlnormalizer-querystring/src/test/org/apache/nutch/net/urlnormalizer/querystring/TestQuerystringURLNormalizer.java b/src/plugin/urlnormalizer-querystring/src/test/org/apache/nutch/net/urlnormalizer/querystring/TestQuerystringURLNormalizer.java
index 0f785e4ee..b85c55dbe 100644
--- a/src/plugin/urlnormalizer-querystring/src/test/org/apache/nutch/net/urlnormalizer/querystring/TestQuerystringURLNormalizer.java
+++ b/src/plugin/urlnormalizer-querystring/src/test/org/apache/nutch/net/urlnormalizer/querystring/TestQuerystringURLNormalizer.java
@@ -31,12 +31,19 @@ public class TestQuerystringURLNormalizer extends TestCase {
QuerystringURLNormalizer normalizer = new QuerystringURLNormalizer();
normalizer.setConf(conf);
-
- assertEquals("http://example.com/?a=b&c=d", normalizer.normalize("http://example.com/?c=d&a=b", URLNormalizers.SCOPE_DEFAULT));
- assertEquals("http://example.com/a/b/c", normalizer.normalize("http://example.com/a/b/c", URLNormalizers.SCOPE_DEFAULT));
- assertEquals("http://example.com:1234/a/b/c", normalizer.normalize("http://example.com:1234/a/b/c", URLNormalizers.SCOPE_DEFAULT));
- assertEquals("http://example.com:1234/a/b/c#ref", normalizer.normalize("http://example.com:1234/a/b/c#ref", URLNormalizers.SCOPE_DEFAULT));
- assertEquals("http://example.com:1234/a/b/c?a=b&c=d#ref", normalizer.normalize("http://example.com:1234/a/b/c?c=d&a=b#ref", URLNormalizers.SCOPE_DEFAULT));
- assertEquals("http://example.com/?a=b&a=c&c=d", normalizer.normalize("http://example.com/?c=d&a=b&a=c", URLNormalizers.SCOPE_DEFAULT));
+
+ assertEquals("http://example.com/?a=b&c=d", normalizer.normalize(
+ "http://example.com/?c=d&a=b", URLNormalizers.SCOPE_DEFAULT));
+ assertEquals("http://example.com/a/b/c", normalizer.normalize(
+ "http://example.com/a/b/c", URLNormalizers.SCOPE_DEFAULT));
+ assertEquals("http://example.com:1234/a/b/c", normalizer.normalize(
+ "http://example.com:1234/a/b/c", URLNormalizers.SCOPE_DEFAULT));
+ assertEquals("http://example.com:1234/a/b/c#ref", normalizer.normalize(
+ "http://example.com:1234/a/b/c#ref", URLNormalizers.SCOPE_DEFAULT));
+ assertEquals("http://example.com:1234/a/b/c?a=b&c=d#ref",
+ normalizer.normalize("http://example.com:1234/a/b/c?c=d&a=b#ref",
+ URLNormalizers.SCOPE_DEFAULT));
+ assertEquals("http://example.com/?a=b&a=c&c=d", normalizer.normalize(
+ "http://example.com/?c=d&a=b&a=c", URLNormalizers.SCOPE_DEFAULT));
}
}
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.java
index 537132379..363da188f 100644
--- 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.java
@@ -51,19 +51,23 @@ import org.xml.sax.InputSource;
* 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>
+ * 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>
- * <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 Logger LOG = LoggerFactory.getLogger(RegexURLNormalizer.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(RegexURLNormalizer.class);
/**
* Class which holds a compiled pattern and its corresponding substition
@@ -75,19 +79,18 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
public String substitution;
}
- private ThreadLocal<HashMap<String, List<Rule>>> scopedRulesThreadLocal =
- new ThreadLocal<HashMap<String,List<Rule>>>() {
- protected java.util.HashMap<String,java.util.List<Rule>> initialValue() {
+ private ThreadLocal<HashMap<String, List<Rule>>> scopedRulesThreadLocal = new ThreadLocal<HashMap<String, List<Rule>>>() {
+ protected java.util.HashMap<String, java.util.List<Rule>> initialValue() {
return new HashMap<String, List<Rule>>();
};
};
-
+
public HashMap<String, List<Rule>> getScopedRules() {
return scopedRulesThreadLocal.get();
}
-
- private List<Rule> defaultRules;
-
+
+ private List<Rule> defaultRules;
+
private static final List<Rule> EMPTY_RULES = Collections.emptyList();
/**
@@ -107,7 +110,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
* configuration files for it.
*/
public RegexURLNormalizer(Configuration conf, String filename)
- throws IOException, PatternSyntaxException {
+ throws IOException, PatternSyntaxException {
super(conf);
List<Rule> rules = readConfigurationFile(filename);
if (rules != null) {
@@ -117,7 +120,8 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
public void setConf(Configuration conf) {
super.setConf(conf);
- if (conf == null) return;
+ if (conf == null)
+ return;
// the default constructor was called
String filename = getConf().get("urlnormalizer.regex.file");
@@ -147,9 +151,10 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
void setConfiguration(Reader reader, String scope) {
List<Rule> rules = readConfiguration(reader);
getScopedRules().put(scope, rules);
- LOG.debug("Set config for scope '" + scope + "': " + rules.size() + " 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.
@@ -190,7 +195,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
}
public String normalize(String urlString, String scope)
- throws MalformedURLException {
+ throws MalformedURLException {
return regexNormalize(urlString, scope);
}
@@ -207,17 +212,17 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
return EMPTY_RULES;
}
}
-
+
private List<Rule> readConfiguration(Reader reader) {
List<Rule> rules = new ArrayList<Rule>();
try {
// borrowed heavily from code in Configuration.java
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
- .parse(new InputSource(reader));
+ .parse(new InputSource(reader));
Element root = doc.getDocumentElement();
if ((!"regex-normalize".equals(root.getTagName()))
- && (LOG.isErrorEnabled())) {
+ && (LOG.isErrorEnabled())) {
LOG.error("bad conf file: top-level element not <regex-normalize>");
}
NodeList regexes = root.getChildNodes();
@@ -240,7 +245,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
if ("pattern".equals(field.getTagName()) && field.hasChildNodes())
patternValue = ((Text) field.getFirstChild()).getData();
if ("substitution".equals(field.getTagName())
- && field.hasChildNodes())
+ && field.hasChildNodes())
subValue = ((Text) field.getFirstChild()).getData();
if (!field.hasChildNodes())
subValue = "";
@@ -251,7 +256,8 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
rule.pattern = Pattern.compile(patternValue);
} catch (PatternSyntaxException e) {
if (LOG.isErrorEnabled()) {
- LOG.error("skipped rule: " + patternValue + " -> " + subValue + " : invalid regular expression pattern: " + e);
+ LOG.error("skipped rule: " + patternValue + " -> " + subValue
+ + " : invalid regular expression pattern: " + e);
}
continue;
}
@@ -265,13 +271,14 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
}
return EMPTY_RULES;
}
- if (rules.size() == 0) 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 PatternSyntaxException,
- IOException {
+ IOException {
RegexURLNormalizer normalizer = new RegexURLNormalizer();
normalizer.setConf(NutchConfiguration.create());
HashMap<String, List<Rule>> scopedRules = normalizer.getScopedRules();
@@ -290,9 +297,10 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
Iterator<String> it = scopedRules.keySet().iterator();
while (it.hasNext()) {
String scope = it.next();
- if (URLNormalizers.SCOPE_DEFAULT.equals(scope)) continue;
+ if (URLNormalizers.SCOPE_DEFAULT.equals(scope))
+ continue;
System.out.println("* Rules for '" + scope + "' scope:");
- i = ((List<Rule>)scopedRules.get(scope)).iterator();
+ i = ((List<Rule>) scopedRules.get(scope)).iterator();
while (i.hasNext()) {
Rule r = (Rule) i.next();
System.out.print(" " + r.pattern.pattern() + " -> ");
@@ -303,10 +311,12 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
if (args.length > 0) {
System.out.println("\n---------- Normalizer test -----------");
String scope = URLNormalizers.SCOPE_DEFAULT;
- if (args.length > 1) scope = args[1];
+ 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.out.println("Output url: '" + normalizer.normalize(args[0], scope)
+ + "'");
}
System.exit(0);
}
diff --git a/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/package-info.java b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/package-info.java
index 4a9c297a6..04562c36b 100644
--- a/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/package-info.java
+++ b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/package-info.java
@@ -20,3 +20,4 @@
* ({@link java.util.regex.Pattern}).
*/
package org.apache.nutch.net.urlnormalizer.regex;
+
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.java
index e569d5289..cbf6c64f6 100644
--- 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.java
@@ -36,24 +36,27 @@ import org.apache.nutch.util.NutchConfiguration;
/** Unit tests for RegexUrlNormalizer. */
public class TestRegexURLNormalizer {
- private static final Logger LOG = LoggerFactory.getLogger(TestRegexURLNormalizer.class);
-
+ private static final Logger LOG = LoggerFactory
+ .getLogger(TestRegexURLNormalizer.class);
+
private RegexURLNormalizer normalizer;
private Configuration conf;
private Map<String, NormalizedURL[]> testData = new HashMap<String, NormalizedURL[]>();
-
+
// 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() throws IOException {
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-"))
+ if (f.getName().endsWith(".xml")
+ && f.getName().startsWith("regex-normalize-"))
return true;
return false;
}
@@ -74,8 +77,8 @@ public class TestRegexURLNormalizer {
@Test
public void testNormalizerDefault() throws Exception {
- normalizeTest((NormalizedURL[])testData.get(URLNormalizers.SCOPE_DEFAULT),
- URLNormalizers.SCOPE_DEFAULT);
+ normalizeTest((NormalizedURL[]) testData.get(URLNormalizers.SCOPE_DEFAULT),
+ URLNormalizers.SCOPE_DEFAULT);
}
@Test
@@ -83,33 +86,36 @@ public class TestRegexURLNormalizer {
Iterator<String> it = testData.keySet().iterator();
while (it.hasNext()) {
String scope = it.next();
- normalizeTest((NormalizedURL[])testData.get(scope), scope);
+ normalizeTest((NormalizedURL[]) testData.get(scope), scope);
}
}
- private void normalizeTest(NormalizedURL[] urls, String scope) throws Exception {
+ private void normalizeTest(NormalizedURL[] urls, String scope)
+ throws Exception {
for (int i = 0; i < urls.length; i++) {
String url = urls[i].url;
String normalized = normalizer.normalize(urls[i].url, scope);
String expected = urls[i].expectedURL;
- LOG.info("scope: " + scope + " url: " + url + " | normalized: " + normalized + " | expected: " + expected);
+ LOG.info("scope: " + scope + " url: " + url + " | normalized: "
+ + normalized + " | expected: " + expected);
Assert.assertEquals(urls[i].expectedURL, normalized);
}
}
-
+
private void bench(int loops, String scope) {
long start = System.currentTimeMillis();
try {
- NormalizedURL[] expected = (NormalizedURL[])testData.get(scope);
- if (expected == null) return;
+ NormalizedURL[] expected = (NormalizedURL[]) testData.get(scope);
+ if (expected == null)
+ return;
for (int i = 0; i < loops; i++) {
normalizeTest(expected, scope);
}
} catch (Exception e) {
Assert.fail(e.toString());
}
- LOG.info("bench time (" + loops + ") " +
- (System.currentTimeMillis() - start) + "ms");
+ LOG.info("bench time (" + loops + ") "
+ + (System.currentTimeMillis() - start) + "ms");
}
private static class NormalizedURL {
@@ -126,17 +132,18 @@ public class TestRegexURLNormalizer {
private NormalizedURL[] readTestFile(String scope) throws IOException {
File f = new File(sampleDir, "regex-normalize-" + scope + ".test");
@SuppressWarnings("resource")
- BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
+ BufferedReader in = new BufferedReader(new InputStreamReader(
+ new FileInputStream(f), "UTF-8"));
List<NormalizedURL> list = new ArrayList<NormalizedURL>();
String line;
- while((line = in.readLine()) != null) {
- if ( line.trim().length() == 0 ||
- line.startsWith("#") ||
- line.startsWith(" ")) continue;
+ 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) {
@@ -150,7 +157,8 @@ public class TestRegexURLNormalizer {
if (args[i].equals("-bench")) {
bench = true;
iter = Integer.parseInt(args[++i]);
- } else scope = args[i];
+ } else
+ scope = args[i];
}
if (scope == null) {
System.err.println("Missing required scope name.");
@@ -161,11 +169,12 @@ public class TestRegexURLNormalizer {
System.exit(-1);
}
TestRegexURLNormalizer test = new TestRegexURLNormalizer();
- NormalizedURL[] urls = (NormalizedURL[])test.testData.get(scope);
+ NormalizedURL[] urls = (NormalizedURL[]) test.testData.get(scope);
if (urls == null) {
- LOG.warn("Missing test data for scope '" + scope + "', using default scope.");
+ LOG.warn("Missing test data for scope '" + scope
+ + "', using default scope.");
scope = URLNormalizers.SCOPE_DEFAULT;
- urls = (NormalizedURL[])test.testData.get(scope);
+ urls = (NormalizedURL[]) test.testData.get(scope);
}
if (bench) {
test.bench(iter, scope);
@@ -174,6 +183,4 @@ public class TestRegexURLNormalizer {
}
}
-
-
}
diff --git a/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java b/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
index 9949271fa..bb938a626 100644
--- a/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
+++ b/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
@@ -35,19 +35,26 @@ import org.slf4j.LoggerFactory;
/**
* Emulate a continuous crawl for one URL.
- *
+ *
*/
public class ContinuousCrawlTestUtil extends TestCase {
- private static final Logger LOG = LoggerFactory.getLogger(ContinuousCrawlTestUtil.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(ContinuousCrawlTestUtil.class);
protected static Text dummyURL = new Text("http://nutch.apache.org/");
protected static Configuration defaultConfig = CrawlDBTestUtil
.createConfiguration();
- protected long interval = FetchSchedule.SECONDS_PER_DAY*1000; // (default) launch crawler every day
- protected long duration = 2*365L*FetchSchedule.SECONDS_PER_DAY*1000L; // run for two years
+ protected long interval = FetchSchedule.SECONDS_PER_DAY * 1000; // (default)
+ // launch
+ // crawler
+ // every day
+ protected long duration = 2 * 365L * FetchSchedule.SECONDS_PER_DAY * 1000L; // run
+ // for
+ // two
+ // years
protected Configuration configuration;
private FetchSchedule schedule;
@@ -62,7 +69,7 @@ public class ContinuousCrawlTestUtil extends TestCase {
protected Content content = new Content();
{
- byte[] data = {'n', 'u', 't', 'c', 'h'};
+ byte[] data = { 'n', 'u', 't', 'c', 'h' };
content.setContent(data);
}
@@ -89,17 +96,17 @@ public class ContinuousCrawlTestUtil extends TestCase {
/** set the interval the crawl is relaunched (default: every day) */
protected void setInterval(int seconds) {
- interval = seconds*1000L;
+ interval = seconds * 1000L;
}
/** set the duration of the continuous crawl (default = 2 years) */
protected void setDuraction(int seconds) {
- duration = seconds*1000L;
+ duration = seconds * 1000L;
}
/**
* default fetch action: set status and time
- *
+ *
* @param datum
* CrawlDatum to fetch
* @param currentTime
@@ -124,19 +131,20 @@ public class ContinuousCrawlTestUtil extends TestCase {
* change content to force a changed signature
*/
protected void changeContent() {
- byte [] data = Arrays.copyOf(content.getContent(), content.getContent().length+1);
+ byte[] data = Arrays.copyOf(content.getContent(),
+ content.getContent().length + 1);
data[content.getContent().length] = '2'; // append one byte
content.setContent(data);
LOG.info("document content changed");
}
-
/**
* default parse action: add signature if successfully fetched
- *
+ *
* @param fetchDatum
* fetch datum
- * @return list of all datums resulting from parse (status: signature, linked, parse_metadata)
+ * @return list of all datums resulting from parse (status: signature, linked,
+ * parse_metadata)
*/
protected List<CrawlDatum> parse(CrawlDatum fetchDatum) {
List<CrawlDatum> parseDatums = new ArrayList<CrawlDatum>(0);
@@ -150,7 +158,7 @@ public class ContinuousCrawlTestUtil extends TestCase {
/**
* default implementation to check the result state
- *
+ *
* @param datum
* the CrawlDatum to be checked
* @return true if the check succeeds
@@ -166,7 +174,7 @@ public class ContinuousCrawlTestUtil extends TestCase {
* <p>
* A loop emulates a continuous crawl launched in regular intervals (see
* {@link #setInterval(int)} over a longer period ({@link #setDuraction(int)}.
- *
+ *
* <ul>
* <li>every "round" emulates
* <ul>
@@ -177,11 +185,11 @@ public class ContinuousCrawlTestUtil extends TestCase {
* <li>and is checked whether it is correct (see {@link #check(CrawlDatum)})
* </ul>
* </p>
- *
+ *
* @param maxErrors
* (if > 0) continue crawl even if the checked CrawlDatum is not
* correct, but stop after max. number of errors
- *
+ *
* @return false if a check of CrawlDatum failed, true otherwise
*/
protected boolean run(int maxErrors) {
@@ -205,9 +213,11 @@ public class ContinuousCrawlTestUtil extends TestCase {
long lastFetchTime = -1;
boolean ok = true; // record failure but keep going
CrawlDatum fetchDatum = new CrawlDatum();
- /* Keep copies because CrawlDbReducer.reduce()
- * and FetchSchedule.shouldFetch() may alter the references.
- * Copies are used for verbose logging in case of an error. */
+ /*
+ * Keep copies because CrawlDbReducer.reduce() and
+ * FetchSchedule.shouldFetch() may alter the references. Copies are used for
+ * verbose logging in case of an error.
+ */
CrawlDatum copyDbDatum = new CrawlDatum();
CrawlDatum copyFetchDatum = new CrawlDatum();
CrawlDatum afterShouldFetch = new CrawlDatum();
diff --git a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
index 92e805455..2e53766a9 100644
--- a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
+++ b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
@@ -36,10 +36,10 @@ import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.handler.ResourceHandler;
-
public class CrawlDBTestUtil {
- private static final Logger LOG = LoggerFactory.getLogger(CrawlDBTestUtil.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(CrawlDBTestUtil.class);
/**
* Creates synthetic crawldb
@@ -52,12 +52,12 @@ public class CrawlDBTestUtil {
* urls to be inserted, objects are of type URLCrawlDatum
* @throws Exception
*/
- public static void createCrawlDb(Configuration conf, FileSystem fs, Path crawldb, List<URLCrawlDatum> init)
- throws Exception {
+ public static void createCrawlDb(Configuration conf, FileSystem fs,
+ Path crawldb, List<URLCrawlDatum> init) throws Exception {
LOG.trace("* creating crawldb: " + crawldb);
Path dir = new Path(crawldb, CrawlDb.CURRENT_NAME);
- MapFile.Writer writer = new MapFile.Writer(conf, fs, new Path(dir, "part-00000")
- .toString(), Text.class, CrawlDatum.class);
+ MapFile.Writer writer = new MapFile.Writer(conf, fs, new Path(dir,
+ "part-00000").toString(), Text.class, CrawlDatum.class);
Iterator<URLCrawlDatum> it = init.iterator();
while (it.hasNext()) {
URLCrawlDatum row = it.next();
@@ -69,25 +69,25 @@ public class CrawlDBTestUtil {
/**
* For now we need to manually construct our Configuration, because we need to
- * override the default one and it is currently not possible to use dynamically
- * set values.
+ * override the default one and it is currently not possible to use
+ * dynamically set values.
*
* @return
* @deprecated Use {@link #createConfiguration()} instead
*/
@Deprecated
- public static Configuration create(){
+ public static Configuration create() {
return createConfiguration();
}
/**
* For now we need to manually construct our Configuration, because we need to
- * override the default one and it is currently not possible to use dynamically
- * set values.
+ * override the default one and it is currently not possible to use
+ * dynamically set values.
*
* @return
*/
- public static Configuration createConfiguration(){
+ public static Configuration createConfiguration() {
Configuration conf = new Configuration();
conf.addResource("nutch-default.xml");
conf.addResource("crawl-tests.xml");
@@ -108,32 +108,36 @@ public class CrawlDBTestUtil {
/**
* Generate seedlist
- * @throws IOException
+ *
+ * @throws IOException
*/
- public static void generateSeedList(FileSystem fs, Path urlPath, List<String> urls) throws IOException{
+ public static void generateSeedList(FileSystem fs, Path urlPath,
+ List<String> urls) throws IOException {
generateSeedList(fs, urlPath, urls, new ArrayList<String>());
}
-
+
/**
* Generate seedlist
- * @throws IOException
+ *
+ * @throws IOException
*/
- public static void generateSeedList(FileSystem fs, Path urlPath, List<String> urls, List<String>metadata) throws IOException{
+ public static void generateSeedList(FileSystem fs, Path urlPath,
+ List<String> urls, List<String> metadata) throws IOException {
FSDataOutputStream out;
- Path file=new Path(urlPath,"urls.txt");
+ Path file = new Path(urlPath, "urls.txt");
fs.mkdirs(urlPath);
- out=fs.create(file);
-
- Iterator<String> urls_i=urls.iterator();
- Iterator<String> metadata_i=metadata.iterator();
-
+ out = fs.create(file);
+
+ Iterator<String> urls_i = urls.iterator();
+ Iterator<String> metadata_i = metadata.iterator();
+
String url;
String md;
- while(urls_i.hasNext()){
- url=urls_i.next();
+ while (urls_i.hasNext()) {
+ url = urls_i.next();
out.writeBytes(url);
-
+
if (metadata_i.hasNext()) {
md = metadata_i.next();
out.writeBytes(md);
@@ -141,19 +145,22 @@ public class CrawlDBTestUtil {
out.writeBytes("\n");
}
-
+
out.flush();
out.close();
}
-
+
/**
* Creates a new JettyServer with one static root context
*
- * @param port port to listen to
- * @param staticContent folder where static content lives
- * @throws UnknownHostException
+ * @param port
+ * port to listen to
+ * @param staticContent
+ * folder where static content lives
+ * @throws UnknownHostException
*/
- public static Server getServer(int port, String staticContent) throws UnknownHostException{
+ public static Server getServer(int port, String staticContent)
+ throws UnknownHostException {
Server webServer = new org.mortbay.jetty.Server();
SocketConnector listener = new SocketConnector();
listener.setPort(port);
diff --git a/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java b/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java
index f5f3db8cb..bfb716d0d 100644
--- a/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java
+++ b/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java
@@ -45,7 +45,8 @@ import org.slf4j.LoggerFactory;
*/
public class CrawlDbUpdateUtil<T extends Reducer<Text, CrawlDatum, Text, CrawlDatum>> {
- private static final Logger LOG = LoggerFactory.getLogger(CrawlDbUpdateUtil.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(CrawlDbUpdateUtil.class);
private T reducer;
@@ -74,9 +75,8 @@ public class CrawlDbUpdateUtil<T extends Reducer<Text, CrawlDatum, Text, CrawlDa
}
/**
- * Dummy reporter which does nothing and does not return null for
- * getCounter()
- *
+ * Dummy reporter which does nothing and does not return null for getCounter()
+ *
* @see {@link Reporter#NULL}
*/
private class DummyReporter implements Reporter {
@@ -117,8 +117,10 @@ public class CrawlDbUpdateUtil<T extends Reducer<Text, CrawlDatum, Text, CrawlDa
* run
* {@link CrawlDbReducer#reduce(Text, Iterator, OutputCollector, Reporter)}
* and return the CrawlDatum(s) which would have been written into CrawlDb
- * @param values list of input CrawlDatums
- * @return list of resulting CrawlDatum(s) in CrawlDb
+ *
+ * @param values
+ * list of input CrawlDatums
+ * @return list of resulting CrawlDatum(s) in CrawlDb
*/
public List<CrawlDatum> update(List<CrawlDatum> values) {
if (values == null || values.size() == 0) {
@@ -138,12 +140,14 @@ public class CrawlDbUpdateUtil<T extends Reducer<Text, CrawlDatum, Text, CrawlDa
* run
* {@link CrawlDbReducer#reduce(Text, Iterator, OutputCollector, Reporter)}
* and return the CrawlDatum(s) which would have been written into CrawlDb
- * @param dbDatum previous CrawlDatum in CrawlDb
- * @param fetchDatum CrawlDatum resulting from fetching
- * @return list of resulting CrawlDatum(s) in CrawlDb
+ *
+ * @param dbDatum
+ * previous CrawlDatum in CrawlDb
+ * @param fetchDatum
+ * CrawlDatum resulting from fetching
+ * @return list of resulting CrawlDatum(s) in CrawlDb
*/
- public List<CrawlDatum> update(CrawlDatum dbDatum,
- CrawlDatum fetchDatum) {
+ public List<CrawlDatum> update(CrawlDatum dbDatum, CrawlDatum fetchDatum) {
List<CrawlDatum> values = new ArrayList<CrawlDatum>();
if (dbDatum != null)
values.add(dbDatum);
diff --git a/src/test/org/apache/nutch/crawl/DummyWritable.java b/src/test/org/apache/nutch/crawl/DummyWritable.java
index 10dba3236..94c27b568 100644
--- a/src/test/org/apache/nutch/crawl/DummyWritable.java
+++ b/src/test/org/apache/nutch/crawl/DummyWritable.java
@@ -21,12 +21,12 @@ import org.apache.hadoop.io.IntWritable;
public class DummyWritable extends IntWritable {
- public DummyWritable() {
+ public DummyWritable() {
- }
+ }
- public DummyWritable(int i) {
- super(i);
- }
+ public DummyWritable(int i) {
+ super(i);
+ }
}
diff --git a/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java b/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
index 5a23aea98..e44cb3998 100644
--- a/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
+++ b/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
@@ -13,11 +13,12 @@ import org.slf4j.LoggerFactory;
public class TODOTestCrawlDbStates extends TestCrawlDbStates {
- private static final Logger LOG = LoggerFactory.getLogger(TODOTestCrawlDbStates.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(TODOTestCrawlDbStates.class);
/**
- * NUTCH-578: a fetch_retry should result in a db_gone if db.fetch.retry.max is reached.
- * Retry counter has to be reset appropriately.
+ * NUTCH-578: a fetch_retry should result in a db_gone if db.fetch.retry.max
+ * is reached. Retry counter has to be reset appropriately.
*/
@Test
public void testCrawlDbReducerPageRetrySchedule() {
@@ -86,8 +87,7 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
* <p>
* Problem: documents not modified for a longer time are fetched in every
* cycle because of an error in the SYNC_DELTA calculation of
- * {@link AdaptiveFetchSchedule}.
- * <br>
+ * {@link AdaptiveFetchSchedule}. <br>
* The next fetch time should always be in the future, never in the past.
* </p>
*/
@@ -95,15 +95,15 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
public void testAdaptiveFetchScheduleSyncDelta() {
LOG.info("NUTCH-1564 test SYNC_DELTA calculation of AdaptiveFetchSchedule");
Configuration conf = CrawlDBTestUtil.createConfiguration();
- conf.setLong("db.fetch.interval.default", 172800); // 2 days
- conf.setLong("db.fetch.schedule.adaptive.min_interval", 86400); // 1 day
+ conf.setLong("db.fetch.interval.default", 172800); // 2 days
+ conf.setLong("db.fetch.schedule.adaptive.min_interval", 86400); // 1 day
conf.setLong("db.fetch.schedule.adaptive.max_interval", 604800); // 7 days
- conf.setLong("db.fetch.interval.max", 604800); // 7 days
+ conf.setLong("db.fetch.interval.max", 604800); // 7 days
conf.set("db.fetch.schedule.class",
"org.apache.nutch.crawl.AdaptiveFetchSchedule");
ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchScheduleNotModifiedFetchTime(
conf);
- crawlUtil.setInterval(FetchSchedule.SECONDS_PER_DAY/3);
+ crawlUtil.setInterval(FetchSchedule.SECONDS_PER_DAY / 3);
if (!crawlUtil.run(100)) {
fail("failed: sync_delta calculation with AdaptiveFetchSchedule");
}
@@ -150,10 +150,10 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
// next fetch time is in less than one minute
// (critical: Nutch can hardly be so fast)
LOG.error("Less then one minute until next fetch: " + result);
- }
+ }
// Next fetch time should be within min. and max. (tolerance: 60 sec.)
- if (secondsUntilNextFetch+60 < minInterval
- || secondsUntilNextFetch-60 > maxInterval) {
+ if (secondsUntilNextFetch + 60 < minInterval
+ || secondsUntilNextFetch - 60 > maxInterval) {
LOG.error("Interval until next fetch time ("
+ TimingUtil.elapsedTime(fetchTime, result.getFetchTime())
+ ") is not within min. and max. interval: " + result);
diff --git a/src/test/org/apache/nutch/crawl/TestAdaptiveFetchSchedule.java b/src/test/org/apache/nutch/crawl/TestAdaptiveFetchSchedule.java
index 020b8b686..3fa798d68 100644
--- a/src/test/org/apache/nutch/crawl/TestAdaptiveFetchSchedule.java
+++ b/src/test/org/apache/nutch/crawl/TestAdaptiveFetchSchedule.java
@@ -61,19 +61,19 @@ public class TestAdaptiveFetchSchedule extends TestCase {
Text url = new Text("http://www.example.com");
changed = FetchSchedule.STATUS_UNKNOWN;
- fs.setFetchSchedule(url, p, p.getFetchTime(),
- p.getModifiedTime(), curTime, lastModified, changed);
+ fs.setFetchSchedule(url, p, p.getFetchTime(), p.getModifiedTime(), curTime,
+ lastModified, changed);
validateFetchInterval(changed, p.getFetchInterval());
changed = FetchSchedule.STATUS_MODIFIED;
- fs.setFetchSchedule(url, p, p.getFetchTime(),
- p.getModifiedTime(), curTime, lastModified, changed);
+ fs.setFetchSchedule(url, p, p.getFetchTime(), p.getModifiedTime(), curTime,
+ lastModified, changed);
validateFetchInterval(changed, p.getFetchInterval());
p.setFetchInterval(interval);
changed = FetchSchedule.STATUS_NOTMODIFIED;
- fs.setFetchSchedule(url, p, p.getFetchTime(),
- p.getModifiedTime(), curTime, lastModified, changed);
+ fs.setFetchSchedule(url, p, p.getFetchTime(), p.getModifiedTime(), curTime,
+ lastModified, changed);
validateFetchInterval(changed, p.getFetchInterval());
}
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java b/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java
index 88c945d6d..6b762fe18 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
package org.apache.nutch.crawl;
import java.io.IOException;
@@ -34,9 +34,9 @@ import org.junit.Before;
import org.junit.Test;
/**
- * CrawlDbFiltering test which tests for correct, error free url
- * normalization when the CrawlDB includes urls with <code>DB GONE</code> status
- * and <code>CRAWLDB_PURGE_404</code> is set to true.
+ * CrawlDbFiltering test which tests for correct, error free url normalization
+ * when the CrawlDB includes urls with <code>DB GONE</code> status and
+ * <code>CRAWLDB_PURGE_404</code> is set to true.
*
* @author lufeng
*/
@@ -68,27 +68,27 @@ public class TestCrawlDbFilter {
/**
* Test url404Purging
- *
+ *
* @throws Exception
*/
@Test
public void testUrl404Purging() throws Exception {
// create a CrawlDatum with DB GONE status
ArrayList<URLCrawlDatum> list = new ArrayList<URLCrawlDatum>();
- list.add(new URLCrawlDatum(new Text("http://www.example.com"), new CrawlDatum(
- CrawlDatum.STATUS_DB_GONE, 0, 0.0f)));
- list.add(new URLCrawlDatum(new Text("http://www.example1.com"), new CrawlDatum(
- CrawlDatum.STATUS_DB_FETCHED, 0, 0.0f)));
- list.add(new URLCrawlDatum(new Text("http://www.example2.com"), new CrawlDatum(
- CrawlDatum.STATUS_DB_UNFETCHED, 0, 0.0f)));
+ list.add(new URLCrawlDatum(new Text("http://www.example.com"),
+ new CrawlDatum(CrawlDatum.STATUS_DB_GONE, 0, 0.0f)));
+ list.add(new URLCrawlDatum(new Text("http://www.example1.com"),
+ new CrawlDatum(CrawlDatum.STATUS_DB_FETCHED, 0, 0.0f)));
+ list.add(new URLCrawlDatum(new Text("http://www.example2.com"),
+ new CrawlDatum(CrawlDatum.STATUS_DB_UNFETCHED, 0, 0.0f)));
dbDir = new Path(testdir, "crawldb");
- newCrawlDb = new Path(testdir,"newcrawldb");
+ newCrawlDb = new Path(testdir, "newcrawldb");
// create crawldb
CrawlDBTestUtil.createCrawlDb(conf, fs, dbDir, list);
// set CRAWLDB_PURGE_404 to true
- conf.setBoolean(CrawlDb.CRAWLDB_PURGE_404,true);
- conf.setBoolean(CrawlDbFilter.URL_NORMALIZING,true);
- conf.setBoolean(CrawlDbFilter.URL_FILTERING,false);
+ conf.setBoolean(CrawlDb.CRAWLDB_PURGE_404, true);
+ conf.setBoolean(CrawlDbFilter.URL_NORMALIZING, true);
+ conf.setBoolean(CrawlDbFilter.URL_FILTERING, false);
conf.setInt("urlnormalizer.loop.count", 2);
JobConf job = new NutchJob(conf);
job.setJobName("Test CrawlDbFilter");
@@ -105,8 +105,7 @@ public class TestCrawlDbFilter {
job.setOutputValueClass(CrawlDatum.class);
JobClient.runJob(job);
- Path fetchlist = new Path(new Path(newCrawlDb,
- "part-00000"), "data");
+ Path fetchlist = new Path(new Path(newCrawlDb, "part-00000"), "data");
ArrayList<URLCrawlDatum> l = readContents(fetchlist);
@@ -116,11 +115,14 @@ public class TestCrawlDbFilter {
/**
* Read contents of fetchlist.
- * @param fetchlist path to Generated fetchlist
+ *
+ * @param fetchlist
+ * path to Generated fetchlist
* @return Generated {@link URLCrawlDatum} objects
* @throws IOException
*/
- private ArrayList<URLCrawlDatum> readContents(Path fetchlist) throws IOException {
+ private ArrayList<URLCrawlDatum> readContents(Path fetchlist)
+ throws IOException {
// verify results
SequenceFile.Reader reader = new SequenceFile.Reader(fs, fetchlist, conf);
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java b/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
index 982252e0e..5422b792d 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
@@ -34,18 +34,15 @@ import org.junit.Before;
import org.junit.Test;
public class TestCrawlDbMerger {
- private static final Logger LOG = Logger.getLogger(CrawlDbMerger.class.getName());
-
+ private static final Logger LOG = Logger.getLogger(CrawlDbMerger.class
+ .getName());
+
String url10 = "http://example.com/";
String url11 = "http://example.com/foo";
String url20 = "http://example.com/";
String url21 = "http://example.com/bar";
- String[] urls_expected = new String[] {
- url10,
- url11,
- url21
- };
-
+ String[] urls_expected = new String[] { url10, url11, url21 };
+
TreeSet<String> init1 = new TreeSet<String>();
TreeSet<String> init2 = new TreeSet<String>();
HashMap<String, CrawlDatum> expected = new HashMap<String, CrawlDatum>();
@@ -54,7 +51,7 @@ public class TestCrawlDbMerger {
FileSystem fs;
Path testDir;
CrawlDbReader reader;
-
+
@Before
public void setUp() throws Exception {
init1.add(url10);
@@ -81,20 +78,21 @@ public class TestCrawlDbMerger {
expected.put(url21, cd2);
conf = NutchConfiguration.create();
fs = FileSystem.get(conf);
- testDir = new Path("test-crawldb-" +
- new java.util.Random().nextInt());
+ testDir = new Path("test-crawldb-" + new java.util.Random().nextInt());
fs.mkdirs(testDir);
}
-
+
@After
public void tearDown() {
try {
if (fs.exists(testDir))
fs.delete(testDir, true);
- } catch (Exception e) { }
+ } catch (Exception e) {
+ }
try {
reader.close();
- } catch (Exception e) { }
+ } catch (Exception e) {
+ }
}
@Test
@@ -106,7 +104,7 @@ public class TestCrawlDbMerger {
createCrawlDb(conf, fs, crawldb2, init2, cd2);
CrawlDbMerger merger = new CrawlDbMerger(conf);
LOG.fine("* merging crawldbs to " + output);
- merger.merge(output, new Path[]{crawldb1, crawldb2}, false, false);
+ merger.merge(output, new Path[] { crawldb1, crawldb2 }, false, false);
LOG.fine("* reading crawldb: " + output);
reader = new CrawlDbReader();
String crawlDb = output.toString();
@@ -127,11 +125,13 @@ public class TestCrawlDbMerger {
reader.close();
fs.delete(testDir, true);
}
-
- private void createCrawlDb(Configuration config, FileSystem fs, Path crawldb, TreeSet<String> init, CrawlDatum cd) throws Exception {
+
+ private void createCrawlDb(Configuration config, FileSystem fs, Path crawldb,
+ TreeSet<String> init, CrawlDatum cd) throws Exception {
LOG.fine("* creating crawldb: " + crawldb);
Path dir = new Path(crawldb, CrawlDb.CURRENT_NAME);
- MapFile.Writer writer = new MapFile.Writer(config, fs, new Path(dir, "part-00000").toString(), Text.class, CrawlDatum.class);
+ MapFile.Writer writer = new MapFile.Writer(config, fs, new Path(dir,
+ "part-00000").toString(), Text.class, CrawlDatum.class);
Iterator<String> it = init.iterator();
while (it.hasNext()) {
String key = it.next();
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java b/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
index d361090a8..bf951fdf0 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
@@ -55,26 +55,26 @@ import org.slf4j.LoggerFactory;
* <li>configuration properties</li>
* <li>(additional) CrawlDatums of status linked (stemming from inlinks)</li>
* </ul>
- * </li>
- * </ul>
+ * </li> </ul>
*/
public class TestCrawlDbStates {
- private static final Logger LOG = LoggerFactory.getLogger(TestCrawlDbStates.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(TestCrawlDbStates.class);
protected static final byte[][] fetchDbStatusPairs = {
- { -1, STATUS_DB_UNFETCHED },
- { STATUS_FETCH_SUCCESS, STATUS_DB_FETCHED },
- { STATUS_FETCH_GONE, STATUS_DB_GONE },
- { STATUS_FETCH_REDIR_TEMP, STATUS_DB_REDIR_TEMP },
- { STATUS_FETCH_REDIR_PERM, STATUS_DB_REDIR_PERM },
+ { -1, STATUS_DB_UNFETCHED }, { STATUS_FETCH_SUCCESS, STATUS_DB_FETCHED },
+ { STATUS_FETCH_GONE, STATUS_DB_GONE },
+ { STATUS_FETCH_REDIR_TEMP, STATUS_DB_REDIR_TEMP },
+ { STATUS_FETCH_REDIR_PERM, STATUS_DB_REDIR_PERM },
{ STATUS_FETCH_NOTMODIFIED, STATUS_DB_NOTMODIFIED },
- { STATUS_FETCH_RETRY, -1 }, // fetch_retry does not have a CrawlDb counter-part
- { -1, STATUS_DB_DUPLICATE },
- };
+ { STATUS_FETCH_RETRY, -1 }, // fetch_retry does not have a CrawlDb
+ // counter-part
+ { -1, STATUS_DB_DUPLICATE }, };
/** tested {@link FetchSchedule} implementations */
- protected String[] schedules = {"DefaultFetchSchedule", "AdaptiveFetchSchedule"};
+ protected String[] schedules = { "DefaultFetchSchedule",
+ "AdaptiveFetchSchedule" };
/** CrawlDatum as result of a link */
protected final CrawlDatum linked = new CrawlDatum(STATUS_LINKED,
@@ -101,7 +101,7 @@ public class TestCrawlDbStates {
int retryMax = conf.getInt("db.fetch.retry.max", 3);
for (String sched : schedules) {
LOG.info("Testing state transitions with " + sched);
- conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl."+sched);
+ conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
FetchSchedule schedule = FetchScheduleFactory
.getFetchSchedule(new JobConf(conf));
for (int i = 0; i < fetchDbStatusPairs.length; i++) {
@@ -138,8 +138,8 @@ public class TestCrawlDbStates {
}
String fromDbStatusName = (fromDbStatus == -1 ? "<not in CrawlDb>"
: getStatusName(fromDbStatus));
- String fetchStatusName = (fetchStatus == -1 ? "<only inlinks>" : CrawlDatum
- .getStatusName(fetchStatus));
+ String fetchStatusName = (fetchStatus == -1 ? "<only inlinks>"
+ : CrawlDatum.getStatusName(fetchStatus));
LOG.info(fromDbStatusName + " + " + fetchStatusName + " => "
+ getStatusName(toDbStatus));
List<CrawlDatum> values = new ArrayList<CrawlDatum>();
@@ -147,7 +147,8 @@ public class TestCrawlDbStates {
CrawlDatum fetch = null;
if (fetchStatus == -1) {
// nothing fetched, need at least one in-link
- if (l == 0) continue;
+ if (l == 0)
+ continue;
} else {
fetch = new CrawlDatum();
if (fromDb != null) {
@@ -183,7 +184,7 @@ public class TestCrawlDbStates {
}
}
}
- }
+ }
/**
* Test states after inject: inject must not modify the status of CrawlDatums
@@ -199,7 +200,7 @@ public class TestCrawlDbStates {
ScoringFilters scfilters = new ScoringFilters(conf);
for (String sched : schedules) {
LOG.info("Testing inject with " + sched);
- conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl."+sched);
+ conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
FetchSchedule schedule = FetchScheduleFactory
.getFetchSchedule(new JobConf(conf));
List<CrawlDatum> values = new ArrayList<CrawlDatum>();
@@ -219,8 +220,8 @@ public class TestCrawlDbStates {
.getStatusName(fromDbStatus)) + " + "
+ getStatusName(STATUS_INJECTED) + " => "
+ getStatusName(toDbStatus));
- CrawlDatum injected = new CrawlDatum(STATUS_INJECTED,
- conf.getInt("db.fetch.interval.default", 2592000), 0.1f);
+ CrawlDatum injected = new CrawlDatum(STATUS_INJECTED, conf.getInt(
+ "db.fetch.interval.default", 2592000), 0.1f);
schedule.initializeSchedule(CrawlDbUpdateUtil.dummyURL, injected);
try {
scfilters.injectedScore(CrawlDbUpdateUtil.dummyURL, injected);
@@ -236,10 +237,10 @@ public class TestCrawlDbStates {
byte status = res.get(0).getStatus();
if (status != toDbStatus) {
fail("Inject for "
- + (fromDbStatus == -1 ? "" : getStatusName(fromDbStatus) + " and ")
- + getStatusName(STATUS_INJECTED)
- + " results in " + getStatusName(status)
- + " (expected: " + getStatusName(toDbStatus) + ")");
+ + (fromDbStatus == -1 ? "" : getStatusName(fromDbStatus)
+ + " and ") + getStatusName(STATUS_INJECTED) + " results in "
+ + getStatusName(status) + " (expected: "
+ + getStatusName(toDbStatus) + ")");
}
values.clear();
}
@@ -258,8 +259,7 @@ public class TestCrawlDbStates {
* <li>modified time is set</li>
* <li>re-fetch is triggered after a certain time to force the fetched content
* to be in a recent segment (old segments are deleted, see comments in
- * {@link CrawlDbReducer#reduce(Text, Iterator, OutputCollector, Reporter)}
- * </li>
+ * {@link CrawlDbReducer#reduce(Text, Iterator, OutputCollector, Reporter)}</li>
* </ul>
*/
@Test
@@ -270,7 +270,7 @@ public class TestCrawlDbStates {
for (String sched : schedules) {
String desc = "test notmodified by signature comparison + " + sched;
LOG.info(desc);
- conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl."+sched);
+ conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchNotModified(conf);
if (!crawlUtil.run(20)) {
fail("failed: " + desc);
@@ -280,8 +280,9 @@ public class TestCrawlDbStates {
for (String sched : schedules) {
String desc = "test notmodified by HTTP 304 + " + sched;
LOG.info(desc);
- conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl."+sched);
- ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchNotModifiedHttp304(conf);
+ conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
+ ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchNotModifiedHttp304(
+ conf);
if (!crawlUtil.run(20)) {
fail("failed: " + desc);
}
@@ -294,7 +295,9 @@ public class TestCrawlDbStates {
protected long currFetchTime;
/** time the last fetch took place */
protected long lastFetchTime;
- /** time the document was fetched first (at all or after it has been changed) */
+ /**
+ * time the document was fetched first (at all or after it has been changed)
+ */
protected long firstFetchTime;
/** state in CrawlDb before the last fetch */
protected byte previousDbState;
@@ -304,18 +307,21 @@ public class TestCrawlDbStates {
private long maxFetchInterval;
private FetchSchedule schedule;
-
CrawlTestFetchNotModified(Configuration conf) {
super(conf);
- maxFetchInterval = conf.getLong("db.fetch.interval.max", 7776000); // default = 90 days
- maxFetchInterval += (24*60*60); // but take one day more to avoid false alarms
- maxFetchInterval *= 1000; // in milli-seconds
+ maxFetchInterval = conf.getLong("db.fetch.interval.max", 7776000); // default
+ // = 90
+ // days
+ maxFetchInterval += (24 * 60 * 60); // but take one day more to avoid
+ // false alarms
+ maxFetchInterval *= 1000; // in milli-seconds
schedule = FetchScheduleFactory.getFetchSchedule(new JobConf(conf));
}
@Override
protected boolean check(CrawlDatum result) {
- if (lastFetchTime > 0 && (currFetchTime - lastFetchTime) > maxFetchInterval) {
+ if (lastFetchTime > 0
+ && (currFetchTime - lastFetchTime) > maxFetchInterval) {
LOG.error("last effective fetch (HTTP 200, not HTTP 304), at "
+ new Date(lastFetchTime)
+ ", took place more than db.fetch.interval.max time, "
@@ -377,7 +383,6 @@ public class TestCrawlDbStates {
return false;
}
-
// test modified time
private boolean checkModifiedTime(CrawlDatum result, long modifiedTime) {
if (result.getModifiedTime() == 0) {
@@ -402,7 +407,7 @@ public class TestCrawlDbStates {
datum = super.fetch(datum, currentTime);
if (firstFetchTime == 0) {
firstFetchTime = currFetchTime;
- } else if ((currFetchTime - firstFetchTime) > (duration/2)) {
+ } else if ((currFetchTime - firstFetchTime) > (duration / 2)) {
// simulate a modification after "one year"
changeContent();
firstFetchTime = currFetchTime;
@@ -411,7 +416,8 @@ public class TestCrawlDbStates {
}
}
- protected class CrawlTestFetchNotModifiedHttp304 extends CrawlTestFetchNotModified {
+ protected class CrawlTestFetchNotModifiedHttp304 extends
+ CrawlTestFetchNotModified {
CrawlTestFetchNotModifiedHttp304(Configuration conf) {
super(conf);
@@ -424,13 +430,13 @@ public class TestCrawlDbStates {
previousDbState = datum.getStatus();
lastSignature = datum.getSignature();
int httpCode;
- /* document is "really" fetched (no HTTP 304)
- * - if last-modified time or signature are unset
- * (page has not been fetched before or fetch is forced)
- * - for test purposes, we simulate a modified after "one year"
+ /*
+ * document is "really" fetched (no HTTP 304) - if last-modified time or
+ * signature are unset (page has not been fetched before or fetch is
+ * forced) - for test purposes, we simulate a modified after "one year"
*/
if (datum.getModifiedTime() == 0 && datum.getSignature() == null
- || (currFetchTime - firstFetchTime) > (duration/2)) {
+ || (currFetchTime - firstFetchTime) > (duration / 2)) {
firstFetchTime = currFetchTime;
httpCode = 200;
datum.setStatus(STATUS_FETCH_SUCCESS);
@@ -450,8 +456,8 @@ public class TestCrawlDbStates {
/**
* NUTCH-1245: a fetch_gone should always result in a db_gone.
* <p>
- * Even in a long-running continuous crawl, when a gone page is
- * re-fetched several times over time.
+ * Even in a long-running continuous crawl, when a gone page is re-fetched
+ * several times over time.
* </p>
*/
@Test
@@ -476,8 +482,7 @@ public class TestCrawlDbStates {
LOG.info("NUTCH-1245 (misconfiguration): test with db.fetch.interval.default > (1.5 * db.fetch.interval.max)");
Configuration conf = CrawlDBTestUtil.createConfiguration();
int fetchIntervalMax = conf.getInt("db.fetch.interval.max", 0);
- conf.setInt("db.fetch.interval.default",
- 3 + (int) (fetchIntervalMax * 1.5));
+ conf.setInt("db.fetch.interval.default", 3 + (int) (fetchIntervalMax * 1.5));
ContinuousCrawlTestUtil crawlUtil = new ContinuousCrawlTestUtil(conf,
STATUS_FETCH_GONE, STATUS_DB_GONE);
if (!crawlUtil.run(0)) {
@@ -485,14 +490,12 @@ public class TestCrawlDbStates {
}
}
-
/**
- * Test whether signatures are reset for "content-less" states
- * (gone, redirect, etc.): otherwise, if this state is temporary
- * and the document appears again with the old content, it may
- * get marked as not_modified in CrawlDb just after the redirect
- * state. In this case we cannot expect content in segments.
- * Cf. NUTCH-1422: reset signature for redirects.
+ * Test whether signatures are reset for "content-less" states (gone,
+ * redirect, etc.): otherwise, if this state is temporary and the document
+ * appears again with the old content, it may get marked as not_modified in
+ * CrawlDb just after the redirect state. In this case we cannot expect
+ * content in segments. Cf. NUTCH-1422: reset signature for redirects.
*/
// TODO: can only test if solution is done in CrawlDbReducer
@Test
@@ -501,7 +504,7 @@ public class TestCrawlDbStates {
Configuration conf = CrawlDBTestUtil.createConfiguration();
for (String sched : schedules) {
LOG.info("Testing reset signature with " + sched);
- conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl."+sched);
+ conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
ContinuousCrawlTestUtil crawlUtil = new CrawlTestSignatureReset(conf);
if (!crawlUtil.run(20)) {
fail("failed: signature not reset");
@@ -511,8 +514,7 @@ public class TestCrawlDbStates {
private class CrawlTestSignatureReset extends ContinuousCrawlTestUtil {
- byte[][] noContentStates = {
- { STATUS_FETCH_GONE, STATUS_DB_GONE },
+ byte[][] noContentStates = { { STATUS_FETCH_GONE, STATUS_DB_GONE },
{ STATUS_FETCH_REDIR_TEMP, STATUS_DB_REDIR_TEMP },
{ STATUS_FETCH_REDIR_PERM, STATUS_DB_REDIR_PERM } };
@@ -528,15 +530,15 @@ public class TestCrawlDbStates {
datum = super.fetch(datum, currentTime);
counter++;
// flip-flopping between successful fetch and one of content-less states
- if (counter%2 == 1) {
+ if (counter % 2 == 1) {
fetchState = STATUS_FETCH_SUCCESS;
} else {
- fetchState = noContentStates[(counter%6)/2][0];
+ fetchState = noContentStates[(counter % 6) / 2][0];
}
LOG.info("Step " + counter + ": fetched with "
+ getStatusName(fetchState));
datum.setStatus(fetchState);
- return datum;
+ return datum;
}
@Override
@@ -560,6 +562,4 @@ public class TestCrawlDbStates {
}
-
}
-
diff --git a/src/test/org/apache/nutch/crawl/TestGenerator.java b/src/test/org/apache/nutch/crawl/TestGenerator.java
index 7c5b982db..d2f68ca9e 100644
--- a/src/test/org/apache/nutch/crawl/TestGenerator.java
+++ b/src/test/org/apache/nutch/crawl/TestGenerator.java
@@ -36,7 +36,7 @@ import org.junit.Test;
* Basic generator test. 1. Insert entries in crawldb 2. Generates entries to
* fetch 3. Verifies that number of generated urls match 4. Verifies that
* highest scoring urls are generated
- *
+ *
*/
public class TestGenerator {
@@ -71,7 +71,7 @@ public class TestGenerator {
/**
* Test that generator generates fetchlish ordered by score (desc).
- *
+ *
* @throws Exception
*/
@Test
@@ -82,8 +82,7 @@ public class TestGenerator {
ArrayList<URLCrawlDatum> list = new ArrayList<URLCrawlDatum>();
for (int i = 0; i <= 100; i++) {
- list.add(createURLCrawlDatum("http://aaa/" + pad(i),
- 1, i));
+ list.add(createURLCrawlDatum("http://aaa/" + pad(i), 1, i));
}
createCrawlDB(list);
@@ -94,7 +93,7 @@ public class TestGenerator {
CrawlDatum.GENERATE_DIR_NAME), "part-00000");
ArrayList<URLCrawlDatum> l = readContents(fetchlist);
-
+
// sort urls by score desc
Collections.sort(l, new ScoreComparator());
@@ -132,18 +131,16 @@ public class TestGenerator {
/**
* Test that generator obeys the property "generate.max.per.host".
- * @throws Exception
+ *
+ * @throws Exception
*/
@Test
- public void testGenerateHostLimit() throws Exception{
+ public void testGenerateHostLimit() throws Exception {
ArrayList<URLCrawlDatum> list = new ArrayList<URLCrawlDatum>();
- list.add(createURLCrawlDatum("http://www.example.com/index1.html",
- 1, 1));
- list.add(createURLCrawlDatum("http://www.example.com/index2.html",
- 1, 1));
- list.add(createURLCrawlDatum("http://www.example.com/index3.html",
- 1, 1));
+ list.add(createURLCrawlDatum("http://www.example.com/index1.html", 1, 1));
+ list.add(createURLCrawlDatum("http://www.example.com/index2.html", 1, 1));
+ list.add(createURLCrawlDatum("http://www.example.com/index3.html", 1, 1));
createCrawlDB(list);
@@ -190,10 +187,11 @@ public class TestGenerator {
/**
* Test that generator obeys the property "generator.max.count" and
* "generator.count.per.domain".
- * @throws Exception
+ *
+ * @throws Exception
*/
@Test
- public void testGenerateDomainLimit() throws Exception{
+ public void testGenerateDomainLimit() throws Exception {
ArrayList<URLCrawlDatum> list = new ArrayList<URLCrawlDatum>();
list.add(createURLCrawlDatum("http://a.example.com/index.html", 1, 1));
@@ -204,7 +202,8 @@ public class TestGenerator {
Configuration myConfiguration = new Configuration(conf);
myConfiguration.setInt(Generator.GENERATOR_MAX_COUNT, 2);
- myConfiguration.set(Generator.GENERATOR_COUNT_MODE, Generator.GENERATOR_COUNT_VALUE_DOMAIN);
+ myConfiguration.set(Generator.GENERATOR_COUNT_MODE,
+ Generator.GENERATOR_COUNT_VALUE_DOMAIN);
Path generatedSegment = generateFetchlist(Integer.MAX_VALUE,
myConfiguration, false);
@@ -219,7 +218,8 @@ public class TestGenerator {
myConfiguration = new Configuration(myConfiguration);
myConfiguration.setInt(Generator.GENERATOR_MAX_COUNT, 3);
- generatedSegment = generateFetchlist(Integer.MAX_VALUE, myConfiguration, false);
+ generatedSegment = generateFetchlist(Integer.MAX_VALUE, myConfiguration,
+ false);
fetchlistPath = new Path(new Path(generatedSegment,
CrawlDatum.GENERATE_DIR_NAME), "part-00000");
@@ -245,11 +245,12 @@ public class TestGenerator {
/**
* Test generator obeys the filter setting.
- * @throws Exception
- * @throws IOException
+ *
+ * @throws Exception
+ * @throws IOException
*/
@Test
- public void testFilter() throws IOException, Exception{
+ public void testFilter() throws IOException, Exception {
ArrayList<URLCrawlDatum> list = new ArrayList<URLCrawlDatum>();
@@ -267,7 +268,8 @@ public class TestGenerator {
Assert.assertNull("should be null (0 entries)", generatedSegment);
- generatedSegment = generateFetchlist(Integer.MAX_VALUE, myConfiguration, false);
+ generatedSegment = generateFetchlist(Integer.MAX_VALUE, myConfiguration,
+ false);
Path fetchlistPath = new Path(new Path(generatedSegment,
CrawlDatum.GENERATE_DIR_NAME), "part-00000");
@@ -279,14 +281,16 @@ public class TestGenerator {
}
-
/**
* Read contents of fetchlist.
- * @param fetchlist path to Generated fetchlist
+ *
+ * @param fetchlist
+ * path to Generated fetchlist
* @return Generated {@link URLCrawlDatum} objects
* @throws IOException
*/
- private ArrayList<URLCrawlDatum> readContents(Path fetchlist) throws IOException {
+ private ArrayList<URLCrawlDatum> readContents(Path fetchlist)
+ throws IOException {
// verify results
SequenceFile.Reader reader = new SequenceFile.Reader(fs, fetchlist, conf);
@@ -307,8 +311,11 @@ public class TestGenerator {
/**
* Generate Fetchlist.
- * @param numResults number of results to generate
- * @param config Configuration to use
+ *
+ * @param numResults
+ * number of results to generate
+ * @param config
+ * Configuration to use
* @return path to generated segment
* @throws IOException
*/
@@ -318,14 +325,16 @@ public class TestGenerator {
Generator g = new Generator(config);
Path[] generatedSegment = g.generate(dbDir, segmentsDir, -1, numResults,
Long.MAX_VALUE, filter, false);
- if (generatedSegment==null) return null;
+ if (generatedSegment == null)
+ return null;
return generatedSegment[0];
}
/**
* Creates CrawlDB.
- *
- * @param list database contents
+ *
+ * @param list
+ * database contents
* @throws IOException
* @throws Exception
*/
@@ -342,9 +351,13 @@ public class TestGenerator {
/**
* Constructs new {@link URLCrawlDatum} from submitted parameters.
- * @param url url to use
- * @param fetchInterval {@link CrawlDatum#setFetchInterval(float)}
- * @param score {@link CrawlDatum#setScore(float)}
+ *
+ * @param url
+ * url to use
+ * @param fetchInterval
+ * {@link CrawlDatum#setFetchInterval(float)}
+ * @param score
+ * {@link CrawlDatum#setScore(float)}
* @return Constructed object
*/
private URLCrawlDatum createURLCrawlDatum(final String url,
diff --git a/src/test/org/apache/nutch/crawl/TestInjector.java b/src/test/org/apache/nutch/crawl/TestInjector.java
index 71bc240e1..20e0ffab1 100644
--- a/src/test/org/apache/nutch/crawl/TestInjector.java
+++ b/src/test/org/apache/nutch/crawl/TestInjector.java
@@ -34,138 +34,143 @@ import org.junit.Before;
import org.junit.Test;
/**
- * Basic injector test:
- * 1. Creates a text file with urls
- * 2. Injects them into crawldb
- * 3. Reads crawldb entries and verifies contents
- * 4. Injects more urls into webdb
- * 5. Reads crawldb entries and verifies contents
+ * Basic injector test: 1. Creates a text file with urls 2. Injects them into
+ * crawldb 3. Reads crawldb entries and verifies contents 4. Injects more urls
+ * into webdb 5. Reads crawldb entries and verifies contents
*
*/
public class TestInjector {
private Configuration conf;
private FileSystem fs;
- final static Path testdir=new Path("build/test/inject-test");
+ final static Path testdir = new Path("build/test/inject-test");
Path crawldbPath;
Path urlPath;
-
+
@Before
public void setUp() throws Exception {
conf = CrawlDBTestUtil.createConfiguration();
- urlPath=new Path(testdir,"urls");
- crawldbPath=new Path(testdir,"crawldb");
- fs=FileSystem.get(conf);
- if (fs.exists(urlPath)) fs.delete(urlPath, false);
- if (fs.exists(crawldbPath)) fs.delete(crawldbPath, true);
+ urlPath = new Path(testdir, "urls");
+ crawldbPath = new Path(testdir, "crawldb");
+ fs = FileSystem.get(conf);
+ if (fs.exists(urlPath))
+ fs.delete(urlPath, false);
+ if (fs.exists(crawldbPath))
+ fs.delete(crawldbPath, true);
}
-
+
@After
- public void tearDown() throws IOException{
+ public void tearDown() throws IOException {
fs.delete(testdir, true);
}
@Test
public void testInject() throws IOException {
- ArrayList<String> urls=new ArrayList<String>();
- // We'll use a separate list for MD so we can still compare url with containsAll
- ArrayList<String> metadata=new ArrayList<String>();
- for(int i=0;i<100;i++) {
+ ArrayList<String> urls = new ArrayList<String>();
+ // We'll use a separate list for MD so we can still compare url with
+ // containsAll
+ ArrayList<String> metadata = new ArrayList<String>();
+ for (int i = 0; i < 100; i++) {
urls.add("http://zzz.com/" + i + ".html");
- metadata.add("\tnutch.score=2." + i + "\tnutch.fetchInterval=171717\tkey=value");
+ metadata.add("\tnutch.score=2." + i
+ + "\tnutch.fetchInterval=171717\tkey=value");
}
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls, metadata);
-
- Injector injector=new Injector(conf);
+
+ Injector injector = new Injector(conf);
injector.inject(crawldbPath, urlPath);
-
+
// verify results
- List<String>read=readCrawldb();
-
+ List<String> read = readCrawldb();
+
Collections.sort(read);
Collections.sort(urls);
Assert.assertEquals(urls.size(), read.size());
-
+
Assert.assertTrue(read.containsAll(urls));
Assert.assertTrue(urls.containsAll(read));
-
- //inject more urls
- ArrayList<String> urls2=new ArrayList<String>();
- for(int i=0;i<100;i++) {
+
+ // inject more urls
+ ArrayList<String> urls2 = new ArrayList<String>();
+ for (int i = 0; i < 100; i++) {
urls2.add("http://xxx.com/" + i + ".html");
- // We'll overwrite previously injected records but preserve their original MD
+ // We'll overwrite previously injected records but preserve their original
+ // MD
urls2.add("http://zzz.com/" + i + ".html");
}
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls2);
- injector=new Injector(conf);
+ injector = new Injector(conf);
conf.setBoolean("db.injector.update", true);
injector.inject(crawldbPath, urlPath);
urls.addAll(urls2);
-
+
// verify results
- read=readCrawldb();
+ read = readCrawldb();
Collections.sort(read);
Collections.sort(urls);
// We should have 100 less records because we've overwritten
Assert.assertEquals(urls.size() - 100, read.size());
-
+
Assert.assertTrue(read.containsAll(urls));
Assert.assertTrue(urls.containsAll(read));
-
+
// Check if we correctly preserved MD
Map<String, CrawlDatum> records = readCrawldbRecords();
-
+
// Iterate over the urls, we're looking for http://zzz.com/ prefixed URLs
// so we can check for MD and score and interval
Text writableKey = new Text("key");
Text writableValue = new Text("value");
for (String url : urls) {
- if (url.indexOf("http://zzz") == 0) {
+ if (url.indexOf("http://zzz") == 0) {
// Check for fetch interval
Assert.assertTrue(records.get(url).getFetchInterval() == 171717);
// Check for default score
Assert.assertTrue(records.get(url).getScore() != 1.0);
// Check for MD key=value
- Assert.assertEquals(writableValue, records.get(url).getMetaData().get(writableKey));
+ Assert.assertEquals(writableValue,
+ records.get(url).getMetaData().get(writableKey));
}
}
}
-
- private List<String> readCrawldb() throws IOException{
- Path dbfile=new Path(crawldbPath,CrawlDb.CURRENT_NAME + "/part-00000/data");
+
+ private List<String> readCrawldb() throws IOException {
+ Path dbfile = new Path(crawldbPath, CrawlDb.CURRENT_NAME
+ + "/part-00000/data");
System.out.println("reading:" + dbfile);
@SuppressWarnings("resource")
- SequenceFile.Reader reader=new SequenceFile.Reader(fs, dbfile, conf);
- ArrayList<String> read=new ArrayList<String>();
-
- READ:
- do {
- Text key=new Text();
- CrawlDatum value=new CrawlDatum();
- if(!reader.next(key, value)) break READ;
+ SequenceFile.Reader reader = new SequenceFile.Reader(fs, dbfile, conf);
+ ArrayList<String> read = new ArrayList<String>();
+
+ READ: do {
+ Text key = new Text();
+ CrawlDatum value = new CrawlDatum();
+ if (!reader.next(key, value))
+ break READ;
read.add(key.toString());
- } while(true);
+ } while (true);
return read;
}
-
- private HashMap<String,CrawlDatum> readCrawldbRecords() throws IOException{
- Path dbfile=new Path(crawldbPath,CrawlDb.CURRENT_NAME + "/part-00000/data");
+
+ private HashMap<String, CrawlDatum> readCrawldbRecords() throws IOException {
+ Path dbfile = new Path(crawldbPath, CrawlDb.CURRENT_NAME
+ + "/part-00000/data");
System.out.println("reading:" + dbfile);
@SuppressWarnings("resource")
- SequenceFile.Reader reader=new SequenceFile.Reader(fs, dbfile, conf);
- HashMap<String,CrawlDatum> read=new HashMap<String,CrawlDatum>();
-
- READ:
- do {
- Text key=new Text();
- CrawlDatum value=new CrawlDatum();
- if(!reader.next(key, value)) break READ;
+ SequenceFile.Reader reader = new SequenceFile.Reader(fs, dbfile, conf);
+ HashMap<String, CrawlDatum> read = new HashMap<String, CrawlDatum>();
+
+ READ: do {
+ Text key = new Text();
+ CrawlDatum value = new CrawlDatum();
+ if (!reader.next(key, value))
+ break READ;
read.put(key.toString(), value);
- } while(true);
+ } while (true);
return read;
}
diff --git a/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java b/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
index 88d8cd6c1..79e96ac95 100644
--- a/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
+++ b/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
@@ -35,41 +35,28 @@ import org.junit.Before;
import org.junit.Test;
public class TestLinkDbMerger {
- private static final Logger LOG = Logger.getLogger(TestLinkDbMerger.class.getName());
-
+ private static final Logger LOG = Logger.getLogger(TestLinkDbMerger.class
+ .getName());
+
String url10 = "http://example.com/foo";
- String[] urls10 = new String[] {
- "http://example.com/100",
- "http://example.com/101"
- };
+ String[] urls10 = new String[] { "http://example.com/100",
+ "http://example.com/101" };
String url11 = "http://example.com/";
- String[] urls11 = new String[] {
- "http://example.com/110",
- "http://example.com/111"
- };
-
+ String[] urls11 = new String[] { "http://example.com/110",
+ "http://example.com/111" };
+
String url20 = "http://example.com/";
- String[] urls20 = new String[] {
- "http://foo.com/200",
- "http://foo.com/201"
- };
+ String[] urls20 = new String[] { "http://foo.com/200", "http://foo.com/201" };
String url21 = "http://example.com/bar";
- String[] urls21 = new String[] {
- "http://foo.com/210",
- "http://foo.com/211"
- };
-
+ String[] urls21 = new String[] { "http://foo.com/210", "http://foo.com/211" };
+
String[] urls10_expected = urls10;
- String[] urls11_expected = new String[] {
- urls11[0],
- urls11[1],
- urls20[0],
- urls20[1]
- };
+ String[] urls11_expected = new String[] { urls11[0], urls11[1], urls20[0],
+ urls20[1] };
String[] urls20_expected = urls11_expected;
String[] urls21_expected = urls21;
-
+
TreeMap<String, String[]> init1 = new TreeMap<String, String[]>();
TreeMap<String, String[]> init2 = new TreeMap<String, String[]>();
HashMap<String, String[]> expected = new HashMap<String, String[]>();
@@ -77,7 +64,7 @@ public class TestLinkDbMerger {
Path testDir;
FileSystem fs;
LinkDbReader reader;
-
+
@Before
public void setUp() throws Exception {
init1.put(url10, urls10);
@@ -90,20 +77,22 @@ public class TestLinkDbMerger {
expected.put(url21, urls21_expected);
conf = NutchConfiguration.create();
fs = FileSystem.get(conf);
- testDir = new Path("build/test/test-linkdb-" +
- new java.util.Random().nextInt());
+ testDir = new Path("build/test/test-linkdb-"
+ + new java.util.Random().nextInt());
fs.mkdirs(testDir);
}
-
+
@After
public void tearDown() {
try {
if (fs.exists(testDir))
fs.delete(testDir, true);
- } catch (Exception e) { }
+ } catch (Exception e) {
+ }
try {
reader.close();
- } catch (Exception e) { }
+ } catch (Exception e) {
+ }
}
@Test
@@ -118,7 +107,7 @@ public class TestLinkDbMerger {
createLinkDb(conf, fs, linkdb2, init2);
LinkDbMerger merger = new LinkDbMerger(conf);
LOG.fine("* merging linkdbs to " + output);
- merger.merge(output, new Path[]{linkdb1, linkdb2}, false, false);
+ merger.merge(output, new Path[] { linkdb1, linkdb2 }, false, false);
LOG.fine("* reading linkdb: " + output);
reader = new LinkDbReader(conf, output);
Iterator<String> it = expected.keySet().iterator();
@@ -132,7 +121,7 @@ public class TestLinkDbMerger {
ArrayList<String> links = new ArrayList<String>();
Iterator<?> it2 = inlinks.iterator();
while (it2.hasNext()) {
- Inlink in = (Inlink)it2.next();
+ Inlink in = (Inlink) it2.next();
links.add(in.getFromUrl());
}
for (int i = 0; i < vals.length; i++) {
@@ -143,11 +132,13 @@ public class TestLinkDbMerger {
reader.close();
fs.delete(testDir, true);
}
-
- private void createLinkDb(Configuration config, FileSystem fs, Path linkdb, TreeMap<String, String[]> init) throws Exception {
+
+ private void createLinkDb(Configuration config, FileSystem fs, Path linkdb,
+ TreeMap<String, String[]> init) throws Exception {
LOG.fine("* creating linkdb: " + linkdb);
Path dir = new Path(linkdb, LinkDb.CURRENT_NAME);
- MapFile.Writer writer = new MapFile.Writer(config, fs, new Path(dir, "part-00000").toString(), Text.class, Inlinks.class);
+ MapFile.Writer writer = new MapFile.Writer(config, fs, new Path(dir,
+ "part-00000").toString(), Text.class, Inlinks.class);
Iterator<String> it = init.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
diff --git a/src/test/org/apache/nutch/crawl/TestSignatureFactory.java b/src/test/org/apache/nutch/crawl/TestSignatureFactory.java
index 97df27168..db82d7acb 100644
--- a/src/test/org/apache/nutch/crawl/TestSignatureFactory.java
+++ b/src/test/org/apache/nutch/crawl/TestSignatureFactory.java
@@ -25,9 +25,9 @@ public class TestSignatureFactory {
@Test
public void testGetSignature() {
- Configuration conf=NutchConfiguration.create();
- Signature signature1=SignatureFactory.getSignature(conf);
- Signature signature2=SignatureFactory.getSignature(conf);
+ Configuration conf = NutchConfiguration.create();
+ Signature signature1 = SignatureFactory.getSignature(conf);
+ Signature signature2 = SignatureFactory.getSignature(conf);
Assert.assertNotNull(signature1);
Assert.assertNotNull(signature2);
Assert.assertEquals(signature1, signature2);
diff --git a/src/test/org/apache/nutch/fetcher/TestFetcher.java b/src/test/org/apache/nutch/fetcher/TestFetcher.java
index f3e8f524c..66aec5aa0 100644
--- a/src/test/org/apache/nutch/fetcher/TestFetcher.java
+++ b/src/test/org/apache/nutch/fetcher/TestFetcher.java
@@ -39,17 +39,13 @@ import org.junit.Test;
import org.mortbay.jetty.Server;
/**
- * Basic fetcher test
- * 1. generate seedlist
- * 2. inject
- * 3. generate
- * 3. fetch
- * 4. Verify contents
- *
+ * Basic fetcher test 1. generate seedlist 2. inject 3. generate 3. fetch 4.
+ * Verify contents
+ *
*/
public class TestFetcher {
- final static Path testdir=new Path("build/test/fetch-test");
+ final static Path testdir = new Path("build/test/fetch-test");
Configuration conf;
FileSystem fs;
Path crawldbPath;
@@ -58,112 +54,118 @@ public class TestFetcher {
Server server;
@Before
- public void setUp() throws Exception{
- conf=CrawlDBTestUtil.createConfiguration();
- fs=FileSystem.get(conf);
+ public void setUp() throws Exception {
+ conf = CrawlDBTestUtil.createConfiguration();
+ fs = FileSystem.get(conf);
fs.delete(testdir, true);
- urlPath=new Path(testdir,"urls");
- crawldbPath=new Path(testdir,"crawldb");
- segmentsPath=new Path(testdir,"segments");
- server=CrawlDBTestUtil.getServer(conf.getInt("content.server.port",50000), "build/test/data/fetch-test-site");
+ urlPath = new Path(testdir, "urls");
+ crawldbPath = new Path(testdir, "crawldb");
+ segmentsPath = new Path(testdir, "segments");
+ server = CrawlDBTestUtil.getServer(
+ conf.getInt("content.server.port", 50000),
+ "build/test/data/fetch-test-site");
server.start();
}
@After
- public void tearDown() throws Exception{
+ public void tearDown() throws Exception {
server.stop();
fs.delete(testdir, true);
}
-
+
@Test
public void testFetch() throws IOException {
-
- //generate seedlist
- ArrayList<String> urls=new ArrayList<String>();
-
- addUrl(urls,"index.html");
- addUrl(urls,"pagea.html");
- addUrl(urls,"pageb.html");
- addUrl(urls,"dup_of_pagea.html");
- addUrl(urls,"nested_spider_trap.html");
- addUrl(urls,"exception.html");
-
+
+ // generate seedlist
+ ArrayList<String> urls = new ArrayList<String>();
+
+ addUrl(urls, "index.html");
+ addUrl(urls, "pagea.html");
+ addUrl(urls, "pageb.html");
+ addUrl(urls, "dup_of_pagea.html");
+ addUrl(urls, "nested_spider_trap.html");
+ addUrl(urls, "exception.html");
+
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
-
- //inject
- Injector injector=new Injector(conf);
+
+ // inject
+ Injector injector = new Injector(conf);
injector.inject(crawldbPath, urlPath);
- //generate
- Generator g=new Generator(conf);
+ // generate
+ Generator g = new Generator(conf);
Path[] generatedSegment = g.generate(crawldbPath, segmentsPath, 1,
Long.MAX_VALUE, Long.MAX_VALUE, false, false);
- long time=System.currentTimeMillis();
- //fetch
- Fetcher fetcher=new Fetcher(conf);
+ long time = System.currentTimeMillis();
+ // fetch
+ Fetcher fetcher = new Fetcher(conf);
// Set fetcher.parse to true
conf.setBoolean("fetcher.parse", true);
fetcher.fetch(generatedSegment[0], 1);
- time=System.currentTimeMillis()-time;
-
- //verify politeness, time taken should be more than (num_of_pages +1)*delay
- int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
+ time = System.currentTimeMillis() - time;
+
+ // verify politeness, time taken should be more than (num_of_pages +1)*delay
+ int minimumTime = (int) ((urls.size() + 1) * 1000 * conf.getFloat(
+ "fetcher.server.delay", 5));
Assert.assertTrue(time > minimumTime);
-
- //verify content
- Path content=new Path(new Path(generatedSegment[0], Content.DIR_NAME),"part-00000/data");
+
+ // verify content
+ Path content = new Path(new Path(generatedSegment[0], Content.DIR_NAME),
+ "part-00000/data");
@SuppressWarnings("resource")
- SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
-
- ArrayList<String> handledurls=new ArrayList<String>();
-
- READ_CONTENT:
- do {
- Text key=new Text();
- Content value=new Content();
- if(!reader.next(key, value)) break READ_CONTENT;
- String contentString=new String(value.getContent());
- if(contentString.indexOf("Nutch fetcher test page")!=-1) {
+ SequenceFile.Reader reader = new SequenceFile.Reader(fs, content, conf);
+
+ ArrayList<String> handledurls = new ArrayList<String>();
+
+ READ_CONTENT: do {
+ Text key = new Text();
+ Content value = new Content();
+ if (!reader.next(key, value))
+ break READ_CONTENT;
+ String contentString = new String(value.getContent());
+ if (contentString.indexOf("Nutch fetcher test page") != -1) {
handledurls.add(key.toString());
}
- } while(true);
+ } while (true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
- //verify that enough pages were handled
+ // verify that enough pages were handled
Assert.assertEquals(urls.size(), handledurls.size());
- //verify that correct pages were handled
+ // verify that correct pages were handled
Assert.assertTrue(handledurls.containsAll(urls));
Assert.assertTrue(urls.containsAll(handledurls));
-
+
handledurls.clear();
- //verify parse data
- Path parseData = new Path(new Path(generatedSegment[0], ParseData.DIR_NAME),"part-00000/data");
+ // verify parse data
+ Path parseData = new Path(
+ new Path(generatedSegment[0], ParseData.DIR_NAME), "part-00000/data");
reader = new SequenceFile.Reader(fs, parseData, conf);
-
- READ_PARSE_DATA:
- do {
+
+ READ_PARSE_DATA: do {
Text key = new Text();
ParseData value = new ParseData();
- if(!reader.next(key, value)) break READ_PARSE_DATA;
- // make sure they all contain "nutch.segment.name" and "nutch.content.digest"
+ if (!reader.next(key, value))
+ break READ_PARSE_DATA;
+ // make sure they all contain "nutch.segment.name" and
+ // "nutch.content.digest"
// keys in parse metadata
Metadata contentMeta = value.getContentMeta();
- if (contentMeta.get(Nutch.SEGMENT_NAME_KEY) != null
- && contentMeta.get(Nutch.SIGNATURE_KEY) != null) {
+ if (contentMeta.get(Nutch.SEGMENT_NAME_KEY) != null
+ && contentMeta.get(Nutch.SIGNATURE_KEY) != null) {
handledurls.add(key.toString());
}
- } while(true);
-
+ } while (true);
+
Collections.sort(handledurls);
Assert.assertEquals(urls.size(), handledurls.size());
@@ -173,9 +175,10 @@ public class TestFetcher {
}
private void addUrl(ArrayList<String> urls, String page) {
- urls.add("http://127.0.0.1:" + server.getConnectors()[0].getPort() + "/" + page);
+ urls.add("http://127.0.0.1:" + server.getConnectors()[0].getPort() + "/"
+ + page);
}
-
+
@Test
public void testAgentNameCheck() {
diff --git a/src/test/org/apache/nutch/indexer/TestIndexingFilters.java b/src/test/org/apache/nutch/indexer/TestIndexingFilters.java
index 02ed9181a..4d5849fdc 100644
--- a/src/test/org/apache/nutch/indexer/TestIndexingFilters.java
+++ b/src/test/org/apache/nutch/indexer/TestIndexingFilters.java
@@ -33,13 +33,14 @@ public class TestIndexingFilters {
/**
* Test behaviour when defined filter does not exist.
+ *
* @throws IndexingException
*/
@Test
public void testNonExistingIndexingFilter() throws IndexingException {
Configuration conf = NutchConfiguration.create();
- conf.addResource("nutch-default.xml");
- conf.addResource("crawl-tests.xml");
+ conf.addResource("nutch-default.xml");
+ conf.addResource("crawl-tests.xml");
String class1 = "NonExistingFilter";
String class2 = "org.apache.nutch.indexer.basic.BasicIndexingFilter";
@@ -47,34 +48,35 @@ public class TestIndexingFilters {
IndexingFilters filters = new IndexingFilters(conf);
filters.filter(new NutchDocument(), new ParseImpl("text", new ParseData(
- new ParseStatus(), "title", new Outlink[0], new Metadata())), new Text(
- "http://www.example.com/"), new CrawlDatum(), new Inlinks());
+ new ParseStatus(), "title", new Outlink[0], new Metadata())), new Text(
+ "http://www.example.com/"), new CrawlDatum(), new Inlinks());
}
/**
* Test behaviour when NutchDOcument is null
*/
@Test
- public void testNutchDocumentNullIndexingFilter() throws IndexingException{
+ public void testNutchDocumentNullIndexingFilter() throws IndexingException {
Configuration conf = NutchConfiguration.create();
conf.addResource("nutch-default.xml");
conf.addResource("crawl-tests.xml");
IndexingFilters filters = new IndexingFilters(conf);
- NutchDocument doc = filters.filter(null, new ParseImpl("text", new ParseData(
- new ParseStatus(), "title", new Outlink[0], new Metadata())), new Text(
- "http://www.example.com/"), new CrawlDatum(), new Inlinks());
-
+ NutchDocument doc = filters.filter(null, new ParseImpl("text",
+ new ParseData(new ParseStatus(), "title", new Outlink[0],
+ new Metadata())), new Text("http://www.example.com/"),
+ new CrawlDatum(), new Inlinks());
+
Assert.assertNull(doc);
}
/**
* Test behaviour when reset the index filter order will not take effect
- *
+ *
* @throws IndexingException
*/
@Test
- public void testFilterCacheIndexingFilter() throws IndexingException{
+ public void testFilterCacheIndexingFilter() throws IndexingException {
Configuration conf = NutchConfiguration.create();
conf.addResource("nutch-default.xml");
conf.addResource("crawl-tests.xml");
@@ -83,24 +85,26 @@ public class TestIndexingFilters {
conf.set(IndexingFilters.INDEXINGFILTER_ORDER, class1);
IndexingFilters filters1 = new IndexingFilters(conf);
- NutchDocument fdoc1 = filters1.filter(new NutchDocument(),new ParseImpl("text",new ParseData(
- new ParseStatus(),"title",new Outlink[0],new Metadata())),new Text("http://www.example.com/"),
- new CrawlDatum(),new Inlinks());
+ NutchDocument fdoc1 = filters1.filter(new NutchDocument(), new ParseImpl(
+ "text", new ParseData(new ParseStatus(), "title", new Outlink[0],
+ new Metadata())), new Text("http://www.example.com/"),
+ new CrawlDatum(), new Inlinks());
// add another index filter
String class2 = "org.apache.nutch.indexer.metadata.MetadataIndexer";
// set content metadata
Metadata md = new Metadata();
- md.add("example","data");
+ md.add("example", "data");
// set content metadata property defined in MetadataIndexer
- conf.set("index.content.md","example");
+ conf.set("index.content.md", "example");
// add MetadataIndxer filter
conf.set(IndexingFilters.INDEXINGFILTER_ORDER, class1 + " " + class2);
IndexingFilters filters2 = new IndexingFilters(conf);
- NutchDocument fdoc2 = filters2.filter(new NutchDocument(),new ParseImpl("text",new ParseData(
- new ParseStatus(),"title",new Outlink[0],md)),new Text("http://www.example.com/"),
- new CrawlDatum(),new Inlinks());
- Assert.assertEquals(fdoc1.getFieldNames().size(),fdoc2.getFieldNames().size());
+ NutchDocument fdoc2 = filters2.filter(new NutchDocument(), new ParseImpl(
+ "text", new ParseData(new ParseStatus(), "title", new Outlink[0], md)),
+ new Text("http://www.example.com/"), new CrawlDatum(), new Inlinks());
+ Assert.assertEquals(fdoc1.getFieldNames().size(), fdoc2.getFieldNames()
+ .size());
}
}
diff --git a/src/test/org/apache/nutch/metadata/TestMetadata.java b/src/test/org/apache/nutch/metadata/TestMetadata.java
index 120b3e883..f3a320d48 100644
--- a/src/test/org/apache/nutch/metadata/TestMetadata.java
+++ b/src/test/org/apache/nutch/metadata/TestMetadata.java
@@ -33,7 +33,6 @@ public class TestMetadata {
private static final String CONTENTTYPE = "contenttype";
-
/**
* Test to ensure that only non-null values get written when the
* {@link Metadata} object is written using a Writeable.
@@ -280,4 +279,3 @@ public class TestMetadata {
}
}
-
diff --git a/src/test/org/apache/nutch/metadata/TestSpellCheckedMetadata.java b/src/test/org/apache/nutch/metadata/TestSpellCheckedMetadata.java
index 7b2ceeecb..ae73ae1b8 100644
--- a/src/test/org/apache/nutch/metadata/TestSpellCheckedMetadata.java
+++ b/src/test/org/apache/nutch/metadata/TestSpellCheckedMetadata.java
@@ -29,7 +29,7 @@ import org.junit.Test;
/**
* JUnit based tests of class
* {@link org.apache.nutch.metadata.SpellCheckedMetadata}.
- *
+ *
* @author Chris Mattmann
* @author J&eacute;r&ocirc;me Charron
*/
@@ -40,20 +40,20 @@ public class TestSpellCheckedMetadata {
/** Test for the <code>getNormalizedName(String)</code> method. */
@Test
public void testGetNormalizedName() {
- Assert.assertEquals("Content-Type", SpellCheckedMetadata
- .getNormalizedName("Content-Type"));
- Assert.assertEquals("Content-Type", SpellCheckedMetadata
- .getNormalizedName("ContentType"));
- Assert.assertEquals("Content-Type", SpellCheckedMetadata
- .getNormalizedName("Content-type"));
- Assert.assertEquals("Content-Type", SpellCheckedMetadata
- .getNormalizedName("contenttype"));
- Assert.assertEquals("Content-Type", SpellCheckedMetadata
- .getNormalizedName("contentype"));
- Assert.assertEquals("Content-Type", SpellCheckedMetadata
- .getNormalizedName("contntype"));
+ Assert.assertEquals("Content-Type",
+ SpellCheckedMetadata.getNormalizedName("Content-Type"));
+ Assert.assertEquals("Content-Type",
+ SpellCheckedMetadata.getNormalizedName("ContentType"));
+ Assert.assertEquals("Content-Type",
+ SpellCheckedMetadata.getNormalizedName("Content-type"));
+ Assert.assertEquals("Content-Type",
+ SpellCheckedMetadata.getNormalizedName("contenttype"));
+ Assert.assertEquals("Content-Type",
+ SpellCheckedMetadata.getNormalizedName("contentype"));
+ Assert.assertEquals("Content-Type",
+ SpellCheckedMetadata.getNormalizedName("contntype"));
}
-
+
/** Test for the <code>add(String, String)</code> method. */
@Test
public void testAdd() {
@@ -253,8 +253,8 @@ public class TestSpellCheckedMetadata {
}
/**
- * IO Test method, usable only when you plan to do changes in metadata
- * to measure relative performance impact.
+ * IO Test method, usable only when you plan to do changes in metadata to
+ * measure relative performance impact.
*/
@Test
public final void testHandlingSpeed() {
diff --git a/src/test/org/apache/nutch/net/TestURLFilters.java b/src/test/org/apache/nutch/net/TestURLFilters.java
index 3cb556ef5..c43941a94 100644
--- a/src/test/org/apache/nutch/net/TestURLFilters.java
+++ b/src/test/org/apache/nutch/net/TestURLFilters.java
@@ -24,6 +24,7 @@ public class TestURLFilters {
/**
* Testcase for NUTCH-325.
+ *
* @throws URLFilterException
*/
@Test
diff --git a/src/test/org/apache/nutch/net/TestURLNormalizers.java b/src/test/org/apache/nutch/net/TestURLNormalizers.java
index bd2e73361..71275b283 100644
--- a/src/test/org/apache/nutch/net/TestURLNormalizers.java
+++ b/src/test/org/apache/nutch/net/TestURLNormalizers.java
@@ -31,41 +31,53 @@ public class TestURLNormalizers {
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);
-
+
+ URLNormalizers normalizers = new URLNormalizers(conf,
+ URLNormalizers.SCOPE_DEFAULT);
+
Assert.assertNotNull(normalizers);
try {
- normalizers.normalize("http://www.example.com/", URLNormalizers.SCOPE_DEFAULT);
+ normalizers.normalize("http://www.example.com/",
+ URLNormalizers.SCOPE_DEFAULT);
} catch (MalformedURLException mue) {
Assert.fail(mue.toString());
}
// NUTCH-1011 - Get rid of superfluous slashes
try {
- String normalizedSlashes = normalizers.normalize("http://www.example.com//path/to//somewhere.html", URLNormalizers.SCOPE_DEFAULT);
- Assert.assertEquals(normalizedSlashes, "http://www.example.com/path/to/somewhere.html");
+ String normalizedSlashes = normalizers.normalize(
+ "http://www.example.com//path/to//somewhere.html",
+ URLNormalizers.SCOPE_DEFAULT);
+ Assert.assertEquals(normalizedSlashes,
+ "http://www.example.com/path/to/somewhere.html");
} catch (MalformedURLException mue) {
Assert.fail(mue.toString());
}
-
+
// HostNormalizer NUTCH-1319
try {
- String normalizedHost = normalizers.normalize("http://www.example.org//path/to//somewhere.html", URLNormalizers.SCOPE_DEFAULT);
- Assert.assertEquals(normalizedHost, "http://example.org/path/to/somewhere.html");
+ String normalizedHost = normalizers.normalize(
+ "http://www.example.org//path/to//somewhere.html",
+ URLNormalizers.SCOPE_DEFAULT);
+ Assert.assertEquals(normalizedHost,
+ "http://example.org/path/to/somewhere.html");
} catch (MalformedURLException mue) {
Assert.fail(mue.toString());
}
-
+
// check the order
int pos1 = -1, pos2 = -1;
- URLNormalizer[] impls = normalizers.getURLNormalizers(URLNormalizers.SCOPE_DEFAULT);
+ 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 (impls[i].getClass().getName().equals(clazz1))
+ pos1 = i;
+ if (impls[i].getClass().getName().equals(clazz2))
+ pos2 = i;
}
if (pos1 != -1 && pos2 != -1) {
- Assert.assertTrue("RegexURLNormalizer before BasicURLNormalizer", pos1 < pos2);
+ Assert.assertTrue("RegexURLNormalizer before BasicURLNormalizer",
+ pos1 < pos2);
}
}
}
diff --git a/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java b/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java
index ede0ce804..1f2c833e8 100644
--- a/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java
+++ b/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
package org.apache.nutch.parse;
import org.apache.nutch.parse.Outlink;
@@ -34,54 +34,66 @@ import org.junit.Test;
public class TestOutlinkExtractor {
private static Configuration conf = NutchConfiguration.create();
-
+
@Test
public void testGetNoOutlinks() {
- Outlink[] outlinks = null;
-
+ Outlink[] outlinks = null;
+
outlinks = OutlinkExtractor.getOutlinks(null, conf);
Assert.assertNotNull(outlinks);
Assert.assertEquals(0, outlinks.length);
-
+
outlinks = OutlinkExtractor.getOutlinks("", conf);
Assert.assertNotNull(outlinks);
Assert.assertEquals(0, outlinks.length);
}
-
+
@Test
public void testGetOutlinksHttp() {
- 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", conf);
-
+ 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",
+ conf);
+
Assert.assertTrue("Url not found!", outlinks.length == 3);
- Assert.assertEquals("Wrong URL", "http://www.nutch.org/index.html", outlinks[0].getToUrl());
- Assert.assertEquals("Wrong URL", "http://www.google.de", outlinks[1].getToUrl());
- Assert.assertEquals("Wrong URL", "http://www.sybit.com/solutions/portals.html", outlinks[2].getToUrl());
+ Assert.assertEquals("Wrong URL", "http://www.nutch.org/index.html",
+ outlinks[0].getToUrl());
+ Assert.assertEquals("Wrong URL", "http://www.google.de",
+ outlinks[1].getToUrl());
+ Assert.assertEquals("Wrong URL",
+ "http://www.sybit.com/solutions/portals.html", outlinks[2].getToUrl());
}
-
+
@Test
public void testGetOutlinksHttp2() {
- 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", conf);
-
+ 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", conf);
+
Assert.assertTrue("Url not found!", outlinks.length == 3);
- Assert.assertEquals("Wrong URL", "http://www.nutch.org/index.html", outlinks[0].getToUrl());
- Assert.assertEquals("Wrong URL", "http://www.google.de", outlinks[1].getToUrl());
- Assert.assertEquals("Wrong URL", "http://www.sybit.com/solutions/portals.html", outlinks[2].getToUrl());
+ Assert.assertEquals("Wrong URL", "http://www.nutch.org/index.html",
+ outlinks[0].getToUrl());
+ Assert.assertEquals("Wrong URL", "http://www.google.de",
+ outlinks[1].getToUrl());
+ Assert.assertEquals("Wrong URL",
+ "http://www.sybit.com/solutions/portals.html", outlinks[2].getToUrl());
}
-
+
@Test
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", conf);
-
- Assert.assertTrue("Url not found!", outlinks.length >1);
- Assert.assertEquals("Wrong URL", "ftp://www.nutch.org", outlinks[0].getToUrl());
- Assert.assertEquals("Wrong URL", "ftp://www.google.de", outlinks[1].getToUrl());
+ "Test with ftp://www.nutch.org is it found? "
+ + "What about www.google.com at ftp://www.google.de", conf);
+
+ Assert.assertTrue("Url not found!", outlinks.length > 1);
+ Assert.assertEquals("Wrong URL", "ftp://www.nutch.org",
+ outlinks[0].getToUrl());
+ Assert.assertEquals("Wrong URL", "ftp://www.google.de",
+ outlinks[1].getToUrl());
}
}
diff --git a/src/test/org/apache/nutch/parse/TestParseData.java b/src/test/org/apache/nutch/parse/TestParseData.java
index 9507306bf..550a260a4 100644
--- a/src/test/org/apache/nutch/parse/TestParseData.java
+++ b/src/test/org/apache/nutch/parse/TestParseData.java
@@ -31,30 +31,27 @@ public class TestParseData {
String title = "The Foo Page";
- Outlink[] outlinks = new Outlink[] {
- new Outlink("http://foo.com/", "Foo"),
- new Outlink("http://bar.com/", "Bar")
- };
+ Outlink[] outlinks = new Outlink[] { new Outlink("http://foo.com/", "Foo"),
+ new Outlink("http://bar.com/", "Bar") };
Metadata metaData = new Metadata();
metaData.add("Language", "en/us");
metaData.add("Charset", "UTF-8");
- ParseData r = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);
-
+ ParseData r = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks,
+ metaData);
+
WritableTestUtils.testWritable(r, null);
}
@Test
public void testMaxOutlinks() throws Exception {
Outlink[] outlinks = new Outlink[128];
- for (int i=0; i<outlinks.length; i++) {
+ for (int i = 0; i < outlinks.length; i++) {
outlinks[i] = new Outlink("http://outlink.com/" + i, "Outlink" + i);
}
ParseData original = new ParseData(ParseStatus.STATUS_SUCCESS,
- "Max Outlinks Title",
- outlinks,
- new Metadata());
+ "Max Outlinks Title", outlinks, new Metadata());
ParseData data = (ParseData) WritableTestUtils.writeRead(original, null);
Assert.assertEquals(outlinks.length, data.getOutlinks().length);
}
diff --git a/src/test/org/apache/nutch/parse/TestParseText.java b/src/test/org/apache/nutch/parse/TestParseText.java
index edacb64c1..241b293d8 100644
--- a/src/test/org/apache/nutch/parse/TestParseText.java
+++ b/src/test/org/apache/nutch/parse/TestParseText.java
@@ -22,7 +22,7 @@ import org.junit.Test;
/** Unit tests for ParseText. */
-public class TestParseText {
+public class TestParseText {
@Test
public void testParseText() throws Exception {
diff --git a/src/test/org/apache/nutch/parse/TestParserFactory.java b/src/test/org/apache/nutch/parse/TestParserFactory.java
index 7b6697302..00c524e2f 100644
--- a/src/test/org/apache/nutch/parse/TestParserFactory.java
+++ b/src/test/org/apache/nutch/parse/TestParserFactory.java
@@ -27,25 +27,25 @@ import org.junit.Test;
/**
* Unit test for new parse plugin selection.
- *
+ *
* @author Sebastien Le Callonnec
* @version 1.0
*/
public class TestParserFactory {
-
+
private Configuration conf;
private ParserFactory parserFactory;
/** Inits the Test Case with the test parse-plugin file */
@Before
public void setUp() throws Exception {
- conf = NutchConfiguration.create();
- conf.set("plugin.includes", ".*");
- conf.set("parse.plugin.file",
- "org/apache/nutch/parse/parse-plugin-test.xml");
- parserFactory = new ParserFactory(conf);
+ conf = NutchConfiguration.create();
+ conf.set("plugin.includes", ".*");
+ conf.set("parse.plugin.file",
+ "org/apache/nutch/parse/parse-plugin-test.xml");
+ parserFactory = new ParserFactory(conf);
}
-
+
/** Unit test for <code>getExtensions(String)</code> method. */
@Test
public void testGetExtensions() throws Exception {
@@ -56,48 +56,50 @@ public class TestParserFactory {
ext = parserFactory.getExtensions("foo/bar").get(0);
Assert.assertEquals("parse-tika", ext.getDescriptor().getPluginId());
}
-
+
/** Unit test to check <code>getParsers</code> method */
@Test
public void testGetParsers() throws Exception {
- Parser [] parsers = parserFactory.getParsers("text/html", "http://foo.com");
+ Parser[] parsers = parserFactory.getParsers("text/html", "http://foo.com");
Assert.assertNotNull(parsers);
Assert.assertEquals(1, parsers.length);
- Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser",
- parsers[0].getClass().getName());
+ Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser", parsers[0]
+ .getClass().getName());
parsers = parserFactory.getParsers("text/html; charset=ISO-8859-1",
- "http://foo.com");
+ "http://foo.com");
Assert.assertNotNull(parsers);
Assert.assertEquals(1, parsers.length);
- Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser",
- parsers[0].getClass().getName());
-
+ Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser", parsers[0]
+ .getClass().getName());
+
parsers = parserFactory.getParsers("application/x-javascript",
- "http://foo.com");
+ "http://foo.com");
Assert.assertNotNull(parsers);
Assert.assertEquals(1, parsers.length);
- Assert.assertEquals("org.apache.nutch.parse.js.JSParseFilter",
- parsers[0].getClass().getName());
-
+ Assert.assertEquals("org.apache.nutch.parse.js.JSParseFilter", parsers[0]
+ .getClass().getName());
+
parsers = parserFactory.getParsers("text/plain", "http://foo.com");
Assert.assertNotNull(parsers);
Assert.assertEquals(1, parsers.length);
- Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser",
- parsers[0].getClass().getName());
-
+ Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser", parsers[0]
+ .getClass().getName());
+
Parser parser1 = parserFactory.getParsers("text/plain", "http://foo.com")[0];
Parser parser2 = parserFactory.getParsers("*", "http://foo.com")[0];
-
- Assert.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");
+
+ Assert.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");
Assert.assertNotNull(parsers);
- Assert.assertEquals(1,parsers.length);
- Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser",
- parsers[0].getClass().getName());
+ Assert.assertEquals(1, parsers.length);
+ Assert.assertEquals("org.apache.nutch.parse.tika.TikaParser", parsers[0]
+ .getClass().getName());
}
-
+
}
diff --git a/src/test/org/apache/nutch/plugin/HelloWorldExtension.java b/src/test/org/apache/nutch/plugin/HelloWorldExtension.java
index 6f4b57e5b..fa564c474 100644
--- a/src/test/org/apache/nutch/plugin/HelloWorldExtension.java
+++ b/src/test/org/apache/nutch/plugin/HelloWorldExtension.java
@@ -24,8 +24,11 @@ package org.apache.nutch.plugin;
*/
public class HelloWorldExtension implements ITestExtension {
- /* (non-Javadoc)
- * @see org.apache.nutch.plugin.ITestExtension#testGetExtension(java.lang.String)
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.apache.nutch.plugin.ITestExtension#testGetExtension(java.lang.String)
*/
public String testGetExtension(String hello) {
return hello + " World";
diff --git a/src/test/org/apache/nutch/plugin/ITestExtension.java b/src/test/org/apache/nutch/plugin/ITestExtension.java
index 451c70617..b6aa81dc0 100644
--- a/src/test/org/apache/nutch/plugin/ITestExtension.java
+++ b/src/test/org/apache/nutch/plugin/ITestExtension.java
@@ -15,11 +15,12 @@
* limitations under the License.
*/
package org.apache.nutch.plugin;
+
/**
* A Simple Test Extension Interface.
*
* @author joa23
- *
+ *
*/
public interface ITestExtension {
public String testGetExtension(String hello);
diff --git a/src/test/org/apache/nutch/plugin/SimpleTestPlugin.java b/src/test/org/apache/nutch/plugin/SimpleTestPlugin.java
index 8eca94546..080142d99 100644
--- a/src/test/org/apache/nutch/plugin/SimpleTestPlugin.java
+++ b/src/test/org/apache/nutch/plugin/SimpleTestPlugin.java
@@ -28,8 +28,8 @@ import org.apache.hadoop.conf.Configuration;
public class SimpleTestPlugin extends Plugin {
/**
- * @param pDescriptor
- * @param conf
+ * @param pDescriptor
+ * @param conf
*/
public SimpleTestPlugin(PluginDescriptor pDescriptor, Configuration conf) {
@@ -55,4 +55,3 @@ public class SimpleTestPlugin extends Plugin {
}
}
-
diff --git a/src/test/org/apache/nutch/plugin/TestPluginSystem.java b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
index e73af5513..a5f4e32b5 100644
--- a/src/test/org/apache/nutch/plugin/TestPluginSystem.java
+++ b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
@@ -42,15 +42,15 @@ public class TestPluginSystem {
private int fPluginCount;
private LinkedList<File> fFolders = new LinkedList<File>();
- private Configuration conf ;
+ private Configuration conf;
private PluginRepository repository;
@Before
public void setUp() throws Exception {
this.conf = NutchConfiguration.create();
conf.set("plugin.includes", ".*");
- // String string = this.conf.get("plugin.includes", "");
- // conf.set("plugin.includes", string + "|Dummy*");
+ // String string = this.conf.get("plugin.includes", "");
+ // conf.set("plugin.includes", string + "|Dummy*");
fPluginCount = 5;
createDummyPlugins(fPluginCount);
this.repository = PluginRepository.get(conf);
@@ -86,8 +86,7 @@ public class TestPluginSystem {
*/
@Test
public void testLoadPlugins() {
- PluginDescriptor[] descriptors = repository
- .getPluginDescriptors();
+ PluginDescriptor[] descriptors = repository.getPluginDescriptors();
int k = descriptors.length;
Assert.assertTrue(fPluginCount <= k);
for (int i = 0; i < descriptors.length; i++) {
@@ -123,11 +122,10 @@ public class TestPluginSystem {
@Test
public void testGetExtensionAndAttributes() {
String xpId = " sdsdsd";
- ExtensionPoint extensionPoint =repository
- .getExtensionPoint(xpId);
+ ExtensionPoint extensionPoint = repository.getExtensionPoint(xpId);
Assert.assertEquals(extensionPoint, null);
- Extension[] extension1 = repository
- .getExtensionPoint(getGetExtensionId()).getExtensions();
+ Extension[] extension1 = repository.getExtensionPoint(getGetExtensionId())
+ .getExtensions();
Assert.assertEquals(extension1.length, fPluginCount);
for (int i = 0; i < extension1.length; i++) {
Extension extension2 = extension1[i];
@@ -141,8 +139,8 @@ public class TestPluginSystem {
*/
@Test
public void testGetExtensionInstances() throws PluginRuntimeException {
- Extension[] extensions = repository
- .getExtensionPoint(getGetExtensionId()).getExtensions();
+ Extension[] extensions = repository.getExtensionPoint(getGetExtensionId())
+ .getExtensions();
Assert.assertEquals(extensions.length, fPluginCount);
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
@@ -161,8 +159,7 @@ public class TestPluginSystem {
*/
@Test
public void testGetClassLoader() {
- PluginDescriptor[] descriptors = repository
- .getPluginDescriptors();
+ PluginDescriptor[] descriptors = repository.getPluginDescriptors();
for (int i = 0; i < descriptors.length; i++) {
PluginDescriptor descriptor = descriptors[i];
Assert.assertNotNull(descriptor.getClassLoader());
@@ -174,8 +171,7 @@ public class TestPluginSystem {
*/
@Test
public void testGetResources() throws IOException {
- PluginDescriptor[] descriptors = repository
- .getPluginDescriptors();
+ PluginDescriptor[] descriptors = repository.getPluginDescriptors();
for (int i = 0; i < descriptors.length; i++) {
PluginDescriptor descriptor = descriptors[i];
if (!descriptor.getPluginId().startsWith("getPluginFolder()")) {
@@ -183,8 +179,7 @@ public class TestPluginSystem {
}
String value = descriptor.getResourceString("key", Locale.UK);
Assert.assertEquals("value", value);
- value = descriptor.getResourceString("key",
- Locale.TRADITIONAL_CHINESE);
+ value = descriptor.getResourceString("key", Locale.TRADITIONAL_CHINESE);
Assert.assertEquals("value", value);
}
@@ -199,7 +194,8 @@ public class TestPluginSystem {
Assert.fail("no plugin directory setuped..");
String name = strings[0];
- return new PluginManifestParser(conf, this.repository).getPluginFolder(name).toString();
+ return new PluginManifestParser(conf, this.repository)
+ .getPluginFolder(name).toString();
}
/**
@@ -213,8 +209,7 @@ public class TestPluginSystem {
File folder = new File(string);
folder.mkdir();
for (int i = 0; i < pCount; i++) {
- String pluginFolder = string + File.separator + "DummyPlugin"
- + i;
+ String pluginFolder = string + File.separator + "DummyPlugin" + i;
File file = new File(pluginFolder);
file.mkdir();
fFolders.add(file);
@@ -265,9 +260,8 @@ public class TestPluginSystem {
*/
private void createPluginManifest(int i, String pFolderPath)
throws IOException {
- FileWriter out = new FileWriter(pFolderPath + File.separator
- + "plugin.xml");
- String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ FileWriter out = new FileWriter(pFolderPath + File.separator + "plugin.xml");
+ String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<!--this is just a simple plugin for testing issues.-->"
+ "<plugin id=\"org.apache.nutch.plugin."
+ i
diff --git a/src/test/org/apache/nutch/protocol/TestContent.java b/src/test/org/apache/nutch/protocol/TestContent.java
index acf07eb62..1475cdaad 100644
--- a/src/test/org/apache/nutch/protocol/TestContent.java
+++ b/src/test/org/apache/nutch/protocol/TestContent.java
@@ -58,52 +58,36 @@ public class TestContent {
Content c = null;
Metadata p = new Metadata();
- c = new Content("http://www.foo.com/",
- "http://www.foo.com/",
- "".getBytes("UTF8"),
- "text/html; charset=UTF-8", p, conf);
+ c = new Content("http://www.foo.com/", "http://www.foo.com/",
+ "".getBytes("UTF8"), "text/html; charset=UTF-8", p, conf);
Assert.assertEquals("text/html", c.getContentType());
- c = new Content("http://www.foo.com/foo.html",
- "http://www.foo.com/",
- "".getBytes("UTF8"),
- "", p, conf);
+ c = new Content("http://www.foo.com/foo.html", "http://www.foo.com/",
+ "".getBytes("UTF8"), "", p, conf);
Assert.assertEquals("text/html", c.getContentType());
- c = new Content("http://www.foo.com/foo.html",
- "http://www.foo.com/",
- "".getBytes("UTF8"),
- null, p, conf);
+ c = new Content("http://www.foo.com/foo.html", "http://www.foo.com/",
+ "".getBytes("UTF8"), null, p, conf);
Assert.assertEquals("text/html", c.getContentType());
- c = new Content("http://www.foo.com/",
- "http://www.foo.com/",
- "<html></html>".getBytes("UTF8"),
- "", p, conf);
+ c = new Content("http://www.foo.com/", "http://www.foo.com/",
+ "<html></html>".getBytes("UTF8"), "", p, conf);
Assert.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, conf);
+ c = new Content("http://www.foo.com/foo.html", "http://www.foo.com/",
+ "<html></html>".getBytes("UTF8"), "text/plain", p, conf);
Assert.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, conf);
+ c = new Content("http://www.foo.com/foo.png", "http://www.foo.com/",
+ "<html></html>".getBytes("UTF8"), "text/plain", p, conf);
Assert.assertEquals("text/html", c.getContentType());
- c = new Content("http://www.foo.com/",
- "http://www.foo.com/",
- "".getBytes("UTF8"),
- "", p, conf);
+ c = new Content("http://www.foo.com/", "http://www.foo.com/",
+ "".getBytes("UTF8"), "", p, conf);
Assert.assertEquals(MimeTypes.OCTET_STREAM, c.getContentType());
- c = new Content("http://www.foo.com/",
- "http://www.foo.com/",
- "".getBytes("UTF8"),
- null, p, conf);
+ c = new Content("http://www.foo.com/", "http://www.foo.com/",
+ "".getBytes("UTF8"), null, p, conf);
Assert.assertNotNull(c.getContentType());
}
diff --git a/src/test/org/apache/nutch/protocol/TestProtocolFactory.java b/src/test/org/apache/nutch/protocol/TestProtocolFactory.java
index ae9d8b15a..394c30391 100644
--- a/src/test/org/apache/nutch/protocol/TestProtocolFactory.java
+++ b/src/test/org/apache/nutch/protocol/TestProtocolFactory.java
@@ -27,58 +27,59 @@ public class TestProtocolFactory {
Configuration conf;
ProtocolFactory factory;
-
+
@Before
public void setUp() throws Exception {
conf = NutchConfiguration.create();
conf.set("plugin.includes", ".*");
conf.set("http.agent.name", "test-bot");
- factory=new ProtocolFactory(conf);
+ factory = new ProtocolFactory(conf);
}
@Test
- public void testGetProtocol(){
+ public void testGetProtocol() {
- //non existing protocol
+ // non existing protocol
try {
factory.getProtocol("xyzxyz://somehost");
Assert.fail("Must throw ProtocolNotFound");
} catch (ProtocolNotFound e) {
- //all is ok
- } catch (Exception ex){
+ // all is ok
+ } catch (Exception ex) {
Assert.fail("Must not throw any other exception");
}
-
- Protocol httpProtocol=null;
-
- //existing protocol
+
+ Protocol httpProtocol = null;
+
+ // existing protocol
try {
- httpProtocol=factory.getProtocol("http://somehost");
+ httpProtocol = factory.getProtocol("http://somehost");
Assert.assertNotNull(httpProtocol);
- } catch (Exception ex){
+ } catch (Exception ex) {
Assert.fail("Must not throw any other exception");
}
- //cache key
- Object protocol = ObjectCache.get(conf).getObject(Protocol.X_POINT_ID + "http");
+ // cache key
+ Object protocol = ObjectCache.get(conf).getObject(
+ Protocol.X_POINT_ID + "http");
Assert.assertNotNull(protocol);
Assert.assertEquals(httpProtocol, protocol);
-
- //test same object instance
+
+ // test same object instance
try {
- Assert.assertTrue(httpProtocol==factory.getProtocol("http://somehost"));
+ Assert.assertTrue(httpProtocol == factory.getProtocol("http://somehost"));
} catch (ProtocolNotFound e) {
Assert.fail("Must not throw any exception");
}
}
-
+
@Test
- public void testContains(){
+ public void testContains() {
Assert.assertTrue(factory.contains("http", "http"));
Assert.assertTrue(factory.contains("http", "http,ftp"));
Assert.assertTrue(factory.contains("http", " http , ftp"));
Assert.assertTrue(factory.contains("smb", "ftp,smb,http"));
Assert.assertFalse(factory.contains("smb", "smbb"));
}
-
+
}
diff --git a/src/test/org/apache/nutch/segment/TestSegmentMerger.java b/src/test/org/apache/nutch/segment/TestSegmentMerger.java
index d99bc006f..351b97cb6 100644
--- a/src/test/org/apache/nutch/segment/TestSegmentMerger.java
+++ b/src/test/org/apache/nutch/segment/TestSegmentMerger.java
@@ -40,12 +40,13 @@ public class TestSegmentMerger {
Path seg2;
Path out;
int countSeg1, countSeg2;
-
+
@Before
public void setUp() throws Exception {
conf = NutchConfiguration.create();
fs = FileSystem.get(conf);
- testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-" + System.currentTimeMillis());
+ testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-"
+ + System.currentTimeMillis());
seg1 = new Path(testDir, "seg1");
seg2 = new Path(testDir, "seg2");
out = new Path(testDir, "out");
@@ -55,12 +56,13 @@ public class TestSegmentMerger {
DecimalFormat df = new DecimalFormat("0000000");
Text k = new Text();
Path ptPath = new Path(new Path(seg1, ParseText.DIR_NAME), "part-00000");
- MapFile.Writer w = new MapFile.Writer(conf, fs, ptPath.toString(), Text.class, ParseText.class);
+ MapFile.Writer w = new MapFile.Writer(conf, fs, ptPath.toString(),
+ Text.class, ParseText.class);
long curSize = 0;
countSeg1 = 0;
FileStatus fileStatus = fs.getFileStatus(ptPath);
long blkSize = fileStatus.getBlockSize();
-
+
while (curSize < blkSize * 2) {
k.set("seg1-" + df.format(countSeg1));
w.append(k, new ParseText("seg1 text " + countSeg1));
@@ -71,7 +73,8 @@ public class TestSegmentMerger {
System.err.println(" - done: " + countSeg1 + " records.");
System.err.println("Creating large segment 2...");
ptPath = new Path(new Path(seg2, ParseText.DIR_NAME), "part-00000");
- w = new MapFile.Writer(conf, fs, ptPath.toString(), Text.class, ParseText.class);
+ w = new MapFile.Writer(conf, fs, ptPath.toString(), Text.class,
+ ParseText.class);
curSize = 0;
countSeg2 = 0;
while (curSize < blkSize * 2) {
@@ -83,16 +86,16 @@ public class TestSegmentMerger {
w.close();
System.err.println(" - done: " + countSeg2 + " records.");
}
-
+
@After
public void tearDown() throws Exception {
fs.delete(testDir, true);
}
-
+
@Test
public void testLargeMerge() throws Exception {
SegmentMerger merger = new SegmentMerger(conf);
- merger.merge(out, new Path[]{seg1, seg2}, false, false, -1);
+ merger.merge(out, new Path[] { seg1, seg2 }, false, false, -1);
// verify output
FileStatus[] stats = fs.listStatus(out);
// there should be just one path
@@ -100,7 +103,8 @@ public class TestSegmentMerger {
Path outSeg = stats[0].getPath();
Text k = new Text();
ParseText v = new ParseText();
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(outSeg, ParseText.DIR_NAME), conf);
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(
+ outSeg, ParseText.DIR_NAME), conf);
int cnt1 = 0, cnt2 = 0;
for (MapFile.Reader r : readers) {
while (r.next(k, v)) {
diff --git a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
index 97e90d6d6..c8ab8ba31 100644
--- a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
+++ b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
@@ -35,19 +35,19 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * New SegmentMerger unit test focusing on several crappy issues with the segment
- * merger. The general problem is disappearing records and incorrect CrawlDatum
- * status values. This unit test performs random sequences of segment merging where
- * we're looking for an expected status.
- * A second test is able to randomly inject redirects in segment, likely causing
- * the segment merger to fail resulting in a bad merged segment.
- *
+ * New SegmentMerger unit test focusing on several crappy issues with the
+ * segment merger. The general problem is disappearing records and incorrect
+ * CrawlDatum status values. This unit test performs random sequences of segment
+ * merging where we're looking for an expected status. A second test is able to
+ * randomly inject redirects in segment, likely causing the segment merger to
+ * fail resulting in a bad merged segment.
+ *
* See also:
- *
+ *
* https://issues.apache.org/jira/browse/NUTCH-1113
* https://issues.apache.org/jira/browse/NUTCH-1616
* https://issues.apache.org/jira/browse/NUTCH-1520
- *
+ *
* Cheers!
*/
public class TestSegmentMergerCrawlDatums {
@@ -57,14 +57,14 @@ public class TestSegmentMergerCrawlDatums {
private static final Logger LOG = LoggerFactory
.getLogger(TestSegmentMergerCrawlDatums.class);
-
+
@Before
public void setUp() throws Exception {
conf = NutchConfiguration.create();
fs = FileSystem.get(conf);
rnd = new Random();
}
-
+
/**
*
*/
@@ -75,15 +75,16 @@ public class TestSegmentMergerCrawlDatums {
new Byte(executeSequence(CrawlDatum.STATUS_FETCH_GONE,
CrawlDatum.STATUS_FETCH_SUCCESS, 256, false)));
}
-
+
/**
*
*/
@Test
public void testMostlyRedirects() throws Exception {
// Our test directory
- Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-" + System.currentTimeMillis());
-
+ Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-"
+ + System.currentTimeMillis());
+
Path segment1 = new Path(testDir, "20140110114943");
Path segment2 = new Path(testDir, "20140110114832");
Path segment3 = new Path(testDir, "20140110114558");
@@ -92,7 +93,7 @@ public class TestSegmentMergerCrawlDatums {
Path segment6 = new Path(testDir, "20140110114507");
Path segment7 = new Path(testDir, "20140110114903");
Path segment8 = new Path(testDir, "20140110114724");
-
+
createSegment(segment1, CrawlDatum.STATUS_FETCH_SUCCESS, true);
createSegment(segment2, CrawlDatum.STATUS_FETCH_SUCCESS, true);
createSegment(segment3, CrawlDatum.STATUS_FETCH_SUCCESS, true);
@@ -101,32 +102,33 @@ public class TestSegmentMergerCrawlDatums {
createSegment(segment6, CrawlDatum.STATUS_FETCH_SUCCESS, false);
createSegment(segment7, CrawlDatum.STATUS_FETCH_SUCCESS, true);
createSegment(segment8, CrawlDatum.STATUS_FETCH_SUCCESS, true);
-
+
// Merge the segments and get status
- Path mergedSegment = merge(testDir, new Path[]{segment1, segment2, segment3, segment4, segment5, segment6, segment7, segment8});
+ Path mergedSegment = merge(testDir, new Path[] { segment1, segment2,
+ segment3, segment4, segment5, segment6, segment7, segment8 });
Byte status = new Byte(status = checkMergedSegment(testDir, mergedSegment));
-
+
Assert.assertEquals(new Byte(CrawlDatum.STATUS_FETCH_SUCCESS), status);
}
-
+
/**
*
*/
@Test
public void testRandomizedSequences() throws Exception {
for (int i = 0; i < rnd.nextInt(16) + 16; i++) {
- byte expectedStatus = (byte)(rnd.nextInt(6) + 0x21);
+ byte expectedStatus = (byte) (rnd.nextInt(6) + 0x21);
while (expectedStatus == CrawlDatum.STATUS_FETCH_RETRY
|| expectedStatus == CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
// fetch_retry and fetch_notmodified never remain in a merged segment
expectedStatus = (byte) (rnd.nextInt(6) + 0x21);
}
- byte randomStatus = (byte)(rnd.nextInt(6) + 0x21);
+ byte randomStatus = (byte) (rnd.nextInt(6) + 0x21);
int rounds = rnd.nextInt(16) + 32;
boolean withRedirects = rnd.nextBoolean();
-
- byte resultStatus = executeSequence(randomStatus, expectedStatus,
- rounds, withRedirects);
+
+ byte resultStatus = executeSequence(randomStatus, expectedStatus, rounds,
+ withRedirects);
Assert.assertEquals(
"Expected status = " + CrawlDatum.getStatusName(expectedStatus)
+ ", but got " + CrawlDatum.getStatusName(resultStatus)
@@ -135,196 +137,225 @@ public class TestSegmentMergerCrawlDatums {
resultStatus);
}
}
-
+
/**
*
*/
@Test
public void testRandomTestSequenceWithRedirects() throws Exception {
- Assert.assertEquals(new Byte(CrawlDatum.STATUS_FETCH_SUCCESS), new Byte(executeSequence(CrawlDatum.STATUS_FETCH_GONE, CrawlDatum.STATUS_FETCH_SUCCESS, 128, true)));
+ Assert.assertEquals(
+ new Byte(CrawlDatum.STATUS_FETCH_SUCCESS),
+ new Byte(executeSequence(CrawlDatum.STATUS_FETCH_GONE,
+ CrawlDatum.STATUS_FETCH_SUCCESS, 128, true)));
}
-
+
/**
* Check a fixed sequence!
*/
@Test
public void testFixedSequence() throws Exception {
// Our test directory
- Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-" + System.currentTimeMillis());
-
+ Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-"
+ + System.currentTimeMillis());
+
Path segment1 = new Path(testDir, "00001");
Path segment2 = new Path(testDir, "00002");
Path segment3 = new Path(testDir, "00003");
-
+
createSegment(segment1, CrawlDatum.STATUS_FETCH_GONE, false);
createSegment(segment2, CrawlDatum.STATUS_FETCH_GONE, true);
createSegment(segment3, CrawlDatum.STATUS_FETCH_SUCCESS, false);
-
+
// Merge the segments and get status
- Path mergedSegment = merge(testDir, new Path[]{segment1, segment2, segment3});
+ Path mergedSegment = merge(testDir, new Path[] { segment1, segment2,
+ segment3 });
Byte status = new Byte(status = checkMergedSegment(testDir, mergedSegment));
-
+
Assert.assertEquals(new Byte(CrawlDatum.STATUS_FETCH_SUCCESS), status);
}
-
+
/**
* Check a fixed sequence!
*/
@Test
public void testRedirFetchInOneSegment() throws Exception {
// Our test directory
- Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-" + System.currentTimeMillis());
-
+ Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-"
+ + System.currentTimeMillis());
+
Path segment = new Path(testDir, "00001");
-
+
createSegment(segment, CrawlDatum.STATUS_FETCH_SUCCESS, true, true);
-
+
// Merge the segments and get status
- Path mergedSegment = merge(testDir, new Path[]{segment});
+ Path mergedSegment = merge(testDir, new Path[] { segment });
Byte status = new Byte(status = checkMergedSegment(testDir, mergedSegment));
-
+
Assert.assertEquals(new Byte(CrawlDatum.STATUS_FETCH_SUCCESS), status);
}
-
+
/**
* Check a fixed sequence!
*/
@Test
public void testEndsWithRedirect() throws Exception {
// Our test directory
- Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-" + System.currentTimeMillis());
-
+ Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-"
+ + System.currentTimeMillis());
+
Path segment1 = new Path(testDir, "00001");
Path segment2 = new Path(testDir, "00002");
-
+
createSegment(segment1, CrawlDatum.STATUS_FETCH_SUCCESS, false);
createSegment(segment2, CrawlDatum.STATUS_FETCH_SUCCESS, true);
-
+
// Merge the segments and get status
- Path mergedSegment = merge(testDir, new Path[]{segment1, segment2});
+ Path mergedSegment = merge(testDir, new Path[] { segment1, segment2 });
Byte status = new Byte(status = checkMergedSegment(testDir, mergedSegment));
-
+
Assert.assertEquals(new Byte(CrawlDatum.STATUS_FETCH_SUCCESS), status);
}
-
+
/**
- * Execute a sequence of creating segments, merging them and checking the final output
- *
- * @param status to start with
- * @param status to end with
- * @param number of rounds
- * @param whether redirects are injected randomly
+ * Execute a sequence of creating segments, merging them and checking the
+ * final output
+ *
+ * @param status
+ * to start with
+ * @param status
+ * to end with
+ * @param number
+ * of rounds
+ * @param whether
+ * redirects are injected randomly
* @return the CrawlDatum status
*/
- protected byte executeSequence(byte firstStatus, byte lastStatus, int rounds, boolean redirect) throws Exception {
+ protected byte executeSequence(byte firstStatus, byte lastStatus, int rounds,
+ boolean redirect) throws Exception {
// Our test directory
- Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-" + System.currentTimeMillis());
-
+ Path testDir = new Path(conf.get("hadoop.tmp.dir"), "merge-"
+ + System.currentTimeMillis());
+
// Format for the segments
DecimalFormat df = new DecimalFormat("0000000");
-
+
// Create our segment paths
Path[] segmentPaths = new Path[rounds];
for (int i = 0; i < rounds; i++) {
String segmentName = df.format(i);
segmentPaths[i] = new Path(testDir, segmentName);
}
-
+
// Create the first segment according to the specified status
createSegment(segmentPaths[0], firstStatus, false);
-
- // Create N segments with random status and optionally with randomized redirect injection
+
+ // Create N segments with random status and optionally with randomized
+ // redirect injection
for (int i = 1; i < rounds - 1; i++) {
// Status, 6 possibilities incremented with 33 hex
- byte status = (byte)(rnd.nextInt(6) + 0x21);
-
+ byte status = (byte) (rnd.nextInt(6) + 0x21);
+
// Whether this is going to be a redirect
boolean addRedirect = redirect ? rnd.nextBoolean() : false;
// If it's a redirect we add a datum resulting from a fetch at random,
// if not: always add a fetch datum to avoid empty segments
boolean addFetch = addRedirect ? rnd.nextBoolean() : true;
-
+
createSegment(segmentPaths[i], status, addFetch, addRedirect);
}
// Create the last segment according to the specified status
// (additionally, add a redirect at random)
- createSegment(segmentPaths[rounds - 1], lastStatus, true, redirect ? rnd.nextBoolean() : false);
-
+ createSegment(segmentPaths[rounds - 1], lastStatus, true,
+ redirect ? rnd.nextBoolean() : false);
+
// Merge the segments!
Path mergedSegment = merge(testDir, segmentPaths);
-
+
// Check the status of the final record and return it
return checkMergedSegment(testDir, mergedSegment);
}
-
+
/**
* Checks the merged segment and removes the stuff again.
- *
- * @param the test directory
- * @param the merged segment
+ *
+ * @param the
+ * test directory
+ * @param the
+ * merged segment
* @return the final status
*/
- protected byte checkMergedSegment(Path testDir, Path mergedSegment) throws Exception {
+ protected byte checkMergedSegment(Path testDir, Path mergedSegment)
+ throws Exception {
// Get a MapFile reader for the <Text,CrawlDatum> pairs
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(mergedSegment, CrawlDatum.FETCH_DIR_NAME), conf);
-
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(
+ mergedSegment, CrawlDatum.FETCH_DIR_NAME), conf);
+
Text key = new Text();
CrawlDatum value = new CrawlDatum();
byte finalStatus = 0x0;
-
+
for (MapFile.Reader reader : readers) {
while (reader.next(key, value)) {
- LOG.info("Reading status for: " + key.toString() + " > " + CrawlDatum.getStatusName(value.getStatus()));
-
+ LOG.info("Reading status for: " + key.toString() + " > "
+ + CrawlDatum.getStatusName(value.getStatus()));
+
// Only consider fetch status
- if (CrawlDatum.hasFetchStatus(value) && key.toString().equals("http://nutch.apache.org/")) {
+ if (CrawlDatum.hasFetchStatus(value)
+ && key.toString().equals("http://nutch.apache.org/")) {
finalStatus = value.getStatus();
}
}
-
+
// Close the reader again
reader.close();
}
// Remove the test directory again
fs.delete(testDir, true);
-
- LOG.info("Final fetch status for: http://nutch.apache.org/ > " + CrawlDatum.getStatusName(finalStatus));
+
+ LOG.info("Final fetch status for: http://nutch.apache.org/ > "
+ + CrawlDatum.getStatusName(finalStatus));
// Return the final status
return finalStatus;
}
-
+
/**
* Merge some segments!
- *
- * @param the test directory
- * @param the segments to merge
+ *
+ * @param the
+ * test directory
+ * @param the
+ * segments to merge
* @return Path to the merged segment
*/
protected Path merge(Path testDir, Path[] segments) throws Exception {
// Our merged output directory
Path out = new Path(testDir, "out");
-
+
// Merge
SegmentMerger merger = new SegmentMerger(conf);
merger.merge(out, segments, false, false, -1);
FileStatus[] stats = fs.listStatus(out);
Assert.assertEquals(1, stats.length);
-
+
return stats[0].getPath();
}
-
+
/**
* Create a segment with the specified status.
- *
- * @param the segment's paths
- * @param the status of the record, ignored if redirect is true
- * @param whether we're doing a redirect as well
+ *
+ * @param the
+ * segment's paths
+ * @param the
+ * status of the record, ignored if redirect is true
+ * @param whether
+ * we're doing a redirect as well
*/
- protected void createSegment(Path segment, byte status, boolean redirect) throws Exception {
+ protected void createSegment(Path segment, byte status, boolean redirect)
+ throws Exception {
if (redirect) {
createSegment(segment, status, false, true);
} else {
@@ -332,28 +363,32 @@ public class TestSegmentMergerCrawlDatums {
}
}
- protected void createSegment(Path segment, byte status, boolean fetch, boolean redirect) throws Exception {
+ protected void createSegment(Path segment, byte status, boolean fetch,
+ boolean redirect) throws Exception {
LOG.info("\nSegment: " + segment.toString());
-
+
// The URL of our main record
String url = "http://nutch.apache.org/";
-
+
// The URL of our redirecting URL
String redirectUrl = "http://nutch.apache.org/i_redirect_to_the_root/";
-
+
// Our value
CrawlDatum value = new CrawlDatum();
-
+
// Path of the segment's crawl_fetch directory
- Path crawlFetchPath = new Path(new Path(segment, CrawlDatum.FETCH_DIR_NAME), "part-00000");
+ Path crawlFetchPath = new Path(
+ new Path(segment, CrawlDatum.FETCH_DIR_NAME), "part-00000");
// Get a writer for map files containing <Text,CrawlDatum> pairs
- MapFile.Writer writer = new MapFile.Writer(conf, fs, crawlFetchPath.toString(), Text.class, CrawlDatum.class);
+ MapFile.Writer writer = new MapFile.Writer(conf, fs,
+ crawlFetchPath.toString(), Text.class, CrawlDatum.class);
// Whether we're handling a redirect now
// first add the linked datum
// - before redirect status because url sorts before redirectUrl
- // - before fetch status to check whether fetch datum is preferred over linked datum when merging
+ // - before fetch status to check whether fetch datum is preferred over
+ // linked datum when merging
if (redirect) {
// We're writing our our main record URL with status linked
LOG.info(url + " > " + CrawlDatum.getStatusName(CrawlDatum.STATUS_LINKED));
@@ -365,7 +400,7 @@ public class TestSegmentMergerCrawlDatums {
// Whether we're fetching now
if (fetch) {
LOG.info(url + " > " + CrawlDatum.getStatusName(status));
-
+
// Set the status
value.setStatus(status);
@@ -376,11 +411,12 @@ public class TestSegmentMergerCrawlDatums {
// Whether we're handing a redirect now
if (redirect) {
// And the redirect URL with redirect status, pointing to our main URL
- LOG.info(redirectUrl + " > " + CrawlDatum.getStatusName(CrawlDatum.STATUS_FETCH_REDIR_TEMP));
+ LOG.info(redirectUrl + " > "
+ + CrawlDatum.getStatusName(CrawlDatum.STATUS_FETCH_REDIR_TEMP));
value.setStatus(CrawlDatum.STATUS_FETCH_REDIR_TEMP);
writer.append(new Text(redirectUrl), value);
}
-
+
// Close the stuff
writer.close();
}
diff --git a/src/test/org/apache/nutch/tools/proxy/AbstractTestbedHandler.java b/src/test/org/apache/nutch/tools/proxy/AbstractTestbedHandler.java
index e947990c9..b4771d0f2 100644
--- a/src/test/org/apache/nutch/tools/proxy/AbstractTestbedHandler.java
+++ b/src/test/org/apache/nutch/tools/proxy/AbstractTestbedHandler.java
@@ -1,4 +1,5 @@
package org.apache.nutch.tools.proxy;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -30,16 +31,17 @@ public abstract class AbstractTestbedHandler extends AbstractHandler {
@Override
public void handle(String target, HttpServletRequest req,
- HttpServletResponse res, int dispatch) throws IOException,
- ServletException {
- Request base_request = (req instanceof Request) ? (Request)req : HttpConnection.getCurrentConnection().getRequest();
+ HttpServletResponse res, int dispatch) throws IOException,
+ ServletException {
+ Request base_request = (req instanceof Request) ? (Request) req
+ : HttpConnection.getCurrentConnection().getRequest();
res.addHeader("X-TestbedHandlers", this.getClass().getSimpleName());
handle(base_request, res, target, dispatch);
}
-
- public abstract void handle(Request req, HttpServletResponse res, String target,
- int dispatch) throws IOException, ServletException;
-
+
+ public abstract void handle(Request req, HttpServletResponse res,
+ String target, int dispatch) throws IOException, ServletException;
+
public void addMyHeader(HttpServletResponse res, String name, String value) {
name = "X-" + this.getClass().getSimpleName() + "-" + name;
res.addHeader(name, value);
diff --git a/src/test/org/apache/nutch/tools/proxy/DelayHandler.java b/src/test/org/apache/nutch/tools/proxy/DelayHandler.java
index c96e21fb0..58f1f4399 100644
--- a/src/test/org/apache/nutch/tools/proxy/DelayHandler.java
+++ b/src/test/org/apache/nutch/tools/proxy/DelayHandler.java
@@ -1,4 +1,5 @@
package org.apache.nutch.tools.proxy;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -25,13 +26,13 @@ import javax.servlet.http.HttpServletResponse;
import org.mortbay.jetty.Request;
public class DelayHandler extends AbstractTestbedHandler {
-
+
public static final long DEFAULT_DELAY = 2000;
-
+
private int delay;
private boolean random;
private Random r;
-
+
public DelayHandler(int delay) {
if (delay < 0) {
delay = -delay;
@@ -43,13 +44,13 @@ public class DelayHandler extends AbstractTestbedHandler {
@Override
public void handle(Request req, HttpServletResponse res, String target,
- int dispatch) throws IOException, ServletException {
+ int dispatch) throws IOException, ServletException {
try {
int del = random ? r.nextInt(delay) : delay;
Thread.sleep(del);
addMyHeader(res, "Delay", String.valueOf(del));
} catch (Exception e) {
-
+
}
}
}
diff --git a/src/test/org/apache/nutch/tools/proxy/FakeHandler.java b/src/test/org/apache/nutch/tools/proxy/FakeHandler.java
index 4debe6f52..a40b1996c 100644
--- a/src/test/org/apache/nutch/tools/proxy/FakeHandler.java
+++ b/src/test/org/apache/nutch/tools/proxy/FakeHandler.java
@@ -1,4 +1,5 @@
package org.apache.nutch.tools.proxy;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -29,22 +30,20 @@ import org.mortbay.jetty.Request;
public class FakeHandler extends AbstractTestbedHandler {
Random r = new Random(1234567890L); // predictable
- private static final String testA =
- "<html><body><h1>Internet Weather Forecast Accuracy</h1>\n" +
- "<p>Weather forecasting is a secure and popular online presence, which is understandable. The weather affects most everyone's life, and the Internet can provide information on just about any location at any hour of the day or night. But how accurate is this information? How much can we trust it? Perhaps it is just my skeptical nature (or maybe the seeming unpredictability of nature), but I've never put much weight into weather forecasts - especially those made more than three days in advance. That skepticism progressed to a new high in the Summer of 2004, but I have only now done the research necessary to test the accuracy of online weather forecasts. First the story, then the data.</p>" +
- "<h2>An Internet Weather Forecast Gone Terribly Awry</h2>" +
- "<p>It was the Summer of 2004 and my wife and I were gearing up for a trip with another couple to Schlitterbahn in New Braunfels - one of the (if not the) best waterparks ever created. As a matter of course when embarking on a 2.5-hour drive to spend the day in a swimsuit, and given the tendency of the area for natural disasters, we checked the weather. The temperatures looked ideal and, most importantly, the chance of rain was a nice round goose egg.</p>";
- private static final String testB =
- "<p>A couple of hours into our Schlitterbahn experience, we got on a bus to leave the 'old section' for the 'new section.' Along the way, clouds gathered and multiple claps of thunder sounded. 'So much for the 0% chance of rain,' I commented. By the time we got to our destination, lightning sightings had led to the slides and pools being evacuated and soon the rain began coming down in torrents - accompanied by voluminous lightning flashes. After at least a half an hour the downpour had subsided, but the lightning showed no sign of letting up, so we began heading back to our vehicles. A hundred yards into the parking lot, we passing a tree that had apparently been split in two during the storm (whether by lightning or wind, I'm not sure). Not but a few yards later, there was a distinct thud and the husband of the couple accompanying us cried out as a near racquetball sized hunk of ice rebounded off of his head and onto the concrete. Soon, similarly sized hail was falling all around us as everyone scampered for cover. Some cowered under overturned trashcans while others were more fortunate and made it indoors.</p>" +
- "<p>The hail, rain and lightning eventually subsided, but the most alarming news was waiting on cell phone voicemail. A friend who lived in the area had called frantically, knowing we were at the park, as the local news was reporting multiple people had been by struck by lightning at Schlitterbahn during the storm.</p>" +
- "<p>'So much for the 0% chance of rain,' I repeated.</p></body></html>";
+ private static final String testA = "<html><body><h1>Internet Weather Forecast Accuracy</h1>\n"
+ + "<p>Weather forecasting is a secure and popular online presence, which is understandable. The weather affects most everyone's life, and the Internet can provide information on just about any location at any hour of the day or night. But how accurate is this information? How much can we trust it? Perhaps it is just my skeptical nature (or maybe the seeming unpredictability of nature), but I've never put much weight into weather forecasts - especially those made more than three days in advance. That skepticism progressed to a new high in the Summer of 2004, but I have only now done the research necessary to test the accuracy of online weather forecasts. First the story, then the data.</p>"
+ + "<h2>An Internet Weather Forecast Gone Terribly Awry</h2>"
+ + "<p>It was the Summer of 2004 and my wife and I were gearing up for a trip with another couple to Schlitterbahn in New Braunfels - one of the (if not the) best waterparks ever created. As a matter of course when embarking on a 2.5-hour drive to spend the day in a swimsuit, and given the tendency of the area for natural disasters, we checked the weather. The temperatures looked ideal and, most importantly, the chance of rain was a nice round goose egg.</p>";
+ private static final String testB = "<p>A couple of hours into our Schlitterbahn experience, we got on a bus to leave the 'old section' for the 'new section.' Along the way, clouds gathered and multiple claps of thunder sounded. 'So much for the 0% chance of rain,' I commented. By the time we got to our destination, lightning sightings had led to the slides and pools being evacuated and soon the rain began coming down in torrents - accompanied by voluminous lightning flashes. After at least a half an hour the downpour had subsided, but the lightning showed no sign of letting up, so we began heading back to our vehicles. A hundred yards into the parking lot, we passing a tree that had apparently been split in two during the storm (whether by lightning or wind, I'm not sure). Not but a few yards later, there was a distinct thud and the husband of the couple accompanying us cried out as a near racquetball sized hunk of ice rebounded off of his head and onto the concrete. Soon, similarly sized hail was falling all around us as everyone scampered for cover. Some cowered under overturned trashcans while others were more fortunate and made it indoors.</p>"
+ + "<p>The hail, rain and lightning eventually subsided, but the most alarming news was waiting on cell phone voicemail. A friend who lived in the area had called frantically, knowing we were at the park, as the local news was reporting multiple people had been by struck by lightning at Schlitterbahn during the storm.</p>"
+ + "<p>'So much for the 0% chance of rain,' I repeated.</p></body></html>";
@Override
- public void handle(Request req, HttpServletResponse res, String target,
- int dispatch) throws IOException, ServletException {
+ public void handle(Request req, HttpServletResponse res, String target,
+ int dispatch) throws IOException, ServletException {
HttpURI u = req.getUri();
String uri = u.toString();
- //System.err.println("-faking " + uri.toString());
+ // System.err.println("-faking " + uri.toString());
addMyHeader(res, "URI", uri);
// don't pass it down the chain
req.setHandled(true);
@@ -68,8 +67,10 @@ public class FakeHandler extends AbstractTestbedHandler {
base = u.getPath();
}
String prefix = u.getScheme() + "://" + u.getHost();
- if (u.getPort() != 80 && u.getPort() != -1) base += ":" + u.getPort();
- if (!base.startsWith("/")) prefix += "/";
+ if (u.getPort() != 80 && u.getPort() != -1)
+ base += ":" + u.getPort();
+ if (!base.startsWith("/"))
+ prefix += "/";
prefix = prefix + base;
for (int i = 0; i < 10; i++) {
String link = "<p><a href='" + prefix;
@@ -82,18 +83,20 @@ public class FakeHandler extends AbstractTestbedHandler {
// fake a few links to random nonexistent hosts
for (int i = 0; i < 5; i++) {
int h = r.nextInt(1000000); // 1 mln hosts
- String link = "<p><a href='http://www.fake-" + h + ".com/'>fake host " + h + "</a></p>\r\n";
+ String link = "<p><a href='http://www.fake-" + h + ".com/'>fake host "
+ + h + "</a></p>\r\n";
os.write(link.getBytes());
}
// fake a link to the root URL
String link = "<p><a href='" + u.getScheme() + "://" + u.getHost();
- if (u.getPort() != 80 && u.getPort() != -1) link += ":" + u.getPort();
+ if (u.getPort() != 80 && u.getPort() != -1)
+ link += ":" + u.getPort();
link += "/'>site " + u.getHost() + "</a></p>\r\n";
os.write(link.getBytes());
os.write(testB.getBytes());
res.flushBuffer();
} catch (IOException ioe) {
- }
+ }
}
}
diff --git a/src/test/org/apache/nutch/tools/proxy/LogDebugHandler.java b/src/test/org/apache/nutch/tools/proxy/LogDebugHandler.java
index 4f2622200..2682f6d63 100644
--- a/src/test/org/apache/nutch/tools/proxy/LogDebugHandler.java
+++ b/src/test/org/apache/nutch/tools/proxy/LogDebugHandler.java
@@ -1,4 +1,5 @@
package org.apache.nutch.tools.proxy;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -31,29 +32,33 @@ import org.slf4j.LoggerFactory;
import org.mortbay.jetty.Request;
public class LogDebugHandler extends AbstractTestbedHandler implements Filter {
- private static final Logger LOG = LoggerFactory.getLogger(LogDebugHandler.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(LogDebugHandler.class);
@Override
public void handle(Request req, HttpServletResponse res, String target,
- int dispatch) throws IOException, ServletException {
- LOG.info("-- " + req.getMethod() + " " + req.getUri().toString() + "\n" + req.getConnection().getRequestFields());
+ int dispatch) throws IOException, ServletException {
+ LOG.info("-- " + req.getMethod() + " " + req.getUri().toString() + "\n"
+ + req.getConnection().getRequestFields());
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
- FilterChain chain) throws IOException, ServletException {
- ((HttpServletResponse)res).addHeader("X-Handled-By", "AsyncProxyHandler");
- ((HttpServletResponse)res).addHeader("X-TestbedHandlers", "AsyncProxyHandler");
+ FilterChain chain) throws IOException, ServletException {
+ ((HttpServletResponse) res).addHeader("X-Handled-By", "AsyncProxyHandler");
+ ((HttpServletResponse) res).addHeader("X-TestbedHandlers",
+ "AsyncProxyHandler");
try {
chain.doFilter(req, res);
} catch (Throwable e) {
- ((HttpServletResponse)res).sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
+ ((HttpServletResponse) res).sendError(HttpServletResponse.SC_BAD_REQUEST,
+ e.toString());
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
-
+
}
}
diff --git a/src/test/org/apache/nutch/tools/proxy/NotFoundHandler.java b/src/test/org/apache/nutch/tools/proxy/NotFoundHandler.java
index fb4d62614..ef439a61b 100644
--- a/src/test/org/apache/nutch/tools/proxy/NotFoundHandler.java
+++ b/src/test/org/apache/nutch/tools/proxy/NotFoundHandler.java
@@ -1,4 +1,5 @@
package org.apache.nutch.tools.proxy;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -27,13 +28,13 @@ public class NotFoundHandler extends AbstractTestbedHandler {
@Override
public void handle(Request req, HttpServletResponse res, String target,
- int dispatch) throws IOException, ServletException {
+ int dispatch) throws IOException, ServletException {
// don't pass it down the chain
req.setHandled(true);
res.addHeader("X-Handled-By", getClass().getSimpleName());
addMyHeader(res, "URI", req.getUri().toString());
- res.sendError(HttpServletResponse.SC_NOT_FOUND, "Not found: " +
- req.getUri().toString());
+ res.sendError(HttpServletResponse.SC_NOT_FOUND, "Not found: "
+ + req.getUri().toString());
}
}
diff --git a/src/test/org/apache/nutch/tools/proxy/ProxyTestbed.java b/src/test/org/apache/nutch/tools/proxy/ProxyTestbed.java
index 61d9c12c2..a7e6aeb5d 100644
--- a/src/test/org/apache/nutch/tools/proxy/ProxyTestbed.java
+++ b/src/test/org/apache/nutch/tools/proxy/ProxyTestbed.java
@@ -1,4 +1,5 @@
package org.apache.nutch.tools.proxy;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -44,17 +45,25 @@ public class ProxyTestbed {
*/
public static void main(String[] args) throws Exception {
if (args.length == 0) {
- System.err.println("TestbedProxy [-seg <segment_name> | -segdir <segments>] [-port <nnn>] [-forward] [-fake] [-delay nnn] [-debug]");
- System.err.println("-seg <segment_name>\tpath to a single segment (can be specified multiple times)");
- System.err.println("-segdir <segments>\tpath to a parent directory of multiple segments (as above)");
- System.err.println("-port <nnn>\trun the proxy on port <nnn> (special permissions may be needed for ports < 1024)");
- System.err.println("-forward\tif specified, requests to all unknown urls will be passed to");
- System.err.println("\t\toriginal servers. If false (default) unknown urls generate 404 Not Found.");
- System.err.println("-delay\tdelay every response by nnn seconds. If delay is negative use a random value up to nnn");
- System.err.println("-fake\tif specified, requests to all unknown urls will succeed with fake content");
+ System.err
+ .println("TestbedProxy [-seg <segment_name> | -segdir <segments>] [-port <nnn>] [-forward] [-fake] [-delay nnn] [-debug]");
+ System.err
+ .println("-seg <segment_name>\tpath to a single segment (can be specified multiple times)");
+ System.err
+ .println("-segdir <segments>\tpath to a parent directory of multiple segments (as above)");
+ System.err
+ .println("-port <nnn>\trun the proxy on port <nnn> (special permissions may be needed for ports < 1024)");
+ System.err
+ .println("-forward\tif specified, requests to all unknown urls will be passed to");
+ System.err
+ .println("\t\toriginal servers. If false (default) unknown urls generate 404 Not Found.");
+ System.err
+ .println("-delay\tdelay every response by nnn seconds. If delay is negative use a random value up to nnn");
+ System.err
+ .println("-fake\tif specified, requests to all unknown urls will succeed with fake content");
System.exit(-1);
}
-
+
Configuration conf = NutchConfiguration.create();
int port = conf.getInt("segment.proxy.port", 8181);
boolean forward = false;
@@ -62,7 +71,7 @@ public class ProxyTestbed {
boolean delay = false;
boolean debug = false;
int delayVal = 0;
-
+
HashSet<Path> segs = new HashSet<Path>();
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-segdir")) {
@@ -88,28 +97,30 @@ public class ProxyTestbed {
System.exit(-1);
}
}
-
+
// Create the server
Server server = new Server();
SocketConnector connector = new SocketConnector();
connector.setPort(port);
connector.setResolveNames(false);
server.addConnector(connector);
-
+
// create a list of handlers
HandlerList list = new HandlerList();
server.addHandler(list);
-
+
if (debug) {
LOG.info("* Added debug handler.");
list.addHandler(new LogDebugHandler());
}
-
+
if (delay) {
- LOG.info("* Added delay handler: " + (delayVal < 0 ? "random delay up to " + (-delayVal) : "constant delay of " + delayVal));
+ LOG.info("* Added delay handler: "
+ + (delayVal < 0 ? "random delay up to " + (-delayVal)
+ : "constant delay of " + delayVal));
list.addHandler(new DelayHandler(delayVal));
}
-
+
// XXX alternatively, we can add the DispatchHandler as the first one,
// XXX to activate handler plugins and redirect requests to appropriate
// XXX handlers ... Here we always load these handlers
@@ -122,7 +133,8 @@ public class ProxyTestbed {
list.addHandler(segment);
LOG.info("* Added segment handler for: " + p);
} catch (Exception e) {
- LOG.warn("Skipping segment '" + p + "': " + StringUtils.stringifyException(e));
+ LOG.warn("Skipping segment '" + p + "': "
+ + StringUtils.stringifyException(e));
}
}
if (forward) {
diff --git a/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java b/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java
index c40f14644..55877cec3 100644
--- a/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java
+++ b/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java
@@ -1,4 +1,5 @@
package org.apache.nutch.tools.proxy;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -50,43 +51,55 @@ import org.mortbay.jetty.Request;
* XXX should turn this into a plugin?
*/
public class SegmentHandler extends AbstractTestbedHandler {
- private static final Logger LOG = LoggerFactory.getLogger(SegmentHandler.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(SegmentHandler.class);
private Segment seg;
-
- private static HashMap<Integer,Integer> protoCodes = new HashMap<Integer,Integer>();
-
+
+ private static HashMap<Integer, Integer> protoCodes = new HashMap<Integer, Integer>();
+
static {
- protoCodes.put(ProtocolStatus.ACCESS_DENIED, HttpServletResponse.SC_UNAUTHORIZED);
- protoCodes.put(ProtocolStatus.BLOCKED, HttpServletResponse.SC_SERVICE_UNAVAILABLE);
- protoCodes.put(ProtocolStatus.EXCEPTION, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ protoCodes.put(ProtocolStatus.ACCESS_DENIED,
+ HttpServletResponse.SC_UNAUTHORIZED);
+ protoCodes.put(ProtocolStatus.BLOCKED,
+ HttpServletResponse.SC_SERVICE_UNAVAILABLE);
+ protoCodes.put(ProtocolStatus.EXCEPTION,
+ HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
protoCodes.put(ProtocolStatus.FAILED, HttpServletResponse.SC_BAD_REQUEST);
protoCodes.put(ProtocolStatus.GONE, HttpServletResponse.SC_GONE);
- protoCodes.put(ProtocolStatus.MOVED, HttpServletResponse.SC_MOVED_PERMANENTLY);
- protoCodes.put(ProtocolStatus.NOTFETCHING, HttpServletResponse.SC_BAD_REQUEST);
+ protoCodes.put(ProtocolStatus.MOVED,
+ HttpServletResponse.SC_MOVED_PERMANENTLY);
+ protoCodes.put(ProtocolStatus.NOTFETCHING,
+ HttpServletResponse.SC_BAD_REQUEST);
protoCodes.put(ProtocolStatus.NOTFOUND, HttpServletResponse.SC_NOT_FOUND);
- protoCodes.put(ProtocolStatus.NOTMODIFIED, HttpServletResponse.SC_NOT_MODIFIED);
- protoCodes.put(ProtocolStatus.PROTO_NOT_FOUND, HttpServletResponse.SC_BAD_REQUEST);
- protoCodes.put(ProtocolStatus.REDIR_EXCEEDED, HttpServletResponse.SC_BAD_REQUEST);
+ protoCodes.put(ProtocolStatus.NOTMODIFIED,
+ HttpServletResponse.SC_NOT_MODIFIED);
+ protoCodes.put(ProtocolStatus.PROTO_NOT_FOUND,
+ HttpServletResponse.SC_BAD_REQUEST);
+ protoCodes.put(ProtocolStatus.REDIR_EXCEEDED,
+ HttpServletResponse.SC_BAD_REQUEST);
protoCodes.put(ProtocolStatus.RETRY, HttpServletResponse.SC_BAD_REQUEST);
- protoCodes.put(ProtocolStatus.ROBOTS_DENIED, HttpServletResponse.SC_FORBIDDEN);
+ protoCodes.put(ProtocolStatus.ROBOTS_DENIED,
+ HttpServletResponse.SC_FORBIDDEN);
protoCodes.put(ProtocolStatus.SUCCESS, HttpServletResponse.SC_OK);
- protoCodes.put(ProtocolStatus.TEMP_MOVED, HttpServletResponse.SC_MOVED_TEMPORARILY);
- protoCodes.put(ProtocolStatus.WOULDBLOCK, HttpServletResponse.SC_BAD_REQUEST);
+ protoCodes.put(ProtocolStatus.TEMP_MOVED,
+ HttpServletResponse.SC_MOVED_TEMPORARILY);
+ protoCodes.put(ProtocolStatus.WOULDBLOCK,
+ HttpServletResponse.SC_BAD_REQUEST);
}
-
+
private static class SegmentPathFilter implements PathFilter {
public static final SegmentPathFilter INSTANCE = new SegmentPathFilter();
-
+
@Override
public boolean accept(Path p) {
return p.getName().startsWith("part-");
}
-
+
}
-
+
private static class Segment implements Closeable {
-
- private static final Partitioner<Text,Writable> PARTITIONER = new HashPartitioner<Text,Writable>();
+
+ private static final Partitioner<Text, Writable> PARTITIONER = new HashPartitioner<Text, Writable>();
private Path segmentDir;
@@ -98,7 +111,8 @@ public class SegmentHandler extends AbstractTestbedHandler {
private MapFile.Reader[] crawl;
private Configuration conf;
- public Segment(FileSystem fs, Path segmentDir, Configuration conf) throws IOException {
+ public Segment(FileSystem fs, Path segmentDir, Configuration conf)
+ throws IOException {
this.segmentDir = segmentDir;
this.conf = conf;
}
@@ -108,43 +122,52 @@ public class SegmentHandler extends AbstractTestbedHandler {
if (crawl == null)
crawl = getReaders(CrawlDatum.FETCH_DIR_NAME);
}
- return (CrawlDatum)getEntry(crawl, url, new CrawlDatum());
+ return (CrawlDatum) getEntry(crawl, url, new CrawlDatum());
}
-
+
public Content getContent(Text url) throws IOException {
synchronized (cLock) {
if (content == null)
content = getReaders(Content.DIR_NAME);
}
- return (Content)getEntry(content, url, new Content());
+ return (Content) getEntry(content, url, new Content());
}
/** Open the output generated by this format. */
private MapFile.Reader[] getReaders(String subDir) throws IOException {
Path dir = new Path(segmentDir, subDir);
FileSystem fs = dir.getFileSystem(conf);
- Path[] names = FileUtil.stat2Paths(fs.listStatus(dir, SegmentPathFilter.INSTANCE));
+ Path[] names = FileUtil.stat2Paths(fs.listStatus(dir,
+ SegmentPathFilter.INSTANCE));
// sort names, so that hash partitioning works
Arrays.sort(names);
-
+
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(), conf);
}
return parts;
}
-
- private Writable getEntry(MapFile.Reader[] readers, Text url,
- Writable entry) throws IOException {
+
+ private Writable getEntry(MapFile.Reader[] readers, Text url, Writable entry)
+ throws IOException {
return MapFileOutputFormat.getEntry(readers, PARTITIONER, url, entry);
}
public void close() throws IOException {
- if (content != null) { closeReaders(content); }
- if (parseText != null) { closeReaders(parseText); }
- if (parseData != null) { closeReaders(parseData); }
- if (crawl != null) { closeReaders(crawl); }
+ if (content != null) {
+ closeReaders(content);
+ }
+ if (parseText != null) {
+ closeReaders(parseText);
+ }
+ if (parseData != null) {
+ closeReaders(parseData);
+ }
+ if (crawl != null) {
+ closeReaders(crawl);
+ }
}
private void closeReaders(MapFile.Reader[] readers) throws IOException {
@@ -154,14 +177,14 @@ public class SegmentHandler extends AbstractTestbedHandler {
}
}
-
+
public SegmentHandler(Configuration conf, Path name) throws Exception {
seg = new Segment(FileSystem.get(conf), name, conf);
}
@Override
public void handle(Request req, HttpServletResponse res, String target,
- int dispatch) throws IOException, ServletException {
+ int dispatch) throws IOException, ServletException {
try {
String uri = req.getUri().toString();
LOG.info("URI: " + uri);
@@ -171,17 +194,18 @@ public class SegmentHandler extends AbstractTestbedHandler {
if (cd != null) {
addMyHeader(res, "Res", "found");
LOG.info("-got " + cd.toString());
- ProtocolStatus ps = (ProtocolStatus)cd.getMetaData().get(Nutch.WRITABLE_PROTO_STATUS_KEY);
+ ProtocolStatus ps = (ProtocolStatus) cd.getMetaData().get(
+ Nutch.WRITABLE_PROTO_STATUS_KEY);
if (ps != null) {
Integer TrCode = protoCodes.get(ps.getCode());
if (TrCode != null) {
- res.setStatus(TrCode.intValue());
+ res.setStatus(TrCode.intValue());
} else {
res.setStatus(HttpServletResponse.SC_OK);
}
addMyHeader(res, "ProtocolStatus", ps.toString());
} else {
- res.setStatus(HttpServletResponse.SC_OK);
+ res.setStatus(HttpServletResponse.SC_OK);
}
Content c = seg.getContent(url);
if (c == null) { // missing content
diff --git a/src/test/org/apache/nutch/tools/proxy/package-info.java b/src/test/org/apache/nutch/tools/proxy/package-info.java
index edd2c61fd..cc820a7de 100644
--- a/src/test/org/apache/nutch/tools/proxy/package-info.java
+++ b/src/test/org/apache/nutch/tools/proxy/package-info.java
@@ -19,3 +19,4 @@
* Proxy to {@link org.apache.nutch.tools.Benchmark benchmark} the crawler.
*/
package org.apache.nutch.tools.proxy;
+
diff --git a/src/test/org/apache/nutch/util/TestGZIPUtils.java b/src/test/org/apache/nutch/util/TestGZIPUtils.java
index 04dc00ee0..a3d461067 100644
--- a/src/test/org/apache/nutch/util/TestGZIPUtils.java
+++ b/src/test/org/apache/nutch/util/TestGZIPUtils.java
@@ -26,221 +26,215 @@ import org.junit.Test;
public class TestGZIPUtils {
/* a short, highly compressable, string */
- String SHORT_TEST_STRING=
- "aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbcccccccccccccccc";
+ String SHORT_TEST_STRING = "aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbcccccccccccccccc";
/* a short, highly compressable, string */
- String LONGER_TEST_STRING=
- SHORT_TEST_STRING + SHORT_TEST_STRING + SHORT_TEST_STRING
- + SHORT_TEST_STRING + SHORT_TEST_STRING + SHORT_TEST_STRING
- + SHORT_TEST_STRING + SHORT_TEST_STRING + SHORT_TEST_STRING
- + SHORT_TEST_STRING + SHORT_TEST_STRING + SHORT_TEST_STRING;
+ String LONGER_TEST_STRING = SHORT_TEST_STRING + SHORT_TEST_STRING
+ + SHORT_TEST_STRING + SHORT_TEST_STRING + SHORT_TEST_STRING
+ + SHORT_TEST_STRING + SHORT_TEST_STRING + SHORT_TEST_STRING
+ + SHORT_TEST_STRING + SHORT_TEST_STRING + SHORT_TEST_STRING
+ + SHORT_TEST_STRING;
/* a snapshot of the nutch webpage */
- String WEBPAGE=
- "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
- + "<html>\n"
- + "<head>\n"
- + " <meta http-equiv=\"content-type\"\n"
- + " content=\"text/html; charset=ISO-8859-1\">\n"
- + " <title>Nutch</title>\n"
- + "</head>\n"
- + "<body>\n"
- + "<h1\n"
- + " style=\"font-family: helvetica,arial,sans-serif; text-align: center; color: rgb(255, 153, 0);\"><a\n"
- + " href=\"http://www.nutch.org/\"><font style=\"color: rgb(255, 153, 0);\">Nutch</font></a><br>\n"
- + "<small>an open source web-search engine</small></h1>\n"
- + "<hr style=\"width: 100%; height: 1px;\" noshade=\"noshade\">\n"
- + "<table\n"
- + " style=\"width: 100%; text-align: left; margin-left: auto; margin-right: auto;\"\n"
- + " border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n"
- + " <tbody>\n"
- + " <tr>\n"
- + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
- + " href=\"http://sourceforge.net/project/showfiles.php?group_id=59548\">Download</a><br>\n"
- + " </td>\n"
- + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
- + " href=\"tutorial.html\">Tutorial</a><br>\n"
- + " </td>\n"
- + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
- + " href=\"http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/nutch/nutch/\">CVS</a><br>\n"
- + " </td>\n"
- + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
- + " href=\"api/index.html\">Javadoc</a><br>\n"
- + " </td>\n"
- + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
- + " href=\"http://sourceforge.net/tracker/?atid=491356&amp;group_id=59548&amp;func=browse\">Bugs</a><br>\n"
- + " </td>\n"
- + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
- + " href=\"http://sourceforge.net/mail/?group_id=59548\">Lists</a></td>\n"
- + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
- + " href=\"policies.html\">Policies</a><br>\n"
- + " </td>\n"
- + " </tr>\n"
- + " </tbody>\n"
- + "</table>\n"
- + "<hr style=\"width: 100%; height: 1px;\" noshade=\"noshade\">\n"
- + "<h2>Introduction</h2>\n"
- + "Nutch is a nascent effort to implement an open-source web search\n"
- + "engine. Web search is a basic requirement for internet navigation, yet\n"
- + "the number of web search engines is decreasing. Today's oligopoly could\n"
- + "soon be a monopoly, with a single company controlling nearly all web\n"
- + "search for its commercial gain. &nbsp;That would not be good for the\n"
- + "users of internet. &nbsp;Nutch aims to enable anyone to easily and\n"
- + "cost-effectively deploy a world-class web search engine.<br>\n"
- + "<br>\n"
- + "To succeed, the Nutch software must be able to:<br>\n"
- + "<ul>\n"
- + " <li> crawl several billion pages per month</li>\n"
- + " <li>maintain an index of these pages</li>\n"
- + " <li>search that index up to 1000 times per second</li>\n"
- + " <li>provide very high quality search results</li>\n"
- + " <li>operate at minimal cost</li>\n"
- + "</ul>\n"
- + "<h2>Status</h2>\n"
- + "Currently we're just a handful of developers working part-time to put\n"
- + "together a demo. &nbsp;The demo is coded entirely in Java. &nbsp;However\n"
- + "persistent data is written in well-documented formats so that modules\n"
- + "may eventually be re-written in other languages (e.g., Perl, C++) as the\n"
- + "project progresses.<br>\n"
- + "<br>\n"
- + "<hr style=\"width: 100%; height: 1px;\" noshade=\"noshade\"> <a\n"
- + " href=\"http://sourceforge.net\"> </a>\n"
- + "<div style=\"text-align: center;\"><a href=\"http://sourceforge.net\"><img\n"
- + " src=\"http://sourceforge.net/sflogo.php?group_id=59548&amp;type=1\"\n"
- + " style=\"border: 0px solid ; width: 88px; height: 31px;\"\n"
- + " alt=\"SourceForge.net Logo\" title=\"\"></a></div>\n"
- + "</body>\n"
- + "</html>\n";
+ String WEBPAGE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
+ + "<html>\n"
+ + "<head>\n"
+ + " <meta http-equiv=\"content-type\"\n"
+ + " content=\"text/html; charset=ISO-8859-1\">\n"
+ + " <title>Nutch</title>\n"
+ + "</head>\n"
+ + "<body>\n"
+ + "<h1\n"
+ + " style=\"font-family: helvetica,arial,sans-serif; text-align: center; color: rgb(255, 153, 0);\"><a\n"
+ + " href=\"http://www.nutch.org/\"><font style=\"color: rgb(255, 153, 0);\">Nutch</font></a><br>\n"
+ + "<small>an open source web-search engine</small></h1>\n"
+ + "<hr style=\"width: 100%; height: 1px;\" noshade=\"noshade\">\n"
+ + "<table\n"
+ + " style=\"width: 100%; text-align: left; margin-left: auto; margin-right: auto;\"\n"
+ + " border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n"
+ + " <tbody>\n"
+ + " <tr>\n"
+ + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
+ + " href=\"http://sourceforge.net/project/showfiles.php?group_id=59548\">Download</a><br>\n"
+ + " </td>\n"
+ + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
+ + " href=\"tutorial.html\">Tutorial</a><br>\n"
+ + " </td>\n"
+ + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
+ + " href=\"http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/nutch/nutch/\">CVS</a><br>\n"
+ + " </td>\n"
+ + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
+ + " href=\"api/index.html\">Javadoc</a><br>\n"
+ + " </td>\n"
+ + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
+ + " href=\"http://sourceforge.net/tracker/?atid=491356&amp;group_id=59548&amp;func=browse\">Bugs</a><br>\n"
+ + " </td>\n"
+ + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
+ + " href=\"http://sourceforge.net/mail/?group_id=59548\">Lists</a></td>\n"
+ + " <td style=\"vertical-align: top; text-align: center;\"><a\n"
+ + " href=\"policies.html\">Policies</a><br>\n"
+ + " </td>\n"
+ + " </tr>\n"
+ + " </tbody>\n"
+ + "</table>\n"
+ + "<hr style=\"width: 100%; height: 1px;\" noshade=\"noshade\">\n"
+ + "<h2>Introduction</h2>\n"
+ + "Nutch is a nascent effort to implement an open-source web search\n"
+ + "engine. Web search is a basic requirement for internet navigation, yet\n"
+ + "the number of web search engines is decreasing. Today's oligopoly could\n"
+ + "soon be a monopoly, with a single company controlling nearly all web\n"
+ + "search for its commercial gain. &nbsp;That would not be good for the\n"
+ + "users of internet. &nbsp;Nutch aims to enable anyone to easily and\n"
+ + "cost-effectively deploy a world-class web search engine.<br>\n"
+ + "<br>\n"
+ + "To succeed, the Nutch software must be able to:<br>\n"
+ + "<ul>\n"
+ + " <li> crawl several billion pages per month</li>\n"
+ + " <li>maintain an index of these pages</li>\n"
+ + " <li>search that index up to 1000 times per second</li>\n"
+ + " <li>provide very high quality search results</li>\n"
+ + " <li>operate at minimal cost</li>\n"
+ + "</ul>\n"
+ + "<h2>Status</h2>\n"
+ + "Currently we're just a handful of developers working part-time to put\n"
+ + "together a demo. &nbsp;The demo is coded entirely in Java. &nbsp;However\n"
+ + "persistent data is written in well-documented formats so that modules\n"
+ + "may eventually be re-written in other languages (e.g., Perl, C++) as the\n"
+ + "project progresses.<br>\n"
+ + "<br>\n"
+ + "<hr style=\"width: 100%; height: 1px;\" noshade=\"noshade\"> <a\n"
+ + " href=\"http://sourceforge.net\"> </a>\n"
+ + "<div style=\"text-align: center;\"><a href=\"http://sourceforge.net\"><img\n"
+ + " src=\"http://sourceforge.net/sflogo.php?group_id=59548&amp;type=1\"\n"
+ + " style=\"border: 0px solid ; width: 88px; height: 31px;\"\n"
+ + " alt=\"SourceForge.net Logo\" title=\"\"></a></div>\n"
+ + "</body>\n"
+ + "</html>\n";
@Test
public void testZipUnzip() {
- byte[] testBytes= SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes();
testZipUnzip(testBytes);
- testBytes= LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes();
testZipUnzip(testBytes);
- testBytes= WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes();
testZipUnzip(testBytes);
}
@Test
public void testZipUnzipBestEffort() {
- byte[] testBytes= SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes();
testZipUnzipBestEffort(testBytes);
- testBytes= LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes();
testZipUnzipBestEffort(testBytes);
- testBytes= WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes();
testZipUnzipBestEffort(testBytes);
}
public void testTruncation() {
- byte[] testBytes= SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes();
testTruncation(testBytes);
- testBytes= LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes();
testTruncation(testBytes);
- testBytes= WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes();
testTruncation(testBytes);
}
@Test
public void testLimit() {
- byte[] testBytes= SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes();
testLimit(testBytes);
- testBytes= LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes();
testLimit(testBytes);
- testBytes= WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes();
testLimit(testBytes);
}
// helpers
public void testZipUnzip(byte[] origBytes) {
- byte[] compressedBytes= GZIPUtils.zip(origBytes);
+ byte[] compressedBytes = GZIPUtils.zip(origBytes);
Assert.assertTrue("compressed array is not smaller!",
compressedBytes.length < origBytes.length);
- byte[] uncompressedBytes= null;
+ byte[] uncompressedBytes = null;
try {
- uncompressedBytes= GZIPUtils.unzip(compressedBytes);
+ uncompressedBytes = GZIPUtils.unzip(compressedBytes);
} catch (IOException e) {
e.printStackTrace();
- Assert.assertTrue("caught exception '" + e + "' during unzip()",
- false);
+ Assert.assertTrue("caught exception '" + e + "' during unzip()", false);
}
- Assert.assertTrue("uncompressedBytes is wrong size",
+ Assert.assertTrue("uncompressedBytes is wrong size",
uncompressedBytes.length == origBytes.length);
- for (int i= 0; i < origBytes.length; i++)
+ for (int i = 0; i < origBytes.length; i++)
if (origBytes[i] != uncompressedBytes[i])
Assert.assertTrue("uncompressedBytes does not match origBytes", false);
}
public void testZipUnzipBestEffort(byte[] origBytes) {
- byte[] compressedBytes= GZIPUtils.zip(origBytes);
+ byte[] compressedBytes = GZIPUtils.zip(origBytes);
Assert.assertTrue("compressed array is not smaller!",
compressedBytes.length < origBytes.length);
- byte[] uncompressedBytes= GZIPUtils.unzipBestEffort(compressedBytes);
- Assert.assertTrue("uncompressedBytes is wrong size",
+ byte[] uncompressedBytes = GZIPUtils.unzipBestEffort(compressedBytes);
+ Assert.assertTrue("uncompressedBytes is wrong size",
uncompressedBytes.length == origBytes.length);
- for (int i= 0; i < origBytes.length; i++)
+ for (int i = 0; i < origBytes.length; i++)
if (origBytes[i] != uncompressedBytes[i])
Assert.assertTrue("uncompressedBytes does not match origBytes", false);
}
public void testTruncation(byte[] origBytes) {
- byte[] compressedBytes= GZIPUtils.zip(origBytes);
+ byte[] compressedBytes = GZIPUtils.zip(origBytes);
System.out.println("original data has len " + origBytes.length);
- System.out.println("compressed data has len "
- + compressedBytes.length);
+ System.out.println("compressed data has len " + compressedBytes.length);
- for (int i= compressedBytes.length; i >= 0; i--) {
+ for (int i = compressedBytes.length; i >= 0; i--) {
- byte[] truncCompressed= new byte[i];
+ byte[] truncCompressed = new byte[i];
- for (int j= 0; j < i; j++)
- truncCompressed[j]= compressedBytes[j];
+ for (int j = 0; j < i; j++)
+ truncCompressed[j] = compressedBytes[j];
- byte[] trunc= GZIPUtils.unzipBestEffort(truncCompressed);
+ byte[] trunc = GZIPUtils.unzipBestEffort(truncCompressed);
if (trunc == null) {
- System.out.println("truncated to len "
- + i + ", trunc is null");
+ System.out.println("truncated to len " + i + ", trunc is null");
} else {
- System.out.println("truncated to len "
- + i + ", trunc.length= "
+ System.out.println("truncated to len " + i + ", trunc.length= "
+ trunc.length);
- for (int j= 0; j < trunc.length; j++)
- if (trunc[j] != origBytes[j])
+ for (int j = 0; j < trunc.length; j++)
+ if (trunc[j] != origBytes[j])
Assert.assertTrue("truncated/uncompressed array differs at pos "
- + j + " (compressed data had been truncated to len "
- + i + ")", false);
+ + j + " (compressed data had been truncated to len " + i + ")",
+ false);
}
}
}
public void testLimit(byte[] origBytes) {
- byte[] compressedBytes= GZIPUtils.zip(origBytes);
+ byte[] compressedBytes = GZIPUtils.zip(origBytes);
Assert.assertTrue("compressed array is not smaller!",
compressedBytes.length < origBytes.length);
- for (int i= 0; i < origBytes.length; i++) {
+ for (int i = 0; i < origBytes.length; i++) {
- byte[] uncompressedBytes=
- GZIPUtils.unzipBestEffort(compressedBytes, i);
+ byte[] uncompressedBytes = GZIPUtils.unzipBestEffort(compressedBytes, i);
- Assert.assertTrue("uncompressedBytes is wrong size",
+ Assert.assertTrue("uncompressedBytes is wrong size",
uncompressedBytes.length == i);
- for (int j= 0; j < i; j++)
+ for (int j = 0; j < i; j++)
if (origBytes[j] != uncompressedBytes[j])
- Assert.assertTrue("uncompressedBytes does not match origBytes", false);
+ Assert
+ .assertTrue("uncompressedBytes does not match origBytes", false);
}
}
diff --git a/src/test/org/apache/nutch/util/TestMimeUtil.java b/src/test/org/apache/nutch/util/TestMimeUtil.java
index 60c475a2f..d0b45dbac 100644
--- a/src/test/org/apache/nutch/util/TestMimeUtil.java
+++ b/src/test/org/apache/nutch/util/TestMimeUtil.java
@@ -36,7 +36,8 @@ public class TestMimeUtil extends TestCase {
private File sampleDir = new File(System.getProperty("test.build.data", "."),
"test-mime-util");
- /** test data, every element on "test page":
+ /**
+ * test data, every element on "test page":
* <ol>
* <li>MIME type</li>
* <li>file name (last URL path element)</li>
@@ -67,15 +68,11 @@ public class TestMimeUtil extends TestCase {
"<?xml version=\"1.0\"?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<html>\n<head>\n"
+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
- + "</head>\n<body>Hello, World!</body></html>" }
- };
+ + "</head>\n<body>Hello, World!</body></html>" } };
- public static String[][] binaryFiles = {
- {
+ public static String[][] binaryFiles = { {
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- "test.xlsx",
- "" }
- };
+ "test.xlsx", "" } };
private String getMimeType(String url, File file, String contentType,
boolean useMagic) throws IOException {
@@ -121,8 +118,8 @@ public class TestMimeUtil extends TestCase {
public void testBinaryFiles() throws IOException {
for (String[] testPage : binaryFiles) {
File dataFile = new File(sampleDir, testPage[1]);
- String mimeType = getMimeType(urlPrefix + testPage[1],
- dataFile, testPage[2], false);
+ String mimeType = getMimeType(urlPrefix + testPage[1], dataFile,
+ testPage[2], false);
assertEquals("", testPage[0], mimeType);
}
}
diff --git a/src/test/org/apache/nutch/util/TestNodeWalker.java b/src/test/org/apache/nutch/util/TestNodeWalker.java
index 1d0224d35..8edf5ab73 100644
--- a/src/test/org/apache/nutch/util/TestNodeWalker.java
+++ b/src/test/org/apache/nutch/util/TestNodeWalker.java
@@ -30,41 +30,40 @@ import org.xml.sax.InputSource;
public class TestNodeWalker {
/* a snapshot of the nutch webpage */
- private final static String WEBPAGE=
- "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\"><head><title>Nutch</title></head>"
- + "<body>"
- + "<ul>"
- + "<li>crawl several billion pages per month</li>"
- + "<li>maintain an index of these pages</li>"
- + "<li>search that index up to 1000 times per second</li>"
- + "<li>provide very high quality search results</li>"
- + "<li>operate at minimal cost</li>"
- + "</ul>"
- + "</body>"
- + "</html>";
+ private final static String WEBPAGE = "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\"><head><title>Nutch</title></head>"
+ + "<body>"
+ + "<ul>"
+ + "<li>crawl several billion pages per month</li>"
+ + "<li>maintain an index of these pages</li>"
+ + "<li>search that index up to 1000 times per second</li>"
+ + "<li>provide very high quality search results</li>"
+ + "<li>operate at minimal cost</li>" + "</ul>" + "</body>" + "</html>";
private final static String[] ULCONTENT = new String[4];
-
+
@Before
- public void setUp() throws Exception{
- ULCONTENT[0]="crawl several billion pages per month" ;
- ULCONTENT[1]="maintain an index of these pages" ;
- ULCONTENT[2]="search that index up to 1000 times per second" ;
- ULCONTENT[3]="operate at minimal cost" ;
+ public void setUp() throws Exception {
+ ULCONTENT[0] = "crawl several billion pages per month";
+ ULCONTENT[1] = "maintain an index of these pages";
+ ULCONTENT[2] = "search that index up to 1000 times per second";
+ ULCONTENT[3] = "operate at minimal cost";
}
@Test
public void testSkipChildren() {
- DOMParser parser= new DOMParser();
-
+ DOMParser parser = new DOMParser();
+
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
- parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
- parser.parse(new InputSource(new ByteArrayInputStream(WEBPAGE.getBytes())));
+ parser.setFeature(
+ "http://apache.org/xml/features/nonvalidating/load-external-dtd",
+ false);
+ parser
+ .parse(new InputSource(new ByteArrayInputStream(WEBPAGE.getBytes())));
} catch (Exception e) {
e.printStackTrace();
}
-
+
StringBuffer sb = new StringBuffer();
NodeWalker walker = new NodeWalker(parser.getDocument());
while (walker.hasNext()) {
@@ -76,30 +75,33 @@ public class TestNodeWalker {
sb.append(text);
}
}
- Assert.assertTrue("UL Content can NOT be found in the node", findSomeUlContent(sb.toString()));
-
- StringBuffer sbSkip = new StringBuffer();
- NodeWalker walkerSkip = new NodeWalker(parser.getDocument());
- while (walkerSkip.hasNext()) {
- Node currentNode = walkerSkip.nextNode();
- String nodeName = currentNode.getNodeName();
- short nodeType = currentNode.getNodeType();
- if ("ul".equalsIgnoreCase(nodeName)) {
- walkerSkip.skipChildren();
- }
- if (nodeType == Node.TEXT_NODE) {
- String text = currentNode.getNodeValue();
- text = text.replaceAll("\\s+", " ");
- sbSkip.append(text);
- }
- }
- Assert.assertFalse("UL Content can be found in the node", findSomeUlContent(sbSkip.toString()));
+ Assert.assertTrue("UL Content can NOT be found in the node",
+ findSomeUlContent(sb.toString()));
+
+ StringBuffer sbSkip = new StringBuffer();
+ NodeWalker walkerSkip = new NodeWalker(parser.getDocument());
+ while (walkerSkip.hasNext()) {
+ Node currentNode = walkerSkip.nextNode();
+ String nodeName = currentNode.getNodeName();
+ short nodeType = currentNode.getNodeType();
+ if ("ul".equalsIgnoreCase(nodeName)) {
+ walkerSkip.skipChildren();
+ }
+ if (nodeType == Node.TEXT_NODE) {
+ String text = currentNode.getNodeValue();
+ text = text.replaceAll("\\s+", " ");
+ sbSkip.append(text);
+ }
+ }
+ Assert.assertFalse("UL Content can be found in the node",
+ findSomeUlContent(sbSkip.toString()));
}
-
+
public boolean findSomeUlContent(String str) {
- for(int i=0; i<ULCONTENT.length ; i++){
- if(str.contains(ULCONTENT[i])) return true;
- }
+ for (int i = 0; i < ULCONTENT.length; i++) {
+ if (str.contains(ULCONTENT[i]))
+ return true;
+ }
return false;
}
}
diff --git a/src/test/org/apache/nutch/util/TestPrefixStringMatcher.java b/src/test/org/apache/nutch/util/TestPrefixStringMatcher.java
index fc97c2e44..9d8b07bf1 100644
--- a/src/test/org/apache/nutch/util/TestPrefixStringMatcher.java
+++ b/src/test/org/apache/nutch/util/TestPrefixStringMatcher.java
@@ -23,99 +23,93 @@ import org.junit.Test;
/** Unit tests for PrefixStringMatcher. */
public class TestPrefixStringMatcher {
-
- private final static int NUM_TEST_ROUNDS= 20;
- private final static int MAX_TEST_PREFIXES= 100;
- private final static int MAX_PREFIX_LEN= 10;
- private final static int NUM_TEST_INPUTS_PER_ROUND= 100;
- private final static int MAX_INPUT_LEN= 20;
-
- private final static char[] alphabet=
- new char[] {
- 'a', 'b', 'c', 'd',
-// 'e', 'f', 'g', 'h', 'i', 'j',
-// 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
-// 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4',
-// '5', '6', '7', '8', '9', '0'
- };
+ private final static int NUM_TEST_ROUNDS = 20;
+ private final static int MAX_TEST_PREFIXES = 100;
+ private final static int MAX_PREFIX_LEN = 10;
+ private final static int NUM_TEST_INPUTS_PER_ROUND = 100;
+ private final static int MAX_INPUT_LEN = 20;
+
+ private final static char[] alphabet = new char[] { 'a', 'b', 'c', 'd',
+ // 'e', 'f', 'g', 'h', 'i', 'j',
+ // 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
+ // 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4',
+ // '5', '6', '7', '8', '9', '0'
+ };
private String makeRandString(int minLen, int maxLen) {
- int len= minLen + (int) (Math.random() * (maxLen - minLen));
- char[] chars= new char[len];
-
- for (int pos= 0; pos < len; pos++) {
- chars[pos]= alphabet[(int) (Math.random() * alphabet.length)];
+ int len = minLen + (int) (Math.random() * (maxLen - minLen));
+ char[] chars = new char[len];
+
+ for (int pos = 0; pos < len; pos++) {
+ chars[pos] = alphabet[(int) (Math.random() * alphabet.length)];
}
-
+
return new String(chars);
}
-
+
@Test
public void testPrefixMatcher() {
- int numMatches= 0;
- int numInputsTested= 0;
+ int numMatches = 0;
+ int numInputsTested = 0;
- for (int round= 0; round < NUM_TEST_ROUNDS; round++) {
+ for (int round = 0; round < NUM_TEST_ROUNDS; round++) {
// build list of prefixes
- int numPrefixes= (int) (Math.random() * MAX_TEST_PREFIXES);
- String[] prefixes= new String[numPrefixes];
- for (int i= 0; i < numPrefixes; i++) {
- prefixes[i]= makeRandString(0, MAX_PREFIX_LEN);
+ int numPrefixes = (int) (Math.random() * MAX_TEST_PREFIXES);
+ String[] prefixes = new String[numPrefixes];
+ for (int i = 0; i < numPrefixes; i++) {
+ prefixes[i] = makeRandString(0, MAX_PREFIX_LEN);
}
- PrefixStringMatcher prematcher= new PrefixStringMatcher(prefixes);
+ PrefixStringMatcher prematcher = new PrefixStringMatcher(prefixes);
// test random strings for prefix matches
- for (int i= 0; i < NUM_TEST_INPUTS_PER_ROUND; i++) {
- String input= makeRandString(0, MAX_INPUT_LEN);
- boolean matches= false;
- int longestMatch= -1;
- int shortestMatch= -1;
+ for (int i = 0; i < NUM_TEST_INPUTS_PER_ROUND; i++) {
+ String input = makeRandString(0, MAX_INPUT_LEN);
+ boolean matches = false;
+ int longestMatch = -1;
+ int shortestMatch = -1;
- for (int j= 0; j < prefixes.length; j++) {
+ for (int j = 0; j < prefixes.length; j++) {
- if ((prefixes[j].length() > 0)
- && input.startsWith(prefixes[j])) {
+ if ((prefixes[j].length() > 0) && input.startsWith(prefixes[j])) {
- matches= true;
- int matchSize= prefixes[j].length();
+ matches = true;
+ int matchSize = prefixes[j].length();
- if (matchSize > longestMatch)
- longestMatch= matchSize;
+ if (matchSize > longestMatch)
+ longestMatch = matchSize;
- if ( (matchSize < shortestMatch)
- || (shortestMatch == -1) )
- shortestMatch= matchSize;
+ if ((matchSize < shortestMatch) || (shortestMatch == -1))
+ shortestMatch = matchSize;
}
}
- if (matches)
+ if (matches)
numMatches++;
numInputsTested++;
- Assert.assertTrue( "'" + input + "' should " + (matches ? "" : "not ")
- + "match!",
- matches == prematcher.matches(input) );
+ Assert.assertTrue("'" + input + "' should " + (matches ? "" : "not ")
+ + "match!", matches == prematcher.matches(input));
if (matches) {
- Assert.assertTrue( shortestMatch
- == prematcher.shortestMatch(input).length());
- Assert.assertTrue( input.substring(0, shortestMatch).equals(
- prematcher.shortestMatch(input)) );
+ Assert.assertTrue(shortestMatch == prematcher.shortestMatch(input)
+ .length());
+ Assert.assertTrue(input.substring(0, shortestMatch).equals(
+ prematcher.shortestMatch(input)));
- Assert.assertTrue( longestMatch
- == prematcher.longestMatch(input).length());
- Assert.assertTrue( input.substring(0, longestMatch).equals(
- prematcher.longestMatch(input)) );
+ Assert.assertTrue(longestMatch == prematcher.longestMatch(input)
+ .length());
+ Assert.assertTrue(input.substring(0, longestMatch).equals(
+ prematcher.longestMatch(input)));
}
}
}
- System.out.println("got " + numMatches + " matches out of "
- + numInputsTested + " tests");
+ System.out.println("got " + numMatches + " matches out of "
+ + numInputsTested + " tests");
}
}
diff --git a/src/test/org/apache/nutch/util/TestStringUtil.java b/src/test/org/apache/nutch/util/TestStringUtil.java
index 44ca2a2c0..df021f028 100644
--- a/src/test/org/apache/nutch/util/TestStringUtil.java
+++ b/src/test/org/apache/nutch/util/TestStringUtil.java
@@ -24,37 +24,37 @@ import org.junit.Test;
public class TestStringUtil {
public void testRightPad() {
- String s= "my string";
+ String s = "my string";
- String ps= StringUtil.rightPad(s, 0);
+ String ps = StringUtil.rightPad(s, 0);
Assert.assertTrue(s.equals(ps));
- ps= StringUtil.rightPad(s, 9);
+ ps = StringUtil.rightPad(s, 9);
Assert.assertTrue(s.equals(ps));
- ps= StringUtil.rightPad(s, 10);
- Assert.assertTrue( (s+" ").equals(ps) );
+ ps = StringUtil.rightPad(s, 10);
+ Assert.assertTrue((s + " ").equals(ps));
- ps= StringUtil.rightPad(s, 15);
- Assert.assertTrue( (s+" ").equals(ps) );
+ ps = StringUtil.rightPad(s, 15);
+ Assert.assertTrue((s + " ").equals(ps));
}
@Test
public void testLeftPad() {
- String s= "my string";
+ String s = "my string";
- String ps= StringUtil.leftPad(s, 0);
+ String ps = StringUtil.leftPad(s, 0);
Assert.assertTrue(s.equals(ps));
- ps= StringUtil.leftPad(s, 9);
+ ps = StringUtil.leftPad(s, 9);
Assert.assertTrue(s.equals(ps));
- ps= StringUtil.leftPad(s, 10);
- Assert.assertTrue( (" "+s).equals(ps) );
+ ps = StringUtil.leftPad(s, 10);
+ Assert.assertTrue((" " + s).equals(ps));
- ps= StringUtil.leftPad(s, 15);
- Assert.assertTrue( (" "+s).equals(ps) );
+ ps = StringUtil.leftPad(s, 15);
+ Assert.assertTrue((" " + s).equals(ps));
}
diff --git a/src/test/org/apache/nutch/util/TestSuffixStringMatcher.java b/src/test/org/apache/nutch/util/TestSuffixStringMatcher.java
index e4c33275a..f2e8a5c58 100644
--- a/src/test/org/apache/nutch/util/TestSuffixStringMatcher.java
+++ b/src/test/org/apache/nutch/util/TestSuffixStringMatcher.java
@@ -23,97 +23,92 @@ import org.junit.Test;
/** Unit tests for SuffixStringMatcher. */
public class TestSuffixStringMatcher {
- private final static int NUM_TEST_ROUNDS= 20;
- private final static int MAX_TEST_SUFFIXES= 100;
- private final static int MAX_SUFFIX_LEN= 10;
- private final static int NUM_TEST_INPUTS_PER_ROUND= 100;
- private final static int MAX_INPUT_LEN= 20;
-
- private final static char[] alphabet=
- new char[] {
- 'a', 'b', 'c', 'd',
-// 'e', 'f', 'g', 'h', 'i', 'j',
-// 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
-// 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4',
-// '5', '6', '7', '8', '9', '0'
- };
+ private final static int NUM_TEST_ROUNDS = 20;
+ private final static int MAX_TEST_SUFFIXES = 100;
+ private final static int MAX_SUFFIX_LEN = 10;
+ private final static int NUM_TEST_INPUTS_PER_ROUND = 100;
+ private final static int MAX_INPUT_LEN = 20;
+
+ private final static char[] alphabet = new char[] { 'a', 'b', 'c', 'd',
+ // 'e', 'f', 'g', 'h', 'i', 'j',
+ // 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
+ // 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4',
+ // '5', '6', '7', '8', '9', '0'
+ };
private String makeRandString(int minLen, int maxLen) {
- int len= minLen + (int) (Math.random() * (maxLen - minLen));
- char[] chars= new char[len];
-
- for (int pos= 0; pos < len; pos++) {
- chars[pos]= alphabet[(int) (Math.random() * alphabet.length)];
+ int len = minLen + (int) (Math.random() * (maxLen - minLen));
+ char[] chars = new char[len];
+
+ for (int pos = 0; pos < len; pos++) {
+ chars[pos] = alphabet[(int) (Math.random() * alphabet.length)];
}
-
+
return new String(chars);
}
-
+
@Test
public void testSuffixMatcher() {
- int numMatches= 0;
- int numInputsTested= 0;
+ int numMatches = 0;
+ int numInputsTested = 0;
- for (int round= 0; round < NUM_TEST_ROUNDS; round++) {
+ for (int round = 0; round < NUM_TEST_ROUNDS; round++) {
// build list of suffixes
- int numSuffixes= (int) (Math.random() * MAX_TEST_SUFFIXES);
- String[] suffixes= new String[numSuffixes];
- for (int i= 0; i < numSuffixes; i++) {
- suffixes[i]= makeRandString(0, MAX_SUFFIX_LEN);
+ int numSuffixes = (int) (Math.random() * MAX_TEST_SUFFIXES);
+ String[] suffixes = new String[numSuffixes];
+ for (int i = 0; i < numSuffixes; i++) {
+ suffixes[i] = makeRandString(0, MAX_SUFFIX_LEN);
}
- SuffixStringMatcher sufmatcher= new SuffixStringMatcher(suffixes);
+ SuffixStringMatcher sufmatcher = new SuffixStringMatcher(suffixes);
// test random strings for suffix matches
- for (int i= 0; i < NUM_TEST_INPUTS_PER_ROUND; i++) {
- String input= makeRandString(0, MAX_INPUT_LEN);
- boolean matches= false;
- int longestMatch= -1;
- int shortestMatch= -1;
+ for (int i = 0; i < NUM_TEST_INPUTS_PER_ROUND; i++) {
+ String input = makeRandString(0, MAX_INPUT_LEN);
+ boolean matches = false;
+ int longestMatch = -1;
+ int shortestMatch = -1;
- for (int j= 0; j < suffixes.length; j++) {
+ for (int j = 0; j < suffixes.length; j++) {
- if ((suffixes[j].length() > 0)
- && input.endsWith(suffixes[j])) {
+ if ((suffixes[j].length() > 0) && input.endsWith(suffixes[j])) {
- matches= true;
- int matchSize= suffixes[j].length();
+ matches = true;
+ int matchSize = suffixes[j].length();
- if (matchSize > longestMatch)
- longestMatch= matchSize;
+ if (matchSize > longestMatch)
+ longestMatch = matchSize;
- if ( (matchSize < shortestMatch)
- || (shortestMatch == -1) )
- shortestMatch= matchSize;
+ if ((matchSize < shortestMatch) || (shortestMatch == -1))
+ shortestMatch = matchSize;
}
}
- if (matches)
+ if (matches)
numMatches++;
numInputsTested++;
- Assert.assertTrue( "'" + input + "' should " + (matches ? "" : "not ")
- + "match!",
- matches == sufmatcher.matches(input) );
+ Assert.assertTrue("'" + input + "' should " + (matches ? "" : "not ")
+ + "match!", matches == sufmatcher.matches(input));
if (matches) {
- Assert.assertTrue( shortestMatch
- == sufmatcher.shortestMatch(input).length());
- Assert.assertTrue( input.substring(input.length() - shortestMatch).equals(
- sufmatcher.shortestMatch(input)) );
-
- Assert.assertTrue( longestMatch
- == sufmatcher.longestMatch(input).length());
- Assert.assertTrue( input.substring(input.length() - longestMatch).equals(
- sufmatcher.longestMatch(input)) );
+ Assert.assertTrue(shortestMatch == sufmatcher.shortestMatch(input)
+ .length());
+ Assert.assertTrue(input.substring(input.length() - shortestMatch)
+ .equals(sufmatcher.shortestMatch(input)));
+
+ Assert.assertTrue(longestMatch == sufmatcher.longestMatch(input)
+ .length());
+ Assert.assertTrue(input.substring(input.length() - longestMatch)
+ .equals(sufmatcher.longestMatch(input)));
}
}
}
- System.out.println("got " + numMatches + " matches out of "
- + numInputsTested + " tests");
+ System.out.println("got " + numMatches + " matches out of "
+ + numInputsTested + " tests");
}
}
diff --git a/src/test/org/apache/nutch/util/TestURLUtil.java b/src/test/org/apache/nutch/util/TestURLUtil.java
index fbfcddeb5..b1fdd5b2d 100644
--- a/src/test/org/apache/nutch/util/TestURLUtil.java
+++ b/src/test/org/apache/nutch/util/TestURLUtil.java
@@ -26,8 +26,7 @@ import org.junit.Test;
public class TestURLUtil {
@Test
- public void testGetDomainName()
- throws Exception {
+ public void testGetDomainName() throws Exception {
URL url = null;
@@ -76,8 +75,7 @@ public class TestURLUtil {
}
@Test
- public void testGetDomainSuffix()
- throws Exception {
+ public void testGetDomainSuffix() throws Exception {
URL url = null;
url = new URL("http://lucene.apache.org/nutch");
@@ -128,8 +126,7 @@ public class TestURLUtil {
}
@Test
- public void testGetHostSegments()
- throws Exception {
+ public void testGetHostSegments() throws Exception {
URL url;
String[] segments;
@@ -161,9 +158,8 @@ public class TestURLUtil {
}
@Test
- public void testChooseRepr()
- throws Exception {
-
+ public void testChooseRepr() throws Exception {
+
String aDotCom = "http://www.a.com";
String bDotCom = "http://www.b.com";
String aSubDotCom = "http://www.news.a.com";
@@ -171,40 +167,41 @@ public class TestURLUtil {
String aPath = "http://www.a.com/xyz/index.html";
String aPath2 = "http://www.a.com/abc/page.html";
String aPath3 = "http://www.news.a.com/abc/page.html";
-
+
// 1) different domain them keep dest, temp or perm
// a.com -> b.com*
Assert.assertEquals(bDotCom, URLUtil.chooseRepr(aDotCom, bDotCom, true));
Assert.assertEquals(bDotCom, URLUtil.chooseRepr(aDotCom, bDotCom, false));
-
+
// 2) permanent and root, keep src
// *a.com -> a.com?y=1 || *a.com -> a.com/xyz/index.html
Assert.assertEquals(aDotCom, URLUtil.chooseRepr(aDotCom, aQStr, false));
Assert.assertEquals(aDotCom, URLUtil.chooseRepr(aDotCom, aPath, false));
-
- //3) permanent and not root and dest root, keep dest
- //a.com/xyz/index.html -> a.com*
+
+ // 3) permanent and not root and dest root, keep dest
+ // a.com/xyz/index.html -> a.com*
Assert.assertEquals(aDotCom, URLUtil.chooseRepr(aPath, aDotCom, false));
-
- //4) permanent and neither root keep dest
+
+ // 4) permanent and neither root keep dest
// a.com/xyz/index.html -> a.com/abc/page.html*
Assert.assertEquals(aPath2, URLUtil.chooseRepr(aPath, aPath2, false));
-
- //5) temp and root and dest not root keep src
- //*a.com -> a.com/xyz/index.html
+
+ // 5) temp and root and dest not root keep src
+ // *a.com -> a.com/xyz/index.html
Assert.assertEquals(aDotCom, URLUtil.chooseRepr(aDotCom, aPath, true));
-
- //6) temp and not root and dest root keep dest
+
+ // 6) temp and not root and dest root keep dest
// a.com/xyz/index.html -> a.com*
Assert.assertEquals(aDotCom, URLUtil.chooseRepr(aPath, aDotCom, true));
- //7) temp and neither root, keep shortest, if hosts equal by path else by hosts
- // a.com/xyz/index.html -> a.com/abc/page.html*
+ // 7) temp and neither root, keep shortest, if hosts equal by path else by
+ // hosts
+ // a.com/xyz/index.html -> a.com/abc/page.html*
// *www.a.com/xyz/index.html -> www.news.a.com/xyz/index.html
Assert.assertEquals(aPath2, URLUtil.chooseRepr(aPath, aPath2, true));
Assert.assertEquals(aPath, URLUtil.chooseRepr(aPath, aPath3, true));
- //8) temp and both root keep shortest sub domain
+ // 8) temp and both root keep shortest sub domain
// *www.a.com -> www.news.a.com
Assert.assertEquals(aDotCom, URLUtil.chooseRepr(aDotCom, aSubDotCom, true));
}
@@ -212,30 +209,18 @@ public class TestURLUtil {
// from RFC3986 section 5.4.1
private static String baseString = "http://a/b/c/d;p?q";
private static String[][] targets = new String[][] {
- // unknown protocol {"g:h" , "g:h"},
- {"g" , "http://a/b/c/g"},
- { "./g" , "http://a/b/c/g"},
- { "g/" , "http://a/b/c/g/"},
- { "/g" , "http://a/g"},
- { "//g" , "http://g"},
- { "?y" , "http://a/b/c/d;p?y"},
- { "g?y" , "http://a/b/c/g?y"},
- { "#s" , "http://a/b/c/d;p?q#s"},
- { "g#s" , "http://a/b/c/g#s"},
- { "g?y#s" , "http://a/b/c/g?y#s"},
- { ";x" , "http://a/b/c/;x"},
- { "g;x" , "http://a/b/c/g;x"},
- { "g;x?y#s" , "http://a/b/c/g;x?y#s"},
- { "" , "http://a/b/c/d;p?q"},
- { "." , "http://a/b/c/"},
- { "./" , "http://a/b/c/"},
- { ".." , "http://a/b/"},
- { "../" , "http://a/b/"},
- { "../g" , "http://a/b/g"},
- { "../.." , "http://a/"},
- { "../../" , "http://a/"},
- { "../../g" , "http://a/g"}
- };
+ // unknown protocol {"g:h" , "g:h"},
+ { "g", "http://a/b/c/g" }, { "./g", "http://a/b/c/g" },
+ { "g/", "http://a/b/c/g/" }, { "/g", "http://a/g" },
+ { "//g", "http://g" }, { "?y", "http://a/b/c/d;p?y" },
+ { "g?y", "http://a/b/c/g?y" }, { "#s", "http://a/b/c/d;p?q#s" },
+ { "g#s", "http://a/b/c/g#s" }, { "g?y#s", "http://a/b/c/g?y#s" },
+ { ";x", "http://a/b/c/;x" }, { "g;x", "http://a/b/c/g;x" },
+ { "g;x?y#s", "http://a/b/c/g;x?y#s" }, { "", "http://a/b/c/d;p?q" },
+ { ".", "http://a/b/c/" }, { "./", "http://a/b/c/" },
+ { "..", "http://a/b/" }, { "../", "http://a/b/" },
+ { "../g", "http://a/b/g" }, { "../..", "http://a/" },
+ { "../../", "http://a/" }, { "../../g", "http://a/g" } };
@Test
public void testResolveURL() throws Exception {
@@ -247,7 +232,8 @@ public class TestURLUtil {
// test NUTCH-566
URL u566 = new URL("http://www.fleurie.org/entreprise.asp");
abs = URLUtil.resolveURL(u566, "?id_entrep=111");
- Assert.assertEquals("http://www.fleurie.org/entreprise.asp?id_entrep=111", abs.toString());
+ Assert.assertEquals("http://www.fleurie.org/entreprise.asp?id_entrep=111",
+ abs.toString());
URL base = new URL(baseString);
Assert.assertEquals("base url parsing", baseString, base.toString());
for (int i = 0; i < targets.length; i++) {
@@ -255,31 +241,41 @@ public class TestURLUtil {
Assert.assertEquals(targets[i][1], targets[i][1], u.toString());
}
}
-
+
@Test
public void testToUNICODE() throws Exception {
- Assert.assertEquals("http://www.çevir.com", URLUtil.toUNICODE("http://www.xn--evir-zoa.com"));
- Assert.assertEquals("http://uni-tübingen.de/", URLUtil.toUNICODE("http://xn--uni-tbingen-xhb.de/"));
- Assert.assertEquals(
- "http://www.medizin.uni-tübingen.de:8080/search.php?q=abc#p1",
- URLUtil.toUNICODE("http://www.medizin.xn--uni-tbingen-xhb.de:8080/search.php?q=abc#p1"));
-
+ Assert.assertEquals("http://www.çevir.com",
+ URLUtil.toUNICODE("http://www.xn--evir-zoa.com"));
+ Assert.assertEquals("http://uni-tübingen.de/",
+ URLUtil.toUNICODE("http://xn--uni-tbingen-xhb.de/"));
+ Assert
+ .assertEquals(
+ "http://www.medizin.uni-tübingen.de:8080/search.php?q=abc#p1",
+ URLUtil
+ .toUNICODE("http://www.medizin.xn--uni-tbingen-xhb.de:8080/search.php?q=abc#p1"));
+
}
-
+
@Test
public void testToASCII() throws Exception {
- Assert.assertEquals("http://www.xn--evir-zoa.com", URLUtil.toASCII("http://www.çevir.com"));
- Assert.assertEquals("http://xn--uni-tbingen-xhb.de/", URLUtil.toASCII("http://uni-tübingen.de/"));
- Assert.assertEquals(
- "http://www.medizin.xn--uni-tbingen-xhb.de:8080/search.php?q=abc#p1",
- URLUtil.toASCII("http://www.medizin.uni-tübingen.de:8080/search.php?q=abc#p1"));
+ Assert.assertEquals("http://www.xn--evir-zoa.com",
+ URLUtil.toASCII("http://www.çevir.com"));
+ Assert.assertEquals("http://xn--uni-tbingen-xhb.de/",
+ URLUtil.toASCII("http://uni-tübingen.de/"));
+ Assert
+ .assertEquals(
+ "http://www.medizin.xn--uni-tbingen-xhb.de:8080/search.php?q=abc#p1",
+ URLUtil
+ .toASCII("http://www.medizin.uni-tübingen.de:8080/search.php?q=abc#p1"));
}
@Test
public void testFileProtocol() throws Exception {
// keep one single slash NUTCH-XXX
- Assert.assertEquals("file:/path/file.html", URLUtil.toASCII("file:/path/file.html"));
- Assert.assertEquals("file:/path/file.html", URLUtil.toUNICODE("file:/path/file.html"));
+ Assert.assertEquals("file:/path/file.html",
+ URLUtil.toASCII("file:/path/file.html"));
+ Assert.assertEquals("file:/path/file.html",
+ URLUtil.toUNICODE("file:/path/file.html"));
}
}
diff --git a/src/test/org/apache/nutch/util/WritableTestUtils.java b/src/test/org/apache/nutch/util/WritableTestUtils.java
index 6c07f2e86..49bcfa97e 100644
--- a/src/test/org/apache/nutch/util/WritableTestUtils.java
+++ b/src/test/org/apache/nutch/util/WritableTestUtils.java
@@ -34,23 +34,22 @@ public class WritableTestUtils {
Assert.assertEquals(before, writeRead(before, conf));
}
-
/** Utility method for testing writables. */
public static Writable writeRead(Writable before, Configuration conf)
- throws Exception {
-
+ throws Exception {
+
DataOutputBuffer dob = new DataOutputBuffer();
before.write(dob);
-
+
DataInputBuffer dib = new DataInputBuffer();
dib.reset(dob.getData(), dob.getLength());
-
- Writable after = (Writable)before.getClass().newInstance();
+
+ Writable after = (Writable) before.getClass().newInstance();
if (conf != null) {
- ((Configurable)after).setConf(conf);
+ ((Configurable) after).setConf(conf);
}
after.readFields(dib);
return after;
}
-
+
}