Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

This patchset contains improvements to Fetcher, described in NUTCH-54, specifically the following:

Andrzej Bialecki29bea6a24ea9
diff --git a/build.xml b/build.xml
index b53b0d680..0bf3996ed 100644
--- a/build.xml
+++ b/build.xml
@@ -209,7 +209,9 @@
<packageset dir="${plugins.dir}/protocol-file/src/java"/>
<packageset dir="${plugins.dir}/protocol-ftp/src/java"/>
<packageset dir="${plugins.dir}/protocol-http/src/java"/>
+ <packageset dir="${plugins.dir}/protocol-httpclient/src/java"/>
<packageset dir="${plugins.dir}/parse-html/src/java"/>
+ <packageset dir="${plugins.dir}/parse-js/src/java"/>
<packageset dir="${plugins.dir}/parse-text/src/java"/>
<packageset dir="${plugins.dir}/parse-pdf/src/java"/>
<packageset dir="${plugins.dir}/parse-rtf/src/java"/>
diff --git a/conf/nutch-default.xml b/conf/nutch-default.xml
index f2a3cd476..959b81bb0 100644
--- a/conf/nutch-default.xml
+++ b/conf/nutch-default.xml
@@ -578,7 +578,7 @@
<property>
<name>plugin.includes</name>
- <value>protocol-http|urlfilter-regex|parse-(text|html)|index-basic|query-(basic|site|url)</value>
+ <value>protocol-httpclient|urlfilter-regex|parse-(text|html|js)|index-basic|query-(basic|site|url)</value>
<description>Regular expression naming plugin directory names to
include. Any plugin not matching this expression is excluded. By
default Nutch includes crawling just HTML and plain text via HTTP,
@@ -600,6 +600,13 @@
is available</description>
</property>
+<property>
+ <name>parser.html.impl</name>
+ <value>neko</value>
+ <description>HTML Parser implementation. Currently the following keywords
+ are recognized: "neko" uses NekoHTML, "tagsoup" uses TagSoup.
+ </description>
+
<!-- urlfilter plugin properties -->
<property>
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index 5395dd673..4633eecb1 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -20,6 +20,7 @@ import java.io.IOException;
import java.io.File;
import java.util.Properties;
+import org.apache.nutch.net.URLFilters;
import org.apache.nutch.pagedb.FetchListEntry;
import org.apache.nutch.io.*;
import org.apache.nutch.db.*;
@@ -68,6 +69,10 @@ public class Fetcher {
private int threadCount = // max number of threads
NutchConf.get().getInt("fetcher.threads.fetch", 10);
+ private static final float NEW_INJECTED_PAGE_SCORE =
+ NutchConf.get().getFloat("db.score.injected", 2.0f);
+ private static final int MAX_REDIRECT =
+ NutchConf.get().getInt("http.redirect.max", 3);
// All threads (FetcherThread or thread started by it) belong to
// group "fetcher". Each FetcherThread is named as "fetcherXX",
@@ -110,45 +115,84 @@ public class Fetcher {
if (!fle.getFetch()) { // should we fetch this page?
if (LOG.isLoggable(Level.FINE))
LOG.fine("not fetching " + url);
- handleNoFetch(fle, FetcherOutput.SUCCESS);
+ handleNoFetch(fle, ProtocolStatus.STATUS_NOTFETCHING);
continue;
}
- LOG.info("fetching " + url); // fetch the page
-
- Protocol protocol = ProtocolFactory.getProtocol(url);
- Content content = protocol.getContent(url);
-
- handleFetch(url, fle, content);
-
- synchronized (Fetcher.this) { // update status
- pages++;
- bytes += content.getContent().length;
- if ((pages % 100) == 0) { // show status every 100pp
- status();
+ // support multiple redirects, if requested by protocol
+ // or content meta-tags (the latter requires running Fetcher
+ // in parsing mode). Protocol-level redirects take precedence over
+ // content-level redirects. Some plugins can handle redirects
+ // automatically, so that only the final success or failure will be
+ // shown here.
+ boolean refetch = false;
+ int redirCnt = 0;
+ do {
+ LOG.fine("redirCnt=" + redirCnt);
+ refetch = false;
+ LOG.info("fetching " + url); // fetch the page
+ Protocol protocol = ProtocolFactory.getProtocol(url);
+ ProtocolOutput output = protocol.getProtocolOutput(fle);
+ ProtocolStatus pstat = output.getStatus();
+ Content content = output.getContent();
+ switch(pstat.getCode()) {
+ case ProtocolStatus.SUCCESS:
+ if (content != null) {
+ synchronized (Fetcher.this) { // update status
+ pages++;
+ bytes += content.getContent().length;
+ if ((pages % 100) == 0) { // show status every 100pp
+ status();
+ }
+ }
+ ParseStatus ps = handleFetch(url, fle, output);
+ if (ps != null && ps.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
+ url = ps.getMessage();
+ url = URLFilters.filter(url);
+ if (url != null) {
+ refetch = true;
+ redirCnt++;
+ fle = new FetchListEntry(true, new Page(url, NEW_INJECTED_PAGE_SCORE), new String[0]);
+ LOG.info(" - content redirect to " + url);
+ }
+ }
+ }
+ break;
+ case ProtocolStatus.MOVED: // try to redirect immediately
+ case ProtocolStatus.TEMP_MOVED: // try to redirect immediately
+ // record the redirect. perhaps the DB will want to know this.
+ handleNoFetch(fle, pstat);
+ url = pstat.getMessage();
+ if (url != null) {
+ refetch = true;
+ redirCnt++;
+ // create new entry.
+ fle = new FetchListEntry(true, new Page(url, NEW_INJECTED_PAGE_SCORE), new String[0]);
+ LOG.info(" - protocol redirect to " + url);
+ }
+ break;
+ case ProtocolStatus.GONE:
+ case ProtocolStatus.NOT_FOUND:
+ case ProtocolStatus.ACCESS_DENIED:
+ case ProtocolStatus.ROBOTS_DENIED:
+ case ProtocolStatus.RETRY:
+ case ProtocolStatus.NOTMODIFIED:
+ handleNoFetch(fle, pstat);
+ break;
+ case ProtocolStatus.EXCEPTION:
+ logError(url, fle, new Exception(pstat.getMessage())); // retry?
+ handleNoFetch(fle, pstat);
+ break;
+ default:
+ LOG.warning("Unknown ProtocolStatus: " + pstat.getCode());
+ handleNoFetch(fle, pstat);
}
- }
- } catch (ResourceGone e) { // don't retry
- logError(url, fle, e);
- handleNoFetch(fle, FetcherOutput.NOT_FOUND);
-
- // dealt with in handleFetch() below
- //} catch (ParseException e) { // don't retry
- // logError(url, fle, e);
- // handleNoFetch(fle, FetcherOutput.CANT_PARSE);
-
- } catch (RetryLater e) { // explicit retry
- logError(url, fle, e);
- handleNoFetch(fle, FetcherOutput.RETRY);
-
- } catch (ProtocolException e) { // implicit retry
- logError(url, fle, e);
- handleNoFetch(fle, FetcherOutput.RETRY);
+ } while (refetch && (redirCnt < MAX_REDIRECT));
} catch (Throwable t) { // an unchecked exception
if (fle != null) {
logError(url, fle, t); // retry?
- handleNoFetch(fle, FetcherOutput.RETRY);
+ handleNoFetch(fle, new ProtocolStatus(t));
}
}
}
@@ -176,36 +220,44 @@ public class Fetcher {
}
}
- private void handleFetch(String url, FetchListEntry fle, Content content) {
+ private ParseStatus handleFetch(String url, FetchListEntry fle, ProtocolOutput output) {
+ Content content = output.getContent();
+ ProtocolStatus protocolStatus = output.getStatus();
if (!Fetcher.this.parsing) {
outputPage(new FetcherOutput(fle, MD5Hash.digest(content.getContent()),
- FetcherOutput.SUCCESS),
+ protocolStatus),
content, null, null);
- return;
+ return null;
}
- try {
String contentType = content.getContentType();
- Parser parser = ParserFactory.getParser(contentType, url);
- Parse parse = parser.getParse(content);
- outputPage(new FetcherOutput(fle, MD5Hash.digest(content.getContent()),
- FetcherOutput.SUCCESS),
- content, new ParseText(parse.getText()), parse.getData());
- } catch (ParseException e) {
- // 20041026, xing
- // If fetching succeeds, but parsing fails, content should be saved
- // so that we can try to parse again in separate pass, possibly
- // using better/alternative parser.
- LOG.info("fetch okay, but can't parse " + url + ", reason: "
- + e.getMessage());
- outputPage(new FetcherOutput(fle, MD5Hash.digest(content.getContent()),
- FetcherOutput.CANT_PARSE),
- content, new ParseText(""),
- new ParseData("", new Outlink[0], new Properties()));
- }
+ Parser parser = null;
+ Parse parse = null;
+ ParseStatus status = null;
+ try {
+ parser = ParserFactory.getParser(contentType, url);
+ parse = parser.getParse(content);
+ status = parse.getData().getStatus();
+ } catch (Exception e) {
+ e.printStackTrace();
+ status = new ParseStatus(e);
+ }
+ if (status.isSuccess()) {
+ outputPage(new FetcherOutput(fle, MD5Hash.digest(content.getContent()),
+ protocolStatus),
+ content, new ParseText(parse.getText()), parse.getData());
+ } else {
+ LOG.info("fetch okay, but can't parse " + url + ", reason: "
+ + status.toString());
+ outputPage(new FetcherOutput(fle, MD5Hash.digest(content.getContent()),
+ protocolStatus),
+ content, new ParseText(""),
+ new ParseData(status, "", new Outlink[0], new Properties()));
+ }
+ return status;
}
- private void handleNoFetch(FetchListEntry fle, int status) {
+ private void handleNoFetch(FetchListEntry fle, ProtocolStatus status) {
String url = fle.getPage().getURL().toString();
MD5Hash hash = MD5Hash.digest(url);
@@ -213,7 +265,7 @@ public class Fetcher {
outputPage(new FetcherOutput(fle, hash, status),
new Content(url, url, new byte[0], "", new Properties()),
new ParseText(""),
- new ParseData("", new Outlink[0], new Properties()));
+ new ParseData(ParseStatus.STATUS_NOTPARSED, "", new Outlink[0], new Properties()));
} else {
outputPage(new FetcherOutput(fle, hash, status),
new Content(url, url, new byte[0], "", new Properties()),
@@ -234,6 +286,7 @@ public class Fetcher {
}
} catch (Throwable t) {
LOG.severe("error writing output:" + t.toString());
+ t.printStackTrace();
}
}
@@ -429,7 +482,7 @@ public class Fetcher {
}
// set log level
- fetcher.setLogLevel(Level.parse(logLevel.toUpperCase()));
+ setLogLevel(Level.parse(logLevel.toUpperCase()));
if (showThreadID) {
LogFormatter.setShowThreadIDs(showThreadID);
diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutput.java b/src/java/org/apache/nutch/fetcher/FetcherOutput.java
index 8a30e0924..117d1d7a1 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherOutput.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherOutput.java
@@ -26,6 +26,8 @@ import org.apache.nutch.util.*;
import org.apache.nutch.pagedb.FetchListEntry;
import org.apache.nutch.tools.UpdateDatabaseTool;
import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.protocol.ProtocolStatus;
/*********************************************
* An entry in the fetcher's output. This includes all of the fetcher output
@@ -50,25 +52,34 @@ public final class FetcherOutput implements Writable {
public static final String DONE_NAME = "fetcher.done";
public static final String ERROR_NAME = "fetcher.error";
- private final static byte VERSION = 4;
-
- public final static byte RETRY = 0;
- public final static byte SUCCESS = 1;
- public final static byte NOT_FOUND = 2;
- public final static byte CANT_PARSE = 4; // fetched, but can't be parsed
+ private final static byte VERSION = 5;
+
+ // backwards compatibility codes
+ private final static byte RETRY = 0;
+ private final static byte SUCCESS = 1;
+ private final static byte NOT_FOUND = 2;
+ private final static byte CANT_PARSE = 4; // fetched, but can't be parsed
+
+ private static final byte[] oldToNewMap = {
+ ProtocolStatus.RETRY,
+ ProtocolStatus.SUCCESS,
+ ProtocolStatus.NOT_FOUND,
+ ProtocolStatus.FAILED,
+ ProtocolStatus.RETRY
+ };
private FetchListEntry fetchListEntry;
private MD5Hash md5Hash;
- private int status;
+ private ProtocolStatus protocolStatus;
private long fetchDate;
public FetcherOutput() {}
public FetcherOutput(FetchListEntry fetchListEntry,
- MD5Hash md5Hash, int status) {
+ MD5Hash md5Hash, ProtocolStatus protocolStatus) {
this.fetchListEntry = fetchListEntry;
this.md5Hash = md5Hash;
- this.status = status;
+ this.protocolStatus = protocolStatus;
this.fetchDate = System.currentTimeMillis();
}
@@ -78,7 +89,12 @@ public final class FetcherOutput implements Writable {
byte version = in.readByte(); // read version
fetchListEntry = FetchListEntry.read(in);
md5Hash = MD5Hash.read(in);
- status = in.readByte();
+ if (version < 5) {
+ int status = in.readByte();
+ protocolStatus = new ProtocolStatus(oldToNewMap[status]);
+ } else {
+ protocolStatus = ProtocolStatus.read(in);
+ }
if (version < 4) {
UTF8.readString(in); // read & ignore title
@@ -95,7 +111,7 @@ public final class FetcherOutput implements Writable {
out.writeByte(VERSION); // store current version
fetchListEntry.write(out);
md5Hash.write(out);
- out.writeByte(status);
+ protocolStatus.write(out);
out.writeLong(fetchDate);
}
@@ -110,8 +126,8 @@ public final class FetcherOutput implements Writable {
//
public FetchListEntry getFetchListEntry() { return fetchListEntry; }
public MD5Hash getMD5Hash() { return md5Hash; }
- public int getStatus() { return status; }
- public void setStatus(int status) { this.status = status; }
+ public ProtocolStatus getProtocolStatus() { return protocolStatus; }
+ public void setProtocolStatus(ProtocolStatus protocolStatus) { this.protocolStatus = protocolStatus; }
public long getFetchDate() { return fetchDate; }
public void setFetchDate(long fetchDate) { this.fetchDate = fetchDate; }
@@ -126,7 +142,7 @@ public final class FetcherOutput implements Writable {
return
this.fetchListEntry.equals(other.fetchListEntry) &&
this.md5Hash.equals(other.md5Hash) &&
- (this.status == other.status);
+ this.protocolStatus.equals(other.protocolStatus);
}
@@ -134,7 +150,7 @@ public final class FetcherOutput implements Writable {
StringBuffer buffer = new StringBuffer();
buffer.append("FetchListEntry: " + fetchListEntry + "Fetch Result:\n" );
buffer.append("MD5Hash: " + md5Hash + "\n" );
- buffer.append("Status: " + status + "\n" );
+ buffer.append("ProtocolStatus: " + protocolStatus + "\n" );
buffer.append("FetchDate: " + new Date(fetchDate) + "\n" );
return buffer.toString();
}
diff --git a/src/java/org/apache/nutch/indexer/IndexSegment.java b/src/java/org/apache/nutch/indexer/IndexSegment.java
index 78a90914d..9bb9bf994 100644
--- a/src/java/org/apache/nutch/indexer/IndexSegment.java
+++ b/src/java/org/apache/nutch/indexer/IndexSegment.java
@@ -134,7 +134,7 @@ public class IndexSegment {
if (!sr.next(fetcherOutput, null, parseText, parseData)) continue;
// only index the page if it was fetched correctly
- if (fetcherOutput.getStatus() != FetcherOutput.SUCCESS) {
+ if (!fetcherOutput.getProtocolStatus().isSuccess()) {
continue;
}
diff --git a/src/java/org/apache/nutch/parse/HTMLMetaTags.java b/src/java/org/apache/nutch/parse/HTMLMetaTags.java
new file mode 100644
index 000000000..7c5ba0dd5
--- /dev/null
+++ b/src/java/org/apache/nutch/parse/HTMLMetaTags.java
@@ -0,0 +1,203 @@
+/**
+ * Copyright 2005 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.nutch.parse;
+
+import java.net.URL;
+import java.util.Iterator;
+import java.util.Properties;
+
+/**
+ * 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;
+
+ private boolean noFollow = false;
+
+ private boolean noCache = false;
+
+ private URL baseHref = null;
+
+ private boolean refresh = false;
+
+ private int refreshTime = 0;
+
+ private URL refreshHref = null;
+
+ private Properties generalTags = new Properties();
+
+ private Properties httpEquivTags = new Properties();
+
+ /**
+ * Sets all boolean values to <code>false</code>. Clears all other tags.
+ */
+ public void reset() {
+ noIndex = false;
+ noFollow = false;
+ noCache = false;
+ refresh = false;
+ refreshTime = 0;
+ baseHref = null;
+ refreshHref = null;
+ generalTags.clear();
+ httpEquivTags.clear();
+ }
+
+ /**
+ * Sets <code>noFollow</code> to <code>true</code>.
+ */
+ public void setNoFollow() {
+ noFollow = true;
+ }
+
+ /**
+ * Sets <code>noIndex</code> to <code>true</code>.
+ */
+ public void setNoIndex() {
+ noIndex = true;
+ }
+
+ /**
+ * Sets <code>noCache</code> to <code>true</code>.
+ */
+ public void setNoCache() {
+ noCache = true;
+ }
+
+ /**
+ * Sets <code>refresh</code> to the supplied value.
+ */
+ public void setRefresh(boolean refresh) {
+ this.refresh = refresh;
+ }
+
+ /**
+ * Sets the <code>baseHref</code>.
+ */
+ public void setBaseHref(URL baseHref) {
+ this.baseHref = baseHref;
+ }
+
+ /**
+ * Sets the <code>refreshHref</code>.
+ */
+ public void setRefreshHref(URL refreshHref) {
+ this.refreshHref = refreshHref;
+ }
+
+ /**
+ * Sets the <code>refreshTime</code>.
+ */
+ public void setRefreshTime(int refreshTime) {
+ this.refreshTime = refreshTime;
+ }
+
+ /**
+ * A convenience method. Returns the current value of <code>noIndex</code>.
+ */
+ public boolean getNoIndex() {
+ return noIndex;
+ }
+
+ /**
+ * A convenience method. Returns the current value of <code>noFollow</code>.
+ */
+ public boolean getNoFollow() {
+ return noFollow;
+ }
+
+ /**
+ * A convenience method. Returns the current value of <code>noCache</code>.
+ */
+ public boolean getNoCache() {
+ return noCache;
+ }
+
+ /**
+ * A convenience method. Returns the current value of <code>refresh</code>.
+ */
+ public boolean getRefresh() {
+ return refresh;
+ }
+
+ /**
+ * A convenience method. Returns the <code>baseHref</code>, if set, or
+ * <code>null</code> otherwise.
+ */
+ public URL getBaseHref() {
+ return baseHref;
+ }
+
+ /**
+ * A convenience method. Returns the <code>refreshHref</code>, if set, or
+ * <code>null</code> otherwise. The value may be invalid if
+ * {@link #getRefresh()}returns <code>false</code>.
+ */
+ public URL getRefreshHref() {
+ return refreshHref;
+ }
+
+ /**
+ * 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() {
+ return refreshTime;
+ }
+
+ /**
+ * Returns all collected values of the general meta tags. Property names are
+ * tag names, property values are "content" values.
+ */
+ public Properties getGeneralTags() {
+ return generalTags;
+ }
+
+ /**
+ * Returns all collected values of the "http-equiv" meta tags. Property names
+ * are tag names, property values are "content" values.
+ */
+ 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(" * general tags:\n");
+ Iterator it = generalTags.keySet().iterator();
+ while (it.hasNext()) {
+ String key = (String)it.next();
+ sb.append(" - " + key + "\t=\t" + generalTags.get(key) + "\n");
+ }
+ sb.append(" * http-equiv tags:\n");
+ it = httpEquivTags.keySet().iterator();
+ while (it.hasNext()) {
+ 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 23a611dca..ad3cee57d 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilter.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilter.java
@@ -30,6 +30,5 @@ public interface HtmlParseFilter {
/** Adds metadata or otherwise modifies a parse of HTML content, given
* the DOM tree of a page. */
- Parse filter(Content content, Parse parse, DocumentFragment doc)
- throws ParseException;
+ Parse filter(Content content, Parse parse, 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 051b1be3c..2dc6ff609 100644
--- a/src/java/org/apache/nutch/parse/HtmlParseFilters.java
+++ b/src/java/org/apache/nutch/parse/HtmlParseFilters.java
@@ -45,11 +45,11 @@ public class HtmlParseFilters {
private HtmlParseFilters() {} // no public ctor
/** Run all defined filters. */
- public static Parse filter(Content content,Parse parse,DocumentFragment doc)
- throws ParseException {
+ public static Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
for (int i = 0 ; i < CACHE.length; i++) {
- parse = CACHE[i].filter(content, parse, doc);
+ parse = CACHE[i].filter(content, parse, metaTags, doc);
+ if (!parse.getData().getStatus().isSuccess()) break;
}
return parse;
diff --git a/src/java/org/apache/nutch/parse/Parse.java b/src/java/org/apache/nutch/parse/Parse.java
index 5c73274e8..4b17a0a7d 100644
--- a/src/java/org/apache/nutch/parse/Parse.java
+++ b/src/java/org/apache/nutch/parse/Parse.java
@@ -20,6 +20,7 @@ package org.apache.nutch.parse;
* @see Parser#getParse(FetcherOutput,Content)
*/
public interface Parse {
+
/** The textual content of the page. This is indexed, searched, and used when
* generating snippets.*/
String getText();
diff --git a/src/java/org/apache/nutch/parse/ParseData.java b/src/java/org/apache/nutch/parse/ParseData.java
index 3c9d4597e..8b369c098 100644
--- a/src/java/org/apache/nutch/parse/ParseData.java
+++ b/src/java/org/apache/nutch/parse/ParseData.java
@@ -21,7 +21,6 @@ import java.util.*;
import org.apache.nutch.io.*;
import org.apache.nutch.fs.*;
-import org.apache.nutch.util.*;
import org.apache.nutch.tools.UpdateDatabaseTool;
@@ -31,15 +30,17 @@ import org.apache.nutch.tools.UpdateDatabaseTool;
public final class ParseData extends VersionedWritable {
public static final String DIR_NAME = "parse_data";
- private final static byte VERSION = 1;
+ private final static byte VERSION = 2;
private String title;
private Outlink[] outlinks;
private Properties metadata;
+ private ParseStatus status;
public ParseData() {}
- public ParseData(String title, Outlink[] outlinks, Properties metadata) {
+ public ParseData(ParseStatus status, String title, Outlink[] outlinks, Properties metadata) {
+ this.status = status;
this.title = title;
this.outlinks = outlinks;
this.metadata = metadata;
@@ -49,6 +50,9 @@ public final class ParseData extends VersionedWritable {
// Accessor methods
//
+ /** The status of parsing the page. */
+ public ParseStatus getStatus() { return status; }
+
/** The title of the page. */
public String getTitle() { return title; }
@@ -70,8 +74,12 @@ public final class ParseData extends VersionedWritable {
public byte getVersion() { return VERSION; }
public final void readFields(DataInput in) throws IOException {
- super.readFields(in); // check version
+ byte version = in.readByte();
+ if (version > 1)
+ status = ParseStatus.read(in);
+ else
+ status = ParseStatus.STATUS_SUCCESS;
title = UTF8.readString(in); // read title
int totalOutlinks = in.readInt(); // read outlinks
@@ -94,8 +102,8 @@ public final class ParseData extends VersionedWritable {
}
public final void write(DataOutput out) throws IOException {
- super.write(out); // write version
-
+ out.writeByte(VERSION); // write version
+ status.write(out); // write status
UTF8.writeString(out, title); // write title
out.writeInt(outlinks.length); // write outlinks
@@ -127,6 +135,7 @@ public final class ParseData extends VersionedWritable {
return false;
ParseData other = (ParseData)o;
return
+ this.status.equals(other.status) &&
this.title.equals(other.title) &&
Arrays.equals(this.outlinks, other.outlinks) &&
this.metadata.equals(other.metadata);
@@ -135,6 +144,7 @@ public final class ParseData extends VersionedWritable {
public String toString() {
StringBuffer buffer = new StringBuffer();
+ buffer.append("Status: " + status + "\n" );
buffer.append("Title: " + title + "\n" );
buffer.append("Outlinks: " + outlinks.length + "\n" );
diff --git a/src/java/org/apache/nutch/parse/ParseStatus.java b/src/java/org/apache/nutch/parse/ParseStatus.java
new file mode 100644
index 000000000..e9f84ba04
--- /dev/null
+++ b/src/java/org/apache/nutch/parse/ParseStatus.java
@@ -0,0 +1,234 @@
+/*
+ * Created on Apr 28, 2005
+ * Author: Andrzej Bialecki &lt;[email protected]&gt;
+ *
+ */
+package org.apache.nutch.parse;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.Properties;
+
+import org.apache.nutch.io.Writable;
+import org.apache.nutch.io.WritableUtils;
+
+/**
+ * @author Andrzej Bialecki &lt;[email protected]&gt;
+ */
+public class ParseStatus implements Writable {
+
+ // Primary status codes:
+
+ /** Parsing was not performed. */
+ public static final byte NOTPARSED = 0;
+ /** Parsing succeeded. */
+ 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"
+ };
+
+ // Secondary success codes go here:
+
+ /** 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;
+
+ // 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. Invalid format - the content may be corrupted or of wrong type. */
+ 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_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;
+
+ protected ParseStatus() {
+
+ }
+
+ public ParseStatus(int majorCode, int minorCode, String[] args) {
+ this.args = args;
+ this.majorCode = (byte)majorCode;
+ this.minorCode = (short)minorCode;
+ }
+
+ public ParseStatus(int majorCode) {
+ 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);
+ }
+
+ /** Simplified constructor for passing just a text message. */
+ public ParseStatus(int majorCode, int minorCode, 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});
+ }
+
+ public ParseStatus(Throwable t) {
+ 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 {
+ majorCode = in.readByte();
+ minorCode = in.readShort();
+ args = WritableUtils.readCompressedStringArray(in);
+ }
+
+ public void write(DataOutput out) throws IOException {
+ out.writeByte(majorCode);
+ out.writeShort(minorCode);
+ WritableUtils.writeCompressedStringArray(out, args);
+ }
+
+ /** 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.
+ */
+ public String getMessage() {
+ if (args != null && args.length > 0 && args[0] != null)
+ return args[0].toString();
+ 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.
+ */
+ public Parse getEmptyParse() {
+ return new EmptyParseImpl(this);
+ }
+
+ public String toString() {
+ StringBuffer res = new StringBuffer();
+ res.append(majorCodes[majorCode] + "(" + majorCode + "," + minorCode + ")");
+ if (args != null) {
+ if (args.length == 1) {
+ res.append(": " + String.valueOf(args[0]));
+ } else {
+ for (int i = 0; i < args.length; i++) {
+ if (args[i] != null)
+ res.append(", args[" + i + "]=" + String.valueOf(args[i]));
+ }
+ }
+ }
+ 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;
+ }
+
+ public void setMinorCode(short minorCode) {
+ this.minorCode = minorCode;
+ }
+
+ public boolean equals(Object o) {
+ 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;
+ if (this.args == null) {
+ 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;
+ for (int i = 0; i < this.args.length; i++) {
+ if (!this.args[i].equals(other.args[i])) return false;
+ }
+ }
+ return true;
+ }
+}
+
+class EmptyParseImpl implements Parse {
+
+ private ParseData data = null;
+
+ public EmptyParseImpl(ParseStatus status) {
+ data = new ParseData(status, "", new Outlink[0], new Properties());
+ }
+
+ public ParseData getData() {
+ return data;
+ }
+
+ public String getText() {
+ return "";
+ }
+}
+
diff --git a/src/java/org/apache/nutch/parse/Parser.java b/src/java/org/apache/nutch/parse/Parser.java
index a2fe0b675..d9df89de1 100644
--- a/src/java/org/apache/nutch/parse/Parser.java
+++ b/src/java/org/apache/nutch/parse/Parser.java
@@ -27,5 +27,5 @@ public interface Parser {
public final static String X_POINT_ID = Parser.class.getName();
/** Creates the parse for some content. */
- Parse getParse(Content c) throws ParseException;
+ Parse getParse(Content c);
}
diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.java
index db58efd66..56e409b29 100644
--- a/src/java/org/apache/nutch/parse/ParserChecker.java
+++ b/src/java/org/apache/nutch/parse/ParserChecker.java
@@ -67,7 +67,7 @@ public class ParserChecker {
LOG.info("fetching: "+url);
Protocol protocol = ProtocolFactory.getProtocol(url);
- Content content = protocol.getContent(url);
+ Content content = protocol.getProtocolOutput(url).getContent();
if (force) {
content.setContentType(contentType);
diff --git a/src/java/org/apache/nutch/protocol/Protocol.java b/src/java/org/apache/nutch/protocol/Protocol.java
index 38757ff9d..69632353e 100755
--- a/src/java/org/apache/nutch/protocol/Protocol.java
+++ b/src/java/org/apache/nutch/protocol/Protocol.java
@@ -18,13 +18,21 @@ package org.apache.nutch.protocol;
import java.io.IOException;
+import org.apache.nutch.pagedb.FetchListEntry;
+
/** A retriever of url content. Implemented by protocol extensions. */
public interface Protocol {
/** The name of the extension point. */
public final static String X_POINT_ID = Protocol.class.getName();
- /** Returns the {@link Content} for a url.
+ /** Returns the {@link Content} for a url. This method may be
+ * more limited than {@link #getProtocolOutput(FetchListEntry)}.
+ * @throws IOException for any errors.
+ */
+ ProtocolOutput getProtocolOutput(String url);
+
+ /** Returns the {@link Content} for a fetchlist entry.
* @throws IOException for any errors.
*/
- Content getContent(String url) throws ProtocolException;
+ ProtocolOutput getProtocolOutput(FetchListEntry fle);
}
diff --git a/src/java/org/apache/nutch/protocol/ProtocolOutput.java b/src/java/org/apache/nutch/protocol/ProtocolOutput.java
new file mode 100644
index 000000000..efe7ac176
--- /dev/null
+++ b/src/java/org/apache/nutch/protocol/ProtocolOutput.java
@@ -0,0 +1,53 @@
+/**
+ * Copyright 2005 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.nutch.protocol;
+
+/**
+ * Simple aggregate to pass from protocol plugins both content and
+ * protocol status.
+ * @author Andrzej Bialecki &lt;[email protected]&gt;
+ */
+public class ProtocolOutput {
+ private Content content;
+ private ProtocolStatus status;
+
+ public ProtocolOutput(Content content, ProtocolStatus status) {
+ this.content = content;
+ this.status = status;
+ }
+
+ public ProtocolOutput(Content content) {
+ this.content = content;
+ this.status = ProtocolStatus.STATUS_SUCCESS;
+ }
+
+ public Content getContent() {
+ return content;
+ }
+
+ public void setContent(Content content) {
+ this.content = content;
+ }
+
+ public ProtocolStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(ProtocolStatus status) {
+ this.status = status;
+ }
+}
diff --git a/src/java/org/apache/nutch/protocol/ProtocolStatus.java b/src/java/org/apache/nutch/protocol/ProtocolStatus.java
new file mode 100644
index 000000000..28c5340a5
--- /dev/null
+++ b/src/java/org/apache/nutch/protocol/ProtocolStatus.java
@@ -0,0 +1,159 @@
+/**
+ * Copyright 2005 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.nutch.protocol;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+import org.apache.nutch.io.Writable;
+import org.apache.nutch.io.WritableUtils;
+import org.apache.nutch.parse.ParseStatus;
+
+/**
+ * @author Andrzej Bialecki &lt;[email protected]&gt;
+ */
+public class ProtocolStatus implements Writable {
+
+ /** Content was retrieved without errors. */
+ 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;
+ /** Resource is gone. */
+ public static final int GONE = 11;
+ /** Resource has moved permanently. New url should be found in args. */
+ public static final int MOVED = 12;
+ /** Resource has moved temporarily. New url should be found in args. */
+ public static final int TEMP_MOVED = 13;
+ /** Resource was not found. */
+ public static final int NOT_FOUND = 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;
+ /** Access denied - authorization required, but missing/incorrect. */
+ public static final int ACCESS_DENIED = 17;
+ /** Access denied by robots.txt rules. */
+ public static final int ROBOTS_DENIED = 18;
+ /** Too many redirects. */
+ public static final int REDIR_EXCEED = 19;
+ /** Not fetching. */
+ public static final int NOTFETCHING = 20;
+ /** Unchanged since the last fetch. */
+ public static final int NOTMODIFIED = 21;
+
+
+ public static final ProtocolStatus STATUS_SUCCESS = new ProtocolStatus(SUCCESS);
+ public static final ProtocolStatus STATUS_NOTFETCHING = new ProtocolStatus(NOTFETCHING);
+ public static final ProtocolStatus STATUS_FAILED = new ProtocolStatus(FAILED);
+ public static final ProtocolStatus STATUS_NOTMODIFIED = new ProtocolStatus(NOTMODIFIED);
+
+ private int code;
+ private String[] args;
+
+ protected ProtocolStatus() {
+
+ }
+
+ public ProtocolStatus(int code, String[] args) {
+ this.code = code;
+ this.args = args;
+ }
+
+ public ProtocolStatus(int code) {
+ this(code, null);
+ }
+
+ public ProtocolStatus(int code, Object message) {
+ this.code = code;
+ this.args = new String[]{String.valueOf(message)};
+ }
+
+ public ProtocolStatus(Throwable t) {
+ this(EXCEPTION, t);
+ }
+
+ public static ProtocolStatus read(DataInput in) throws IOException {
+ ProtocolStatus res = new ProtocolStatus();
+ res.readFields(in);
+ return res;
+ }
+
+ public void readFields(DataInput in) throws IOException {
+ code = in.readByte();
+ args = WritableUtils.readCompressedStringArray(in);
+ }
+
+ public void write(DataOutput out) throws IOException {
+ out.writeByte((byte)code);
+ WritableUtils.writeCompressedStringArray(out, args);
+ }
+
+ public String[] getArgs() {
+ return args;
+ }
+
+ public int getCode() {
+ return code;
+ }
+
+ public boolean isSuccess() {
+ return code == SUCCESS;
+ }
+
+ public String getMessage() {
+ if (args != null && args.length > 0) return args[0];
+ return null;
+ }
+
+ 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) return false;
+ if (this.args == null) {
+ 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;
+ for (int i = 0; i < this.args.length; i++) {
+ if (!this.args[i].equals(other.args[i])) return false;
+ }
+ }
+ return true;
+ }
+
+ public String toString() {
+ StringBuffer res = new StringBuffer();
+ res.append("(" + code + ")");
+ if (args != null) {
+ if (args.length == 1) {
+ res.append(": " + String.valueOf(args[0]));
+ } else {
+ for (int i = 0; i < args.length; i++) {
+ if (args[i] != null)
+ res.append(", args[" + i + "]=" + String.valueOf(args[i]));
+ }
+ }
+ }
+ return res.toString();
+ }
+}
diff --git a/src/java/org/apache/nutch/tools/ParseSegment.java b/src/java/org/apache/nutch/tools/ParseSegment.java
index 002caba08..09dd6c0cb 100644
--- a/src/java/org/apache/nutch/tools/ParseSegment.java
+++ b/src/java/org/apache/nutch/tools/ParseSegment.java
@@ -178,14 +178,15 @@ public class ParseSegment {
// safe guard against mismatched files
if (!url.equals(content.getUrl())) {
LOG.severe("Mismatched entries under "
- + FetcherOutput.DIR_NAME_NP + " and " + Content.DIR_NAME);
+ + FetcherOutput.DIR_NAME_NP + " (" + url +
+ ") and " + Content.DIR_NAME + " (" + content.getUrl() + ")");
continue;
}
// if fetch was successful or
// previously unable to parse (so try again)
- if (fetcherOutput.getStatus() == FetcherOutput.SUCCESS ||
- fetcherOutput.getStatus() == FetcherOutput.CANT_PARSE) {
+ ProtocolStatus ps = fetcherOutput.getProtocolStatus();
+ if (ps.isSuccess()) {
handleContent(url, content);
synchronized (ParseSegment.this) {
pages++; // record successful parse
@@ -195,18 +196,18 @@ public class ParseSegment {
}
} else {
// errored at fetch step
- logError(url, new ProtocolException("Error at fetch stage"));
- handleNoContent(ParserOutput.NOFETCH);
+ logError(url, new ProtocolException("Error at fetch stage: " + ps));
+ handleNoContent(new ParseStatus(ParseStatus.FAILED_MISSING_CONTENT));
}
} catch (ParseException e) {
logError(url, e);
- handleNoContent(ParserOutput.FAILURE);
+ handleNoContent(new ParseStatus(e));
} catch (Throwable t) { // an unchecked exception
if (fle != null) {
logError(url, t);
- handleNoContent(ParserOutput.UNKNOWN);
+ handleNoContent(new ParseStatus(t));
} else {
LOG.severe("Unexpected exception");
}
@@ -238,27 +239,26 @@ public class ParseSegment {
Parse parse = parser.getParse(content);
outputPage
- (new ParseText(parse.getText()), parse.getData(),ParserOutput.SUCCESS);
+ (new ParseText(parse.getText()), parse.getData());
}
- private void handleNoContent(int status) {
+ private void handleNoContent(ParseStatus status) {
if (ParseSegment.this.dryRun) {
LOG.info("To be handled as no content");
return;
}
outputPage(new ParseText(""),
- new ParseData("", new Outlink[0], new Properties()),
- status);
+ new ParseData(status, "", new Outlink[0], new Properties()));
}
private void outputPage
- (ParseText parseText, ParseData parseData, int status) {
+ (ParseText parseText, ParseData parseData) {
try {
t3 = System.currentTimeMillis();
synchronized (parserOutputWriter) {
t4 = System.currentTimeMillis();
parserOutputWriter.append(new LongWritable(myEntry),
- new ParserOutput(parseData, parseText, status));
+ new ParserOutput(parseData, parseText));
t5 = System.currentTimeMillis();
if (LOG.isLoggable(Level.FINE))
LOG.fine("Entry: "+myEntry
@@ -274,30 +274,21 @@ public class ParseSegment {
}
/**
- * Inner class ParserOutput: ParseData + ParseText + status
+ * Inner class ParserOutput: ParseData + ParseText
*/
private class ParserOutput extends VersionedWritable {
public static final String DIR_NAME = "parser";
- private final static byte VERSION = 1;
-
- // could be more detailed
- public final static byte UNKNOWN = (byte)0; // unknown problem in parsing
- public final static byte SUCCESS = (byte)1; // parsing succeeded
- public final static byte FAILURE = (byte)2; // parsing failed
- public final static byte NOFETCH = (byte)3; // fetch was not a SUCCESS
-
- private int status;
+ private final static byte VERSION = 2;
private ParseData parseData = new ParseData();
private ParseText parseText = new ParseText();
public ParserOutput() {}
- public ParserOutput(ParseData parseData, ParseText parseText, int status) {
+ public ParserOutput(ParseData parseData, ParseText parseText) {
this.parseData = parseData;
this.parseText = parseText;
- this.status = status;
}
public byte getVersion() { return VERSION; }
@@ -310,13 +301,8 @@ public class ParseSegment {
return this.parseText;
}
- public int getStatus() {
- return this.status;
- }
-
public final void readFields(DataInput in) throws IOException {
super.readFields(in); // check version
- status = in.readByte();
parseData.readFields(in);
parseText.readFields(in);
return;
@@ -324,7 +310,6 @@ public class ParseSegment {
public final void write(DataOutput out) throws IOException {
super.write(out); // write version
- out.writeByte(status);
parseData.write(out);
parseText.write(out);
return;
@@ -523,19 +508,6 @@ public class ParseSegment {
if (fetcherNPReader.key() != key.get())
throw new IOException("Mismatch between entries under "
+ FetcherOutput.DIR_NAME_NP + " and in " + sortedFile.getName());
- // reset status in fo (FetcherOutput), using status in ParserOutput
- switch (val.getStatus()) {
- case ParserOutput.SUCCESS:
- fo.setStatus(FetcherOutput.SUCCESS);
- break;
- case ParserOutput.UNKNOWN:
- case ParserOutput.FAILURE:
- fo.setStatus(FetcherOutput.CANT_PARSE);
- break;
- case ParserOutput.NOFETCH:
- default:
- // do not reset
- }
fetcherWriter.append(fo);
parseDataWriter.append(val.getParseData());
parseTextWriter.append(val.getParseText());
diff --git a/src/java/org/apache/nutch/tools/UpdateDatabaseTool.java b/src/java/org/apache/nutch/tools/UpdateDatabaseTool.java
index b35b5efe9..69b331bec 100644
--- a/src/java/org/apache/nutch/tools/UpdateDatabaseTool.java
+++ b/src/java/org/apache/nutch/tools/UpdateDatabaseTool.java
@@ -29,6 +29,7 @@ import org.apache.nutch.linkdb.*;
import org.apache.nutch.pagedb.*;
import org.apache.nutch.fetcher.*;
import org.apache.nutch.parse.*;
+import org.apache.nutch.protocol.ProtocolStatus;
import org.apache.nutch.util.*;
@@ -108,14 +109,14 @@ public class UpdateDatabaseTool {
if (!fle.getFetch()) { // didn't fetch
pageContentsUnchanged(fo); // treat as unchanged
- } else if (fo.getStatus() == fo.SUCCESS) { // fetch succeed
+ } else if (fo.getProtocolStatus().isSuccess()) { // fetch succeed
if (fo.getMD5Hash().equals(page.getMD5())) {
pageContentsUnchanged(fo); // contents unchanged
} else {
pageContentsChanged(fo, pd); // contents changed
}
- } else if (fo.getStatus() == fo.RETRY &&
+ } else if (fo.getProtocolStatus().getCode() == ProtocolStatus.RETRY &&
page.getRetriesSinceFetch() < MAX_RETRIES) {
pageRetry(fo); // retry later
diff --git a/src/plugin/build.xml b/src/plugin/build.xml
index 62e380d0a..f04fea916 100755
--- a/src/plugin/build.xml
+++ b/src/plugin/build.xml
@@ -9,12 +9,14 @@
<ant dir="protocol-file" target="deploy"/>
<ant dir="protocol-ftp" target="deploy"/>
<ant dir="protocol-http" target="deploy"/>
+ <ant dir="protocol-httpclient" target="deploy"/>
<ant dir="parse-html" target="deploy"/>
+ <ant dir="parse-js" target="deploy"/>
<ant dir="parse-text" target="deploy"/>
<ant dir="parse-pdf" target="deploy"/>
<ant dir="parse-msword" target="deploy"/>
-<!-- <ant dir="parse-mp3" target="deploy"/> license: jid3 is LGPL-->
-<!-- <ant dir="parse-rtf" target="deploy"/> license: parse-rtf is LGPL-->
+<!-- <ant dir="parse-mp3" target="deploy"/> -->
+<!-- <ant dir="parse-rtf" target="deploy"/> -->
<ant dir="parse-ext" target="deploy"/>
<ant dir="index-basic" target="deploy"/>
<ant dir="index-more" target="deploy"/>
@@ -38,8 +40,8 @@
<ant dir="parse-html" target="test"/>
<ant dir="parse-pdf" target="test"/>
<ant dir="parse-msword" target="test"/>
-<!-- <ant dir="parse-mp3" target="test"/> -->
-<!-- <ant dir="parse-rtf" target="test"/> -->
+ <!-- <ant dir="parse-mp3" target="test"/> -->
+ <!-- <ant dir="parse-rtf" target="test"/> -->
<ant dir="parse-ext" target="test"/>
<ant dir="creativecommons" target="test"/>
<ant dir="languageidentifier" target="test"/>
@@ -53,7 +55,9 @@
<ant dir="protocol-file" target="clean"/>
<ant dir="protocol-ftp" target="clean"/>
<ant dir="protocol-http" target="clean"/>
+ <ant dir="protocol-httpclient" target="clean"/>
<ant dir="parse-html" target="clean"/>
+ <ant dir="parse-js" target="clean"/>
<ant dir="parse-text" target="clean"/>
<ant dir="parse-pdf" target="clean"/>
<ant dir="parse-msword" target="clean"/>
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 44d5dd432..193f8beff 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
@@ -252,19 +252,22 @@ public class CCParseFilter implements HtmlParseFilter {
/** Adds metadata or otherwise modifies a parse of an HTML document, given
* the DOM tree of a page. */
- public Parse filter(Content content, Parse parse, DocumentFragment doc)
- throws ParseException {
+ public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
// construct base url
URL base;
try {
base = new URL(content.getBaseUrl());
} catch (MalformedURLException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
}
- // extract license metadata
- Walker.walk(doc, base, parse.getData().getMetadata());
+ try {
+ // extract license metadata
+ Walker.walk(doc, base, parse.getData().getMetadata());
+ } catch (ParseException e) {
+ return new ParseStatus(e).getEmptyParse();
+ }
return parse;
}
diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
index 7a5794830..2d3fa72cb 100644
--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
@@ -14,9 +14,9 @@
* limitations under the License.
*/
package org.apache.nutch.analysis.lang;
+import org.apache.nutch.parse.HTMLMetaTags;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.HtmlParseFilter;
-import org.apache.nutch.parse.ParseException;
import org.apache.nutch.protocol.Content;
import org.w3c.dom.*;
@@ -38,8 +38,7 @@ public class HTMLLanguageParser implements HtmlParseFilter {
* <li>3. meta http-equiv (content-language) (http://www.w3.org/TR/REC-html40/struct/global.html#h-7.4.4.2)
* <br>Only the first occurence of language is stored.
*/
- public Parse filter(Content content, Parse parse, DocumentFragment doc)
- throws ParseException {
+ public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
String lang = findLanguage(doc);
if (lang != null) {
diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java
index 67c9c5d26..207cbc103 100644
--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java
+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java
@@ -239,7 +239,7 @@ public class LanguageIdentifier implements IndexingFilter {
Protocol protocol;
try {
protocol = ProtocolFactory.getProtocol(url);
- Content content = protocol.getContent(url);
+ Content content = protocol.getProtocolOutput(url).getContent();
String contentType = content.getContentType();
Parser parser = ParserFactory.getParser(contentType, url);
Parse parse = parser.getParse(content);
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 207db050f..cc990aea4 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
@@ -17,15 +17,14 @@
package org.apache.nutch.parse.ext;
import org.apache.nutch.protocol.Content;
+import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseImpl;
import org.apache.nutch.parse.Outlink;
-import org.apache.nutch.parse.ParseException;
import org.apache.nutch.util.LogFormatter;
-import org.apache.nutch.util.NutchConf;
import org.apache.nutch.util.CommandRunner;
import org.apache.nutch.plugin.Extension;
@@ -88,14 +87,14 @@ public class ExtParser implements Parser {
public ExtParser () {}
- public Parse getParse(Content content) throws ParseException {
+ public Parse getParse(Content content) {
String contentType = content.getContentType();
String[] params = (String[]) TYPE_PARAMS_MAP.get(contentType);
if (params == null)
- throw new ParseException(
- "No external command defined for contentType: " + contentType);
+ return new ParseStatus(ParseStatus.FAILED,
+ "No external command defined for contentType: " + contentType).getEmptyParse();
String command = params[0];
int timeout = Integer.parseInt(params[1]);
@@ -114,8 +113,10 @@ public class ExtParser implements Parser {
(String)content.getMetadata().get("Content-Length");
if (contentLength != null
&& raw.length != Integer.parseInt(contentLength)) {
- throw new ParseException("Content truncated at "+raw.length
- +" bytes. Parser can't handle incomplete "+contentType+" file.");
+ return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
+ "Content truncated at " + raw.length
+ +" bytes. Parser can't handle incomplete "
+ + contentType + " file.").getEmptyParse();
}
ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE);
@@ -133,15 +134,14 @@ public class ExtParser implements Parser {
cr.evaluate();
if (cr.getExitValue() != 0)
- throw new ParseException("External command "+command
- +" failed with error: "+es.toString());
+ return new ParseStatus(ParseStatus.FAILED,
+ "External command " + command
+ + " failed with error: " + es.toString()).getEmptyParse();
text = os.toString();
- } catch (ParseException e) {
- throw e;
} catch (Exception e) { // run time exception
- throw new ParseException("ExtParser failed. "+e);
+ return new ParseStatus(e).getEmptyParse();
}
if (text == null)
@@ -157,7 +157,7 @@ public class ExtParser implements Parser {
Properties metaData = new Properties();
metaData.putAll(content.getMetadata()); // copy through
- ParseData parseData = new ParseData(title, outlinks, metaData);
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);
return new ParseImpl(text, parseData);
}
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 c3463835a..c8515b1a8 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
@@ -79,7 +79,7 @@ public class TestExtParser extends TestCase {
// get nutch content
Protocol protocol = ProtocolFactory.getProtocol(urlString);
- content = protocol.getContent(urlString);
+ content = protocol.getProtocolOutput(urlString).getContent();
protocol = null;
}
diff --git a/src/plugin/parse-html/lib/tagsoup-1.0rc3.jar b/src/plugin/parse-html/lib/tagsoup-1.0rc3.jar
new file mode 100644
index 000000000..fee98b02f
Binary files /dev/null and b/src/plugin/parse-html/lib/tagsoup-1.0rc3.jar differ
diff --git a/src/plugin/parse-html/lib/tagsoup.LICENSE.txt b/src/plugin/parse-html/lib/tagsoup.LICENSE.txt
new file mode 100644
index 000000000..b074880be
--- /dev/null
+++ b/src/plugin/parse-html/lib/tagsoup.LICENSE.txt
@@ -0,0 +1,49 @@
+The Academic Free License
+v. 2.1
+
+This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work:
+
+Licensed under the Academic Free License version 2.1
+
+1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following:
+
+a) to reproduce the Original Work in copies;
+
+b) to prepare derivative works ("Derivative Works") based upon the Original Work;
+
+c) to distribute copies of the Original Work and Derivative Works to the public;
+
+d) to perform the Original Work publicly; and
+
+e) to display the Original Work publicly.
+
+2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works.
+
+3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work.
+
+4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license.
+
+5) This section intentionally omitted.
+
+6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work.
+
+7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer.
+
+8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
+
+9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions.
+
+10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware.
+
+11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License.
+
+12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License.
+
+13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable.
+
+14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You.
+
+This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner.
+
diff --git a/src/plugin/parse-html/plugin.xml b/src/plugin/parse-html/plugin.xml
index 615642448..103d0aede 100755
--- a/src/plugin/parse-html/plugin.xml
+++ b/src/plugin/parse-html/plugin.xml
@@ -18,6 +18,7 @@
<export name="*"/>
</library>
<library name="nekohtml-0.9.4.jar"/>
+ <library name="tagsoup-1.0rc3.jar"/>
</runtime>
<extension id="org.apache.nutch.parse.html"
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
new file mode 100644
index 000000000..bcdb1f365
--- /dev/null
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMBuilder.java
@@ -0,0 +1,738 @@
+/*
+ * XXX [email protected]: This class is copied verbatim from Xalan-J 2.6.0
+ * XXX distribution, org.apache.xml.utils.DOMBuilder, in order to
+ * avoid dependency on Xalan.
+ */
+
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * $Id: DOMBuilder.java,v 1.19 2004/02/25 13:07:51 aruny Exp $
+ */
+package org.apache.nutch.parse.html;
+
+import java.util.Stack;
+
+import org.w3c.dom.Comment;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+import org.w3c.dom.CDATASection;
+
+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.
+ * @xsl.usage general
+ */
+public class DOMBuilder
+ implements ContentHandler, LexicalHandler
+{
+
+ /** Root document */
+ public Document m_doc;
+
+ /** Current node */
+ protected Node m_currentNode = null;
+
+ /** First node of document fragment or null if not a DocumentFragment */
+ public DocumentFragment m_docFrag = null;
+
+ /** Vector of element nodes */
+ protected Stack m_elemStack = new Stack();
+
+ /**
+ * 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)
+ {
+ 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
+ */
+ 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
+ */
+ public DOMBuilder(Document doc)
+ {
+ m_doc = doc;
+ }
+
+ /**
+ * 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()
+ {
+ 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()
+ {
+ return m_currentNode;
+ }
+
+ /**
+ * Return null since there is no Writer for this class.
+ *
+ * @return null
+ */
+ public java.io.Writer getWriter()
+ {
+ return null;
+ }
+
+ /**
+ * Append a node to the current container.
+ *
+ * @param newNode New node to append
+ */
+ protected void append(Node newNode) throws org.xml.sax.SAXException
+ {
+
+ Node currentNode = m_currentNode;
+
+ if (null != currentNode)
+ {
+ currentNode.appendChild(newNode);
+
+ // System.out.println(newNode.getNodeName());
+ }
+ else if (null != m_docFrag)
+ {
+ m_docFrag.appendChild(newNode);
+ }
+ else
+ {
+ boolean ok = true;
+ short type = newNode.getNodeType();
+
+ 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...");
+ }
+
+ 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!");
+ }
+ }
+
+ if (ok)
+ m_doc.appendChild(newNode);
+ }
+ }
+
+ /**
+ * 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.
+ * @see org.xml.sax.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>
+ */
+ 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>
+ */
+ 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.
+ * @see #endElement
+ * @see org.xml.sax.Attributes
+ */
+ 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.
+ if ((null == ns) || (ns.length() == 0))
+ elem = m_doc.createElementNS(null,name);
+ else
+ elem = m_doc.createElementNS(ns, name);
+
+ append(elem);
+
+ try
+ {
+ int nAtts = atts.getLength();
+
+ if (0 != nAtts)
+ {
+ for (int i = 0; i < nAtts; 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))
+ 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));
+ // 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
+ 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));
+ }
+ }
+
+ // append(elem);
+
+ m_elemStack.push(elem);
+
+ m_currentNode = elem;
+
+ // append(elem);
+ }
+ catch(java.lang.Exception de)
+ {
+ // de.printStackTrace();
+ throw new org.xml.sax.SAXException(de);
+ }
+
+ }
+
+ /**
+
+
+
+ * 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
+ */
+ public void endElement(String ns, String localName, String name)
+ throws org.xml.sax.SAXException
+ {
+ m_elemStack.pop();
+ 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.
+ */
+ 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.
+ * @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)
+ {
+ cdata(ch, start, length);
+
+ return;
+ }
+
+ 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);
+ }
+ }
+
+ /**
+ * 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
+
+
+ String s = new String(ch, start, length);
+
+ append(m_doc.createProcessingInstruction("xslt-next-is-raw",
+ "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 '%'.
+ * @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
+ {
+
+ // Almost certainly the wrong behavior...
+ // entityReference(name);
+ }
+
+ /**
+ * Report the end of an entity.
+ *
+ * @param name The name of the entity that is ending.
+ * @see #startEntity
+ */
+ public void endEntity(String name) throws org.xml.sax.SAXException{}
+
+ /**
+ * Receive notivication of a entityReference.
+ *
+ * @param name name of the entity reference
+ */
+ 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.
+ * @see #characters
+ */
+ public void ignorableWhitespace(char ch[], int start, int length)
+ throws org.xml.sax.SAXException
+ {
+ if(isOutsideDocElem())
+ return; // avoid DOM006 Hierarchy request error
+
+ String s = new String(ch, start, length);
+
+ append(m_doc.createTextNode(s));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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.
+ */
+ public void processingInstruction(String target, String data)
+ 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.
+ */
+ public void comment(char ch[], int start, int length) throws org.xml.sax.SAXException
+ {
+ append(m_doc.createComment(new String(ch, start, length)));
+ }
+
+ /** 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
+ {
+ m_inCData = true;
+ append(m_doc.createCDATASection(""));
+ }
+
+ /**
+ * Report the end of a CDATA section.
+ *
+ * @see #startCDATA
+ */
+ 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.
+ * @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
+
+ String s = new String(ch, start, length);
+
+ // XXX [email protected]: modified from the original, to accomodate TagSoup.
+ Node n = m_currentNode.getLastChild();
+ if (n instanceof CDATASection)
+ ((CDATASection)n).appendData(s);
+ else if (n instanceof Comment)
+ ((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.
+ * @see #endDTD
+ * @see #startEntity
+ */
+ public void startDTD(String name, String publicId, String systemId)
+ 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
+ {
+
+ // 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.
+ * @see #endPrefixMapping
+ * @see #startElement
+ */
+ public void startPrefixMapping(String prefix, String uri)
+ 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);
+ }
+ }
+ */
+ }
+
+ /**
+ * 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.
+ * @see #startPrefixMapping
+ * @see #endElement
+ */
+ 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 '%'.
+ */
+ public void skippedEntity(String name) throws org.xml.sax.SAXException{}
+}
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
new file mode 100644
index 000000000..c6b30aaa1
--- /dev/null
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java
@@ -0,0 +1,186 @@
+/**
+ * Copyright 2005 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.nutch.parse.html;
+
+import java.net.URL;
+import java.util.Properties;
+
+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.
+ */
+public class HTMLMetaProcessor {
+
+ /**
+ * 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>.
+ */
+ 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) {
+
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+
+ if ("body".equalsIgnoreCase(node.getNodeName())) {
+ // META tags should not be under body
+ return;
+ }
+
+ if ("meta".equalsIgnoreCase(node.getNodeName())) {
+ NamedNodeMap attrs = node.getAttributes();
+ Node nameNode = attrs.getNamedItem("name");
+ Node equivNode = attrs.getNamedItem("http-equiv");
+ Node contentNode = attrs.getNamedItem("content");
+
+ if (nameNode != null) {
+ if (contentNode != null) {
+ String name = nameNode.getNodeValue().toLowerCase();
+ metaTags.getGeneralTags().setProperty(name, contentNode.getNodeValue());
+ if ("robots".equals(name)) {
+
+ if (contentNode != null) {
+ 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();
+ }
+ }
+
+ } // end if (name == robots)
+ }
+ }
+
+ if (equivNode != null) {
+ if (contentNode != null) {
+ String name = equivNode.getNodeValue().toLowerCase();
+ String content = contentNode.getNodeValue();
+ metaTags.getHttpEquivTags().setProperty(name, content);
+ if ("pragma".equals(name)) {
+ content = content.toLowerCase();
+ int index = content.indexOf("no-cache");
+ 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);
+ try {
+ metaTags.setRefreshTime(Integer.parseInt(time));
+ // skip this if we couldn't parse the time
+ metaTags.setRefresh(true);
+ } catch (Exception e) {
+ ;
+ }
+ 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
+ idx = content.indexOf(';') + 1;
+ } else idx += 4;
+ if (idx != -1) {
+ String url = content.substring(idx);
+ URL refreshUrl = null;
+ try {
+ refreshUrl = new URL(url);
+ } catch (Exception e) {
+ // this has to be an absolute url!
+ if (!url.startsWith("/")) url = "/" + url;
+ try {
+ refreshUrl = new URL(currURL, url);
+ } catch (Exception e1) {
+ ;
+ }
+ }
+ if (refreshUrl == null) metaTags.setRefresh(false);
+ metaTags.setRefreshHref(refreshUrl);
+ }
+ }
+ }
+ }
+ }
+
+ } else if ("base".equalsIgnoreCase(node.getNodeName())) {
+ NamedNodeMap attrs = node.getAttributes();
+ Node hrefNode = attrs.getNamedItem("href");
+
+ if (hrefNode != null) {
+ String urlString = hrefNode.getNodeValue();
+
+ URL url = null;
+ try {
+ if (currURL == null)
+ url = new URL(urlString);
+ else
+ url = new URL(currURL, urlString);
+ } catch (Exception e) {
+ ;
+ }
+
+ if (url != null)
+ metaTags.setBaseHref(url);
+ }
+
+ }
+
+ }
+
+ NodeList children = node.getChildNodes();
+ if (children != null) {
+ int len = children.getLength();
+ for (int i = 0; i < len; i++) {
+ getMetaTagsHelper(metaTags, children.item(i), currURL);
+ }
+ }
+ }
+
+}
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 2a34a04ed..1e85fd9ef 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
@@ -28,14 +28,11 @@ import org.cyberneko.html.parsers.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.w3c.dom.*;
-import org.w3c.dom.html.*;
import org.apache.html.dom.*;
-import org.apache.nutch.fetcher.FetcherOutput;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.*;
import org.apache.nutch.parse.*;
-import org.apache.nutch.parse.html.RobotsMetaProcessor.*;
public class HtmlParser implements Parser {
@@ -52,6 +49,8 @@ public class HtmlParser implements Parser {
private static Pattern charsetPattern =
Pattern.compile("charset=\\s*([a-z][_\\-0-9a-z]*)",
Pattern.CASE_INSENSITIVE);
+
+ private static String parserImpl = NutchConf.get().get("parser.html.impl", "neko");
/**
* Given a <code>byte[]</code> representing an html file of an
@@ -94,22 +93,14 @@ public class HtmlParser implements Parser {
private static String defaultCharEncoding =
NutchConf.get().get("parser.character.encoding.default", "windows-1252");
- public Parse getParse(Content content) throws ParseException {
- DOMParser parser = new DOMParser();
-
- // some plugins, e.g., creativecommons, need to examine html comments
- try {
- parser.setFeature("http://apache.org/xml/features/include-comments",
- true);
- } catch (SAXException e) {}
-
- RobotsMetaIndicator robotsMeta = new RobotsMetaIndicator();
+ public Parse getParse(Content content) {
+ HTMLMetaTags metaTags = new HTMLMetaTags();
URL base;
try {
base = new URL(content.getBaseUrl());
} catch (MalformedURLException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
}
String text = "";
@@ -120,19 +111,18 @@ public class HtmlParser implements Parser {
// check that contentType is one we can handle
String contentType = content.getContentType();
if (!"".equals(contentType) && !contentType.startsWith("text/html"))
- throw new ParseException("Content-Type not text/html: " + contentType);
+ return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_INVALID_FORMAT,
+ "Content-Type not text/html: " + contentType).getEmptyParse();
// parse the content
DocumentFragment root;
try {
byte[] contentInOctets = content.getContent();
- InputSource input =
- new InputSource(new ByteArrayInputStream(contentInOctets));
+ InputSource input = new InputSource(new ByteArrayInputStream(contentInOctets));
String encoding = StringUtil.parseCharacterEncoding(contentType);
if (encoding!=null) {
metadata.put("OriginalCharEncoding", encoding);
if ((encoding = StringUtil.resolveEncodingAlias(encoding)) != null) {
- input.setEncoding(encoding);
metadata.put("CharEncodingForConversion", encoding);
LOG.fine(base + ": setting encoding to " + encoding);
}
@@ -144,7 +134,6 @@ public class HtmlParser implements Parser {
if (encoding!=null) {
metadata.put("OriginalCharEncoding", encoding);
if ((encoding = StringUtil.resolveEncodingAlias(encoding)) != null) {
- input.setEncoding(encoding);
metadata.put("CharEncodingForConversion", encoding);
LOG.fine(base + ": setting encoding to " + encoding);
}
@@ -158,33 +147,29 @@ public class HtmlParser implements Parser {
// (e.g. se: windows-1252, kr: x-windows-949, cn: gb18030, tw: big5
// doesn't work for jp because euc-jp and shift_jis have about the
// same share)
-
+ encoding = defaultCharEncoding;
metadata.put("CharEncodingForConversion", defaultCharEncoding);
- input.setEncoding(defaultCharEncoding);
LOG.fine(base + ": falling back to " + defaultCharEncoding);
}
-
+ input.setEncoding(encoding);
LOG.fine("Parsing...");
- parser.parse(input);
-
- // convert Document to DocumentFragment
- HTMLDocumentImpl doc = (HTMLDocumentImpl)parser.getDocument();
- doc.setErrorChecking(false);
- root = doc.createDocumentFragment();
- root.appendChild(doc.getDocumentElement());
+ root = parse(input);
} catch (IOException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
} catch (DOMException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
} catch (SAXException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
+ } catch (Exception e) {
+ e.printStackTrace();
+ return new ParseStatus(e).getEmptyParse();
}
// get meta directives
- RobotsMetaProcessor.getRobotsMetaDirectives(robotsMeta, root, base);
-
+ HTMLMetaProcessor.getMetaTags(metaTags, root, base);
+ LOG.info("Meta tags for " + base + ": " + metaTags.toString());
// check meta directives
- if (!robotsMeta.getNoIndex()) { // okay to index
+ if (!metaTags.getNoIndex()) { // okay to index
StringBuffer sb = new StringBuffer();
LOG.fine("Getting text...");
DOMContentUtils.getText(sb, root); // extract text
@@ -195,7 +180,7 @@ public class HtmlParser implements Parser {
title = sb.toString().trim();
}
- if (!robotsMeta.getNoFollow()) { // okay to follow links
+ if (!metaTags.getNoFollow()) { // okay to follow links
ArrayList l = new ArrayList(); // extract outlinks
URL baseTag = DOMContentUtils.getBase(root);
LOG.fine("Getting links...");
@@ -204,20 +189,78 @@ public class HtmlParser implements Parser {
LOG.fine("found "+outlinks.length+" outlinks in "+content.getUrl());
}
- if (!robotsMeta.getNoCache()) { // okay to cache
+ if (!metaTags.getNoCache()) { // okay to cache
// ??? FIXME ???
}
// copy content metadata through
metadata.putAll(content.getMetadata());
-
- ParseData parseData = new ParseData(title, outlinks, metadata);
+ ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);
+ if (metaTags.getRefresh()) {
+ status.setMinorCode(ParseStatus.SUCCESS_REDIRECT);
+ status.setMessage(metaTags.getRefreshHref().toString());
+ }
+ ParseData parseData = new ParseData(status, title, outlinks, metadata);
Parse parse = new ParseImpl(text, parseData);
// run filters on parse
- return HtmlParseFilters.filter(content, parse, root);
+ return HtmlParseFilters.filter(content, parse, metaTags, root);
}
+ private DocumentFragment parse(InputSource input) throws Exception {
+ if (parserImpl.equalsIgnoreCase("tagsoup"))
+ return parseTagSoup(input);
+ else return parseNeko(input);
+ }
+
+ private DocumentFragment parseTagSoup(InputSource input) throws Exception {
+ HTMLDocumentImpl doc = new HTMLDocumentImpl();
+ DocumentFragment frag = doc.createDocumentFragment();
+ DOMBuilder builder = new DOMBuilder(doc, frag);
+ org.ccil.cowan.tagsoup.Parser reader = new org.ccil.cowan.tagsoup.Parser();
+ reader.setContentHandler(builder);
+ reader.setFeature(reader.ignoreBogonsFeature, true);
+ reader.setFeature(reader.bogonsEmptyFeature, false);
+ 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();
+ // some plugins, e.g., creativecommons, need to examine html comments
+ try {
+ parser.setFeature("http://apache.org/xml/features/include-comments",
+ true);
+ parser.setFeature("http://apache.org/xml/features/augmentations",
+ true);
+ 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/report-errors",
+ true);
+ } catch (SAXException e) {}
+ // convert Document to DocumentFragment
+ HTMLDocumentImpl doc = new HTMLDocumentImpl();
+ doc.setErrorChecking(false);
+ DocumentFragment res = doc.createDocumentFragment();
+ DocumentFragment frag = doc.createDocumentFragment();
+ parser.parse(input, frag);
+ res.appendChild(frag);
+
+ try {
+ while(true) {
+ frag = doc.createDocumentFragment();
+ parser.parse(input, frag);
+ if (!frag.hasChildNodes()) break;
+ LOG.info(" - new frag, " + frag.getChildNodes().getLength() + " nodes.");
+ res.appendChild(frag);
+ }
+ } catch (Exception x) { x.printStackTrace();};
+ return res;
+ }
+
public static void main(String[] args) throws Exception {
LOG.setLevel(Level.FINE);
String name = args[0];
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/RobotsMetaProcessor.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/RobotsMetaProcessor.java
deleted file mode 100644
index c3470ac7e..000000000
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/RobotsMetaProcessor.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/**
- * Copyright 2005 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.nutch.parse.html;
-
-import java.net.URL;
-
-import org.w3c.dom.*;
-import org.w3c.dom.html.*;
-import org.apache.html.dom.*;
-
-/**
- * Class for parsing META Directives from DOM trees. This class
- * currently handles Robots META directives (all, none, nofollow,
- * noindex), finding BASE HREF tags, and HTTP-EQUIV no-cache
- * instructions.
- */
-public class RobotsMetaProcessor {
-
- /**
- * Utility class with indicators for the robots directives "noindex"
- * and "nofollow", and HTTP-EQUIV/no-cache
- */
- public static class RobotsMetaIndicator {
- private boolean noIndex= false;
- private boolean noFollow= false;
- private boolean noCache= false;
- private URL baseHref= null;
-
- /**
- * Sets <code>noIndex</code>, <code>noFollow</code> and
- * <code>noCache</code> to <code>false</code>.
- */
- public void reset() {
- noIndex= false;
- noFollow= false;
- noCache= false;
- baseHref= null;
- }
-
- /**
- * Sets <code>noFollow</code> to <code>true</code>.
- */
- public void setNoFollow() {
- noFollow= true;
- }
-
- /**
- * Sets <code>noIndex</code> to <code>true</code>.
- */
- public void setNoIndex() {
- noIndex= true;
- }
-
- /**
- * Sets <code>noCache</code> to <code>true</code>.
- */
- public void setNoCache() {
- noCache= true;
- }
-
- /**
- * Sets the <code>baseHref</code>.
- */
- public void setBaseHref(URL baseHref) {
- this.baseHref= baseHref;
- }
-
- /**
- * Returns the current value of <code>noIndex</code>.
- */
- public boolean getNoIndex() {
- return noIndex;
- }
-
- /**
- * Returns the current value of <code>noFollow</code>.
- */
- public boolean getNoFollow() {
- return noFollow;
- }
-
- /**
- * Returns the current value of <code>noCache</code>.
- */
- public boolean getNoCache() {
- return noCache;
- }
-
- /**
- * Returns the <code>baseHref</code>, if set, or <code>null</code>
- * otherwise.
- */
- public URL getBaseHref() {
- return baseHref;
- }
-
- }
-
- /**
- * 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 getRobotsMetaDirectives(
- RobotsMetaIndicator robotsMeta, Node node, URL currURL) {
-
- robotsMeta.reset();
- getRobotsMetaDirectivesHelper(robotsMeta, node, currURL);
- }
-
- private static final void getRobotsMetaDirectivesHelper(
- RobotsMetaIndicator robotsMeta, Node node, URL currURL) {
-
- if (node.getNodeType() == Node.ELEMENT_NODE) {
-
- if ("BODY".equals(node.getNodeName())) {
- // META tags should not be under body
- return;
- }
-
- if ("META".equals(node.getNodeName())) {
- NamedNodeMap attrs= node.getAttributes();
- Node nameNode= attrs.getNamedItem("name");
-
- if (nameNode != null) {
- if ("robots".equalsIgnoreCase(nameNode.getNodeValue())) {
- Node contentNode= attrs.getNamedItem("content");
-
- if (contentNode != null) {
- String directives=
- contentNode.getNodeValue().toLowerCase();
- int index= directives.indexOf("none");
-
- if (index >= 0) {
- robotsMeta.setNoIndex();
- robotsMeta.setNoFollow();
- }
-
- index= directives.indexOf("all");
- if (index >= 0) {
- // do nothing...
- }
-
- index= directives.indexOf("noindex");
- if (index >= 0) {
- robotsMeta.setNoIndex();
- }
-
- index= directives.indexOf("nofollow");
- if (index >= 0) {
- robotsMeta.setNoFollow();
- }
- }
-
- } // end if (name == robots)
- } // end if (nameNode != null)
-
- Node HTTPEquivNode= attrs.getNamedItem("http-equiv");
-
- if ( (HTTPEquivNode != null)
- && ("Pragma".equalsIgnoreCase(HTTPEquivNode.getNodeValue())) ) {
- Node contentNode= attrs.getNamedItem("content");
-
- if (contentNode != null) {
- String content= contentNode.getNodeValue().toLowerCase();
- int index= content.indexOf("no-cache");
- if (index >= 0)
- robotsMeta.setNoCache();
- }
-
- }
-
- } else if ("BASE".equalsIgnoreCase(node.getNodeName())) {
- NamedNodeMap attrs= node.getAttributes();
- Node hrefNode= attrs.getNamedItem("href");
-
- if (hrefNode != null) {
- String urlString= hrefNode.getNodeValue();
-
- URL url= null;
- try {
- if (currURL == null)
- url= new URL(urlString);
- else
- url= new URL(currURL, urlString);
- } catch (Exception e) {
- ;
- }
-
- if (url != null)
- robotsMeta.setBaseHref(url);
- }
-
- }
-
- }
-
- NodeList children = node.getChildNodes();
- if ( children != null ) {
- int len = children.getLength();
- for ( int i = 0; i < len; i++ ) {
- getRobotsMetaDirectivesHelper(robotsMeta, children.item(i), currURL);
- }
- }
- }
-
-}
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
new file mode 100644
index 000000000..cc226ead6
--- /dev/null
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/XMLCharacterRecognizer.java
@@ -0,0 +1,113 @@
+/*
+ * XXX [email protected]: This class is copied verbatim from Xalan-J 2.6.0
+ * XXX distribution, org.apache.xml.utils.XMLCharacterRecognizer,
+ * XXX in order to avoid dependency on Xalan.
+ */
+
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * $Id: XMLCharacterRecognizer.java,v 1.7 2004/02/17 04:21:14 minchau Exp $
+ */
+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.
+ * @xsl.usage internal
+ */
+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.
+ * @return =true if <var>ch</var> is XML whitespace; otherwise =false.
+ */
+ 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.
+ */
+ public static boolean isWhiteSpace(char ch[], int start, int length)
+ {
+
+ int end = start + length;
+
+ for (int s = start; s < end; s++)
+ {
+ if (!isWhiteSpace(ch[s]))
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Tell if the string is 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)
+ {
+
+ int n = buf.length();
+
+ for (int i = 0; i < n; i++)
+ {
+ if (!isWhiteSpace(buf.charAt(i)))
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Tell if the string is whitespace.
+ *
+ * @param buf StringBuffer to check as XML whitespace.
+ * @return True if characters in buffer are XML whitespace, false otherwise
+ */
+ public static boolean isWhiteSpace(String s)
+ {
+
+ if(null != s)
+ {
+ int n = s.length();
+
+ for (int i = 0; i < n; i++)
+ {
+ if (!isWhiteSpace(s.charAt(i)))
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+}
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 8824cec9b..f12fb3f88 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
@@ -205,6 +205,7 @@ public class TestDOMContentUtils extends TestCase {
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", ""),
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 218df8050..fa98029f5 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
@@ -18,7 +18,8 @@ package org.apache.nutch.parse.html;
import junit.framework.TestCase;
-import org.apache.nutch.parse.html.RobotsMetaProcessor.*;
+import org.apache.nutch.parse.HTMLMetaTags;
+import org.apache.nutch.parse.html.HTMLMetaProcessor.*;
import java.io.ByteArrayInputStream;
import java.net.URL;
@@ -28,7 +29,7 @@ import org.xml.sax.*;
import org.w3c.dom.*;
import org.apache.html.dom.*;
-/** Unit tests for RobotsMetaProcessor. */
+/** Unit tests for HTMLMetaProcessor. */
public class TestRobotsMetaProcessor extends TestCase {
public TestRobotsMetaProcessor(String name) {
super(name);
@@ -157,8 +158,8 @@ public class TestRobotsMetaProcessor extends TestCase {
e.printStackTrace();
}
- RobotsMetaIndicator robotsMeta= new RobotsMetaIndicator();
- RobotsMetaProcessor.getRobotsMetaDirectives(robotsMeta, node,
+ HTMLMetaTags robotsMeta= new HTMLMetaTags();
+ HTMLMetaProcessor.getMetaTags(robotsMeta, node,
currURLsAndAnswers[i][0]);
assertTrue("got index wrong on test " + i,
diff --git a/src/plugin/parse-js/build.xml b/src/plugin/parse-js/build.xml
new file mode 100644
index 000000000..9f54071b4
--- /dev/null
+++ b/src/plugin/parse-js/build.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+
+<project name="parse-js" default="jar">
+
+ <import file="../build-plugin.xml"/>
+
+</project>
diff --git a/src/plugin/parse-js/plugin.xml b/src/plugin/parse-js/plugin.xml
new file mode 100644
index 000000000..2f55d61e6
--- /dev/null
+++ b/src/plugin/parse-js/plugin.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<plugin
+ id="parse-js"
+ name="JavaScript Parser"
+ version="1.0.0"
+ provider-name="nutch.org">
+
+ <extension-point
+ id="org.apache.nutch.parse.HtmlParseFilter"
+ name="HTML Parse Filter"/>
+
+ <runtime>
+ <library name="parse-js.jar">
+ <export name="*"/>
+ </library>
+ </runtime>
+
+ <extension id="org.apache.nutch.parse.js.JSParseFilter"
+ name="Parse JS Filter"
+ point="org.apache.nutch.parse.HtmlParseFilter">
+ <implementation id="JSParseFilter"
+ class="org.apache.nutch.parse.js.JSParseFilter"
+ contentType="application/x-javascript"
+ pathSuffix=""/>
+ </extension>
+
+</plugin>
diff --git a/src/plugin/parse-js/src/java/org/apache/nutch/package.html b/src/plugin/parse-js/src/java/org/apache/nutch/package.html
new file mode 100644
index 000000000..7dffe62bc
--- /dev/null
+++ b/src/plugin/parse-js/src/java/org/apache/nutch/package.html
@@ -0,0 +1,6 @@
+<html>
+<body>
+<p>A parser plugin and content filter to extract all (possible) links
+from JavaScript files and code snippets.</p>
+</body>
+</html>
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
new file mode 100644
index 000000000..b63e4392a
--- /dev/null
+++ b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
@@ -0,0 +1,226 @@
+package org.apache.nutch.parse.js;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.nutch.parse.HTMLMetaTags;
+import org.apache.nutch.parse.HtmlParseFilter;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseImpl;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.parse.Parser;
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.LogFormatter;
+import org.apache.oro.text.regex.MatchResult;
+import org.apache.oro.text.regex.Pattern;
+import org.apache.oro.text.regex.PatternCompiler;
+import org.apache.oro.text.regex.PatternMatcher;
+import org.apache.oro.text.regex.PatternMatcherInput;
+import org.apache.oro.text.regex.Perl5Compiler;
+import org.apache.oro.text.regex.Perl5Matcher;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+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
+ * by Stephan Strittmatter.
+ *
+ * @author Andrzej Bialecki &lt;[email protected]&gt;
+ */
+public class JSParseFilter implements HtmlParseFilter, Parser {
+ public static final Logger LOG =
+ LogFormatter.getLogger("org.apache.nutch.parse.js.JSParseFilter");
+
+ private static final int MAX_TITLE_LEN = 80;
+
+ public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {
+ String url = content.getBaseUrl();
+ ArrayList outlinks = new ArrayList();
+ walk(doc, parse, metaTags, url, outlinks);
+ if (outlinks.size() > 0) {
+ Outlink[] old = parse.getData().getOutlinks();
+ Properties metadata = parse.getData().getMetadata();
+ String title = parse.getData().getTitle();
+ List list = Arrays.asList(old);
+ outlinks.addAll(list);
+ ParseStatus status = parse.getData().getStatus();
+ String text = parse.getText();
+ Outlink[] newlinks = (Outlink[])outlinks.toArray(new Outlink[outlinks.size()]);
+ parse = new ParseImpl(text, new ParseData(status, title, newlinks, metadata));
+ }
+ return parse;
+ }
+
+ private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List 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();
+ 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');
+ script.append(nn.item(i).getNodeValue());
+ }
+ //LOG.info("script: language=" + lang + ", text: " + script.toString());
+ Outlink[] links = getJSLinks(script.toString(), base, base);
+ if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
+ // no other children of interest here, go one level up.
+ return;
+ }
+ } else {
+ // process all HTML 4.0 events, if present...
+ NamedNodeMap attrs = n.getAttributes();
+ int len = attrs.getLength();
+ for (int i = 0; i < len; i++) {
+ // Window: onload,onunload
+ // Form: onchange,onsubmit,onreset,onselect,onblur,onfocus
+ // Keyboard: onkeydown,onkeypress,onkeyup
+ // Mouse: onclick,ondbclick,onmousedown,onmouseout,onmousover,onmouseup
+ Node anode = attrs.item(i);
+ if (anode.getNodeName().startsWith("on")) {
+ Outlink[] links = getJSLinks(anode.getNodeValue(), base, base);
+ if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
+ }
+ }
+ }
+ }
+ NodeList nl = n.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ walk(nl.item(i), parse, metaTags, base, outlinks);
+ }
+ }
+
+ public Parse getParse(Content c) {
+ String type = c.getContentType();
+ if (type != null && !type.toLowerCase().startsWith("application/x-javascript"))
+ return new ParseStatus(ParseStatus.FAILED_INVALID_FORMAT,
+ "Content not JavaScript: " + type).getEmptyParse();
+ String script = new String(c.getContent());
+ Outlink[] outlinks = getJSLinks(script, c.getUrl(), c.getUrl());
+ 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;
+ title = script.substring(0, idx);
+ } else {
+ idx = Math.min(MAX_TITLE_LEN, script.length());
+ title = script.substring(0, idx);
+ }
+ Properties metadata = new Properties();
+ metadata.putAll(c.getMetadata());
+ ParseData pd = new ParseData(ParseStatus.STATUS_SUCCESS, title,
+ outlinks, metadata);
+ Parse parse = new ParseImpl(script, pd);
+ return parse;
+ }
+
+ 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*)";
+
+ /**
+ * This method extracts URLs from literals embedded in JavaScript.
+ */
+ private static Outlink[] getJSLinks(String plainText, String anchor, String base) {
+
+ final List outlinks = new ArrayList();
+ URL baseURL = null;
+
+ try {
+ baseURL = new URL(base);
+ } catch (Exception e) {
+ LOG.throwing(JSParseFilter.class.getName(), "getJSLinks", e);
+ }
+
+ try {
+ final PatternCompiler cp = new Perl5Compiler();
+ final Pattern pattern = cp.compile(STRING_PATTERN,
+ 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);
+ final PatternMatcher matcher = new Perl5Matcher();
+
+ final PatternMatcher matcher1 = new Perl5Matcher();
+ final PatternMatcherInput input = new PatternMatcherInput(plainText);
+
+ MatchResult result;
+ String url;
+
+ //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)) {
+ //LOG.fine(" - invalid '" + url + "'");
+ continue;
+ }
+ if (url.startsWith("www.")) {
+ url = "http://" + url;
+ } else url = new URL(baseURL, url).toString();
+ url = url.replaceAll("&amp;", "&");
+ LOG.fine(" - outlink from JS: '" + url + "'");
+ outlinks.add(new Outlink(url, anchor));
+ }
+ } catch (Exception ex) {
+ // if it is a malformed URL we just throw it away and continue with
+ // extraction.
+ LOG.throwing(JSParseFilter.class.getName(), "getJSLinks", ex);
+ }
+
+ final Outlink[] retval;
+
+ //create array of the Outlinks
+ if (outlinks != null && outlinks.size() > 0) {
+ retval = (Outlink[]) outlinks.toArray(new Outlink[0]);
+ } else {
+ retval = new Outlink[0];
+ }
+
+ return retval;
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 2) {
+ System.err.println(JSParseFilter.class.getName() + " file.js baseURL");
+ return;
+ }
+ InputStream in = new FileInputStream(args[0]);
+ BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
+ StringBuffer sb = new StringBuffer();
+ String line = null;
+ while ((line = br.readLine()) != null) sb.append(line + "\n");
+ Outlink[] links = getJSLinks(sb.toString(), args[1], args[1]);
+ System.out.println("Outlinks extracted: " + links.length);
+ for (int i = 0; i < links.length; i++)
+ System.out.println(" - " + links[i]);
+ }
+}
diff --git a/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java b/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java
index 3e0e946cf..6df02ac8c 100644
--- a/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java
+++ b/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java
@@ -18,6 +18,7 @@ package org.apache.nutch.parse.msword;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseData;
@@ -52,13 +53,13 @@ public class MSWordParser implements Parser {
public MSWordParser () {}
- public Parse getParse(Content content) throws ParseException {
+ public Parse getParse(Content content) {
// check that contentType is one we can handle
String contentType = content.getContentType();
if (contentType != null && !contentType.startsWith("application/msword"))
- throw new ParseException(
- "Content-Type not application/msword: "+contentType);
+ return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_INVALID_FORMAT,
+ "Content-Type not application/msword: " + contentType).getEmptyParse();
String text = null;
String title = null;
@@ -71,8 +72,9 @@ public class MSWordParser implements Parser {
String contentLength = content.get("Content-Length");
if (contentLength != null
&& raw.length != Integer.parseInt(contentLength)) {
- throw new ParseException("Content truncated at "+raw.length
- +" bytes. Parser can't handle incomplete msword file.");
+ return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
+ "Content truncated at " + raw.length
+ +" bytes. Parser can't handle incomplete msword file.").getEmptyParse();
}
WordExtractor extractor = new WordExtractor();
@@ -86,13 +88,14 @@ public class MSWordParser implements Parser {
extractor = null;
} catch (ParseException e) {
- throw e;
+ return new ParseStatus(e).getEmptyParse();
} catch (FastSavedException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
} catch (PasswordProtectedException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
} catch (Exception e) { // run time exception
- throw new ParseException("Can't be handled as msword document. "+e);
+ return new ParseStatus(ParseStatus.FAILED,
+ "Can't be handled as msword document. " + e).getEmptyParse();
} finally {
// nothing so far
}
@@ -116,7 +119,7 @@ public class MSWordParser implements Parser {
// collect outlink
Outlink[] outlinks = new Outlink[0];
- ParseData parseData = new ParseData(title, outlinks, metadata);
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metadata);
return new ParseImpl(text, parseData);
// any filter?
//return HtmlParseFilters.filter(content, parse, root);
diff --git a/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java b/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java
index cbf76c402..9065945d6 100644
--- a/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java
+++ b/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java
@@ -64,7 +64,7 @@ public class TestMSWordParser extends TestCase {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
protocol = ProtocolFactory.getProtocol(urlString);
- content = protocol.getContent(urlString);
+ content = protocol.getProtocolOutput(urlString).getContent();
parser = ParserFactory.getParser(content.getContentType(), urlString);
parse = parser.getParse(content);
diff --git a/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java b/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java
index cb52a6fc9..3e789117c 100644
--- a/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java
+++ b/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java
@@ -27,6 +27,7 @@ import org.pdfbox.exceptions.InvalidPasswordException;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseData;
@@ -79,13 +80,13 @@ public class PdfParser implements Parser {
rootLogger.addAppender(appender);
}
- public Parse getParse(Content content) throws ParseException {
+ public Parse getParse(Content content) {
// check that contentType is one we can handle
String contentType = content.getContentType();
if (contentType != null && !contentType.startsWith("application/pdf"))
- throw new ParseException(
- "Content-Type not application/pdf: "+contentType);
+ return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_INVALID_FORMAT,
+ "Content-Type not application/pdf: " + contentType).getEmptyParse();
// in memory representation of pdf file
PDDocument pdf = null;
@@ -100,8 +101,9 @@ public class PdfParser implements Parser {
String contentLength = content.get("Content-Length");
if (contentLength != null
&& raw.length != Integer.parseInt(contentLength)) {
- throw new ParseException("Content truncated at "+raw.length
- +" bytes. Parser can't handle incomplete pdf file.");
+ return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,
+ "Content truncated at "+raw.length
+ +" bytes. Parser can't handle incomplete pdf file.").getEmptyParse();
}
PDFParser parser = new PDFParser(
@@ -134,14 +136,15 @@ public class PdfParser implements Parser {
// formatDate(info.getCreationDate())
// formatDate(info.getModificationDate())
- } catch (ParseException e) {
- throw e;
} catch (CryptographyException e) {
- throw new ParseException("Error decrypting document. "+e);
+ return new ParseStatus(ParseStatus.FAILED,
+ "Error decrypting document. " + e).getEmptyParse();
} catch (InvalidPasswordException e) {
- throw new ParseException("Can't decrypt document. "+e);
+ return new ParseStatus(ParseStatus.FAILED,
+ "Can't decrypt document - invalid password. " + e).getEmptyParse();
} catch (Exception e) { // run time exception
- throw new ParseException("Can't be handled as pdf document. "+e);
+ return new ParseStatus(ParseStatus.FAILED,
+ "Can't be handled as pdf document. " + e).getEmptyParse();
} finally {
try {
if (pdf != null)
@@ -164,7 +167,7 @@ public class PdfParser implements Parser {
Properties metadata = new Properties();
metadata.putAll(content.getMetadata()); // copy through
- ParseData parseData = new ParseData(title, outlinks, metadata);
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metadata);
return new ParseImpl(text, parseData);
// any filter?
//return HtmlParseFilters.filter(content, parse, root);
diff --git a/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java b/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java
index 31675478b..1d5f3563d 100644
--- a/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java
+++ b/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java
@@ -64,7 +64,7 @@ public class TestPdfParser extends TestCase {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
protocol = ProtocolFactory.getProtocol(urlString);
- content = protocol.getContent(urlString);
+ content = protocol.getProtocolOutput(urlString).getContent();
parser = ParserFactory.getParser(content.getContentType(), urlString);
parse = parser.getParse(content);
diff --git a/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java b/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java
index 605e51506..7e5d74666 100644
--- a/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java
+++ b/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java
@@ -23,12 +23,12 @@ import org.apache.nutch.parse.*;
import org.apache.nutch.util.*;
public class TextParser implements Parser {
- public Parse getParse(Content content) throws ParseException {
+ public Parse getParse(Content content) {
// copy content meta data through
Properties metadata = new Properties();
metadata.putAll(content.getMetadata());
- ParseData parseData = new ParseData("", new Outlink[0], metadata);
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "", new Outlink[0], metadata);
String encoding =
StringUtil.parseCharacterEncoding(content.getContentType());
@@ -37,7 +37,7 @@ public class TextParser implements Parser {
try { // try to use named encoding
text = new String(content.getContent(), encoding);
} catch (java.io.UnsupportedEncodingException e) {
- throw new ParseException(e);
+ return new ParseStatus(e).getEmptyParse();
}
} else {
// FIXME: implement charset detector. This code causes problem when
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 cef8187c7..0ca032682 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
@@ -17,24 +17,24 @@
package org.apache.nutch.protocol.file;
+import org.apache.nutch.db.Page;
import org.apache.nutch.net.protocols.HttpDateFormat;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.pagedb.FetchListEntry;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
+import org.apache.nutch.protocol.ProtocolOutput;
+import org.apache.nutch.protocol.ProtocolStatus;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.net.MalformedURLException;
import java.net.URL;
-import java.io.InputStream;
-// 20040528, xing, disabled for now
-//import java.io.Reader;
-import java.io.IOException;
-
/************************************
* File.java deals with file: scheme.
*
@@ -65,9 +65,20 @@ public class File implements Protocol {
}
/** Set the point at which content is truncated. */
- public void setMaxContentLength(int length) {this.maxContentLength = length;}
+ public void setMaxContentLength(int length) {maxContentLength = length;}
- public Content getContent(String urlString) throws FileException {
+ public ProtocolOutput getProtocolOutput(String urlString) {
+ ProtocolOutput output = null;
+ try {
+ return getProtocolOutput(new FetchListEntry(true,
+ new Page(urlString, 1.0f), new String[0]));
+ } catch (MalformedURLException mue) {
+ return new ProtocolOutput(null, new ProtocolStatus(mue));
+ }
+ }
+
+ public ProtocolOutput getProtocolOutput(FetchListEntry fle) {
+ String urlString = fle.getUrl().toString();
try {
URL url = new URL(urlString);
@@ -80,7 +91,7 @@ public class File implements Protocol {
int code = response.getCode();
if (code == 200) { // got a good response
- return response.toContent(); // return it
+ return new ProtocolOutput(response.toContent()); // return it
} else if (code >= 300 && code < 400) { // handle redirect
if (redirects == MAX_REDIRECTS)
@@ -94,8 +105,8 @@ public class File implements Protocol {
throw new FileError(code);
}
}
- } catch (IOException e) {
- throw new FileException(e);
+ } catch (Exception e) {
+ return new ProtocolOutput(null, new ProtocolStatus(e));
}
}
@@ -139,7 +150,7 @@ public class File implements Protocol {
// set log level
LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));
- Content content = file.getContent(urlString);
+ Content content = file.getProtocolOutput(urlString).getContent();
System.err.println("Content-Type: " + content.getContentType());
System.err.println("Content-Length: " + content.get("Content-Length"));
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 e0dbe6540..ea6a5003b 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
@@ -19,22 +19,24 @@ package org.apache.nutch.protocol.ftp;
import org.apache.commons.net.ftp.FTPFileEntryParser;
+import org.apache.nutch.db.Page;
import org.apache.nutch.net.protocols.HttpDateFormat;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.pagedb.FetchListEntry;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
+import org.apache.nutch.protocol.ProtocolOutput;
+import org.apache.nutch.protocol.ProtocolStatus;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.net.MalformedURLException;
import java.net.URL;
-import java.io.InputStream;
-// 20040528, xing, disabled for now
-//import java.io.Reader;
import java.io.IOException;
/************************************
@@ -91,13 +93,13 @@ public class Ftp implements Protocol {
}
/** Set the timeout. */
- public void setTimeout(int timeout) {
- this.timeout = timeout;
+ public void setTimeout(int to) {
+ timeout = to;
}
/** Set the point at which content is truncated. */
public void setMaxContentLength(int length) {
- this.maxContentLength = length;
+ maxContentLength = length;
}
/** Set followTalk */
@@ -110,7 +112,18 @@ public class Ftp implements Protocol {
this.keepConnection = keepConnection;
}
- public Content getContent(String urlString) throws FtpException {
+ public ProtocolOutput getProtocolOutput(String urlString) {
+ ProtocolOutput output = null;
+ try {
+ return getProtocolOutput(new FetchListEntry(true,
+ new Page(urlString, 1.0f), new String[0]));
+ } catch (MalformedURLException mue) {
+ return new ProtocolOutput(null, new ProtocolStatus(mue));
+ }
+ }
+
+ public ProtocolOutput getProtocolOutput(FetchListEntry fle) {
+ String urlString = fle.getUrl().toString();
try {
URL url = new URL(urlString);
@@ -123,7 +136,7 @@ public class Ftp implements Protocol {
int code = response.getCode();
if (code == 200) { // got a good response
- return response.toContent(); // return it
+ return new ProtocolOutput(response.toContent()); // return it
} else if (code >= 300 && code < 400) { // handle redirect
if (redirects == MAX_REDIRECTS)
@@ -137,8 +150,8 @@ public class Ftp implements Protocol {
throw new FtpError(code);
}
}
- } catch (IOException e) {
- throw new FtpException(e);
+ } catch (Exception e) {
+ return new ProtocolOutput(null, new ProtocolStatus(e));
}
}
@@ -205,7 +218,7 @@ public class Ftp implements Protocol {
// set log level
LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));
- Content content = ftp.getContent(urlString);
+ Content content = ftp.getProtocolOutput(urlString).getContent();
System.err.println("Content-Type: " + content.getContentType());
System.err.println("Content-Length: " + content.get("Content-Length"));
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 d38114989..cdde0824a 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
@@ -16,7 +16,7 @@
package org.apache.nutch.protocol.http;
-import java.io.*;
+import java.net.MalformedURLException;
import java.net.URL;
import java.net.InetAddress;
import java.net.UnknownHostException;
@@ -28,6 +28,8 @@ import java.util.logging.Logger;
import org.apache.nutch.util.LogFormatter;
import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.db.Page;
+import org.apache.nutch.pagedb.FetchListEntry;
import org.apache.nutch.protocol.*;
/** An implementation of the Http protocol. */
@@ -170,7 +172,18 @@ public class Http implements Protocol {
}
}
- public Content getContent(String urlString) throws ProtocolException {
+ public ProtocolOutput getProtocolOutput(String urlString) {
+ ProtocolOutput output = null;
+ try {
+ return getProtocolOutput(new FetchListEntry(true,
+ new Page(urlString, 1.0f), new String[0]));
+ } catch (MalformedURLException mue) {
+ return new ProtocolOutput(null, new ProtocolStatus(mue));
+ }
+ }
+
+ public ProtocolOutput getProtocolOutput(FetchListEntry fle) {
+ String urlString = fle.getUrl().toString();
try {
URL url = new URL(urlString);
@@ -191,7 +204,7 @@ public class Http implements Protocol {
int code = response.getCode();
if (code == 200) { // got a good response
- return response.toContent(); // return it
+ return new ProtocolOutput(response.toContent()); // return it
} else if (code == 410) { // page is gone
throw new ResourceGone(url, "Http: " + code);
@@ -207,8 +220,8 @@ public class Http implements Protocol {
throw new HttpError(code);
}
}
- } catch (IOException e) {
- throw new HttpException(e);
+ } catch (Exception e) {
+ return new ProtocolOutput(null, new ProtocolStatus(e));
}
}
@@ -285,7 +298,7 @@ public class Http implements Protocol {
LOG.setLevel(Level.FINE);
}
- Content content = http.getContent(url);
+ Content content = http.getProtocolOutput(url).getContent();
System.out.println("Content Type: " + content.getContentType());
System.out.println("Content Length: " + content.get("Content-Length"));
diff --git a/src/plugin/protocol-httpclient/build.xml b/src/plugin/protocol-httpclient/build.xml
new file mode 100644
index 000000000..146415550
--- /dev/null
+++ b/src/plugin/protocol-httpclient/build.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+
+<project name="protocol-httpclient" default="jar">
+
+ <import file="../build-plugin.xml"/>
+
+</project>
diff --git a/src/plugin/protocol-httpclient/lib/commons-codec.jar b/src/plugin/protocol-httpclient/lib/commons-codec.jar
new file mode 100644
index 000000000..cce1e07c7
Binary files /dev/null and b/src/plugin/protocol-httpclient/lib/commons-codec.jar differ
diff --git a/src/plugin/protocol-httpclient/lib/commons-httpclient-3.0-rc2.jar b/src/plugin/protocol-httpclient/lib/commons-httpclient-3.0-rc2.jar
new file mode 100644
index 000000000..bea0a98a3
Binary files /dev/null and b/src/plugin/protocol-httpclient/lib/commons-httpclient-3.0-rc2.jar differ
diff --git a/src/plugin/protocol-httpclient/plugin.xml b/src/plugin/protocol-httpclient/plugin.xml
new file mode 100644
index 000000000..bb1b7f1b1
--- /dev/null
+++ b/src/plugin/protocol-httpclient/plugin.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<plugin
+ id="protocol-httpclient"
+ name="Http / Https Protocol Plug-in"
+ version="1.0.0"
+ provider-name="nutch.org">
+
+ <extension-point
+ id="org.apache.nutch.protocol.Protocol"
+ name="Nutch Protocol"/>
+
+ <runtime>
+ <library name="protocol-httpclient.jar">
+ <export name="*"/>
+ </library>
+ <library name="commons-codec.jar" />
+ <library name="commons-httpclient-3.0-rc2.jar" />
+
+ </runtime>
+
+ <extension id="org.apache.nutch.protocol.httpclient"
+ name="HttpProtocol"
+ point="org.apache.nutch.protocol.Protocol">
+
+ <implementation id="org.apache.nutch.protocol.httpclient.Http"
+ class="org.apache.nutch.protocol.httpclient.Http"
+ protocolName="http"/>
+
+ </extension>
+
+ <extension id="org.apache.nutch.protocol.https"
+ name="HttpsProtocol"
+ point="org.apache.nutch.protocol.Protocol">
+
+ <implementation id="org.apache.nutch.protocol.httpclient.Http"
+ class="org.apache.nutch.protocol.httpclient.Http"
+ protocolName="https"/>
+
+ </extension>
+
+</plugin>
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
new file mode 100644
index 000000000..9ea05b883
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java
@@ -0,0 +1,129 @@
+/*
+ * Based on EasySSLProtocolSocketFactory from commons-httpclient:
+ *
+ * $Header:
+ * /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/DummySSLProtocolSocketFactory.java,v
+ * 1.7 2004/06/11 19:26:27 olegk Exp $ $Revision$ $Date: 2005-02-26 05:01:52
+ * -0800 (Sat, 26 Feb 2005) $
+ */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.HttpClientError;
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
+import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.sun.net.ssl.SSLContext;
+import com.sun.net.ssl.TrustManager;
+
+public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactory {
+
+ /** Log object for this class. */
+ private static final Log LOG = LogFactory.getLog(DummySSLProtocolSocketFactory.class);
+
+ private SSLContext sslcontext = null;
+
+ /**
+ * Constructor for DummySSLProtocolSocketFactory.
+ */
+ public DummySSLProtocolSocketFactory() {
+ super();
+ }
+
+ private static SSLContext createEasySSLContext() {
+ try {
+ SSLContext context = SSLContext.getInstance("SSL");
+ context.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null);
+ return context;
+ } catch (Exception e) {
+ LOG.error(e.getMessage(), e);
+ throw new HttpClientError(e.toString());
+ }
+ }
+
+ private SSLContext getSSLContext() {
+ if (this.sslcontext == null) {
+ this.sslcontext = createEasySSLContext();
+ }
+ return this.sslcontext;
+ }
+
+ /**
+ * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
+ */
+ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException,
+ UnknownHostException {
+
+ return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
+ }
+
+ /**
+ * Attempts to get a new socket connection to the given host within the given
+ * time limit.
+ * <p>
+ * To circumvent the limitations of older JREs that do not support connect
+ * timeout a controller thread is executed. The controller thread attempts to
+ * create a new socket within the given limit of time. If socket constructor
+ * does not return until the timeout expires, the controller terminates and
+ * throws an {@link ConnectTimeoutException}
+ * </p>
+ *
+ * @param host the host name/IP
+ * @param port the port on the host
+ * @param clientHost the local host name/IP to bind the socket to
+ * @param clientPort 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
+ */
+ 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");
+ }
+ int timeout = params.getConnectionTimeout();
+ if (timeout == 0) {
+ 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);
+ }
+ }
+
+ /**
+ * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
+ */
+ public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
+ return getSSLContext().getSocketFactory().createSocket(host, port);
+ }
+
+ /**
+ * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.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 boolean equals(Object obj) {
+ return ((obj != null) && obj.getClass().equals(DummySSLProtocolSocketFactory.class));
+ }
+
+ public int hashCode() {
+ return DummySSLProtocolSocketFactory.class.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
new file mode 100644
index 000000000..a5b5f18d0
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummyX509TrustManager.java
@@ -0,0 +1,60 @@
+/*
+ * Based on EasyX509TrustManager from commons-httpclient.
+ */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+import com.sun.net.ssl.TrustManagerFactory;
+import com.sun.net.ssl.TrustManager;
+import com.sun.net.ssl.X509TrustManager;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class DummyX509TrustManager implements X509TrustManager
+{
+ private X509TrustManager standardTrustManager = null;
+
+ /** Log object for this class. */
+ private static final Log LOG = LogFactory.getLog(DummyX509TrustManager.class);
+
+ /**
+ * Constructor for DummyX509TrustManager.
+ */
+ public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
+ super();
+ TrustManagerFactory factory = TrustManagerFactory.getInstance("SunX509");
+ factory.init(keystore);
+ TrustManager[] trustmanagers = factory.getTrustManagers();
+ if (trustmanagers.length == 0) {
+ throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
+ }
+ this.standardTrustManager = (X509TrustManager)trustmanagers[0];
+ }
+
+ /**
+ * @see com.sun.net.ssl.X509TrustManager#isClientTrusted(X509Certificate[])
+ */
+ public boolean isClientTrusted(X509Certificate[] certificates) {
+ return true;
+ }
+
+ /**
+ * @see com.sun.net.ssl.X509TrustManager#isServerTrusted(X509Certificate[])
+ */
+ public boolean isServerTrusted(X509Certificate[] certificates) {
+ return true;
+ }
+
+ /**
+ * @see com.sun.net.ssl.X509TrustManager#getAcceptedIssuers()
+ */
+ public X509Certificate[] getAcceptedIssuers() {
+ return this.standardTrustManager.getAcceptedIssuers();
+ }
+}
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
new file mode 100644
index 000000000..4675fe82c
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
@@ -0,0 +1,415 @@
+/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.net.InetAddress;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.commons.httpclient.Cookie;
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpState;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.NTCredentials;
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.Protocol;
+import org.apache.nutch.db.Page;
+import org.apache.nutch.pagedb.FetchListEntry;
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.protocol.ProtocolException;
+import org.apache.nutch.protocol.ProtocolOutput;
+import org.apache.nutch.protocol.ProtocolStatus;
+import org.apache.nutch.protocol.RetryLater;
+import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
+
+/** An implementation of the Http protocol. */
+public class Http implements org.apache.nutch.protocol.Protocol {
+
+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.net.Http");
+
+ static {
+ if (NutchConf.get().getBoolean("http.verbose", false)) LOG.setLevel(Level.FINE);
+ }
+
+ static final int BUFFER_SIZE = 8 * 1024;
+ private static final int MAX_REDIRECTS = NutchConf.get().getInt("http.redirect.max", 3);
+ private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
+ private static HttpClient client;
+
+ static synchronized HttpClient getClient() {
+ if (client != null) return client;
+ configureClient();
+ return client;
+ }
+
+ static String PROXY_HOST = NutchConf.get().get("http.proxy.host");
+ static int PROXY_PORT = NutchConf.get().getInt("http.proxy.port", 8080);
+ static boolean PROXY = (PROXY_HOST != null && PROXY_HOST.length() > 0);
+ static int TIMEOUT = NutchConf.get().getInt("http.timeout", 10000);
+ static int MAX_CONTENT = NutchConf.get().getInt("http.content.limit", 64 * 1024);
+ static int MAX_DELAYS = NutchConf.get().getInt("http.max.delays", 3);
+ static int MAX_THREADS_PER_HOST = NutchConf.get().getInt("fetcher.threads.per.host", 1);
+ static int MAX_THREADS_TOTAL = NutchConf.get().getInt("fetcher.threads.fetch", 10);
+ static String AGENT_STRING = getAgentString();
+ static long SERVER_DELAY = (long) (NutchConf.get().getFloat("fetcher.server.delay", 1.0f) * 1000);
+ static String NTLM_USERNAME = NutchConf.get().get("http.auth.ntlm.username", "");
+ static String NTLM_PASSWORD = NutchConf.get().get("http.auth.ntlm.password", "");
+ static String NTLM_DOMAIN = NutchConf.get().get("http.auth.ntlm.domain", "");
+ static String NTLM_HOST = NutchConf.get().get("http.auth.ntlm.host", "");
+
+ static {
+ LOG.info("http.proxy.host = " + PROXY_HOST);
+ LOG.info("http.proxy.port = " + PROXY_PORT);
+
+ LOG.info("http.timeout = " + TIMEOUT);
+ LOG.info("http.content.limit = " + MAX_CONTENT);
+ LOG.info("http.agent = " + AGENT_STRING);
+
+ LOG.info("http.auth.ntlm.username = " + NTLM_USERNAME);
+
+ LOG.info("fetcher.server.delay = " + SERVER_DELAY);
+ LOG.info("http.max.delays = " + MAX_DELAYS);
+ }
+
+ /**
+ * Maps from InetAddress to a Long naming the time it should be unblocked. The
+ * Long is zero while the address is in use, then set to now+wait when a
+ * request finishes. This way only one thread at a time accesses an address.
+ */
+ private static HashMap BLOCKED_ADDR_TO_TIME = new HashMap();
+
+ /** Maps an address to the number of threads accessing that address. */
+ private static HashMap THREADS_PER_HOST_COUNT = new HashMap();
+
+ /**
+ * Queue of blocked InetAddress. This contains all of the non-zero entries
+ * from BLOCKED_ADDR_TO_TIME, ordered by increasing time.
+ */
+ private static LinkedList BLOCKED_ADDR_QUEUE = new LinkedList();
+
+ private RobotRulesParser robotRules = new RobotRulesParser();
+
+ private static InetAddress blockAddr(URL url) throws ProtocolException {
+ InetAddress addr;
+ try {
+ addr = InetAddress.getByName(url.getHost());
+ } catch (UnknownHostException e) {
+ throw new HttpException(e);
+ }
+
+ int delays = 0;
+ while (true) {
+ cleanExpiredServerBlocks(); // free held addresses
+
+ Long time;
+ synchronized (BLOCKED_ADDR_TO_TIME) {
+ time = (Long) BLOCKED_ADDR_TO_TIME.get(addr);
+ if (time == null) { // address is free
+
+ // get # of threads already accessing this addr
+ Integer counter = (Integer) THREADS_PER_HOST_COUNT.get(addr);
+ int count = (counter == null) ? 0 : counter.intValue();
+
+ count++; // increment & store
+ THREADS_PER_HOST_COUNT.put(addr, new Integer(count));
+
+ if (count >= MAX_THREADS_PER_HOST) {
+ BLOCKED_ADDR_TO_TIME.put(addr, new Long(0)); // block it
+ }
+ return addr;
+ }
+ }
+
+ if (delays == MAX_DELAYS) throw new RetryLater(url, "Exceeded http.max.delays: retry later.");
+
+ long done = time.longValue();
+ long now = System.currentTimeMillis();
+ long sleep = 0;
+ if (done == 0) { // address is still in use
+ sleep = SERVER_DELAY; // wait at least delay
+
+ } else if (now < done) { // address is on hold
+ sleep = done - now; // wait until its free
+ }
+
+ try {
+ Thread.sleep(sleep);
+ } catch (InterruptedException e) {}
+ delays++;
+ }
+ }
+
+ private static void cleanExpiredServerBlocks() {
+ synchronized (BLOCKED_ADDR_TO_TIME) {
+ while (!BLOCKED_ADDR_QUEUE.isEmpty()) {
+ InetAddress addr = (InetAddress) BLOCKED_ADDR_QUEUE.getLast();
+ long time = ((Long) BLOCKED_ADDR_TO_TIME.get(addr)).longValue();
+ if (time <= System.currentTimeMillis()) {
+ BLOCKED_ADDR_TO_TIME.remove(addr);
+ BLOCKED_ADDR_QUEUE.removeLast();
+ } else {
+ break;
+ }
+ }
+ }
+ }
+
+ private static void unblockAddr(InetAddress addr) {
+ synchronized (BLOCKED_ADDR_TO_TIME) {
+ int addrCount = ((Integer) THREADS_PER_HOST_COUNT.get(addr)).intValue();
+ if (addrCount == 1) {
+ THREADS_PER_HOST_COUNT.remove(addr);
+ BLOCKED_ADDR_QUEUE.addFirst(addr);
+ BLOCKED_ADDR_TO_TIME.put(addr, new Long(System.currentTimeMillis() + SERVER_DELAY));
+ } else {
+ THREADS_PER_HOST_COUNT.put(addr, new Integer(addrCount - 1));
+ }
+ }
+ }
+
+ public ProtocolOutput getProtocolOutput(String urlString) {
+ ProtocolOutput output = null;
+ try {
+ return getProtocolOutput(new FetchListEntry(true, new Page(urlString, 1.0f), new String[0]));
+ } catch (MalformedURLException mue) {
+ return new ProtocolOutput(null, new ProtocolStatus(mue));
+ }
+ }
+
+ public ProtocolOutput getProtocolOutput(FetchListEntry fle) {
+ String urlString = fle.getUrl().toString();
+ try {
+ URL url = new URL(urlString);
+
+ int redirects = 0;
+ HttpAuthentication auth = null;
+ while (true) {
+ try {
+ if (!RobotRulesParser.isAllowed(url))
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.ROBOTS_DENIED, url));
+ } catch (Throwable e) {
+ // XXX Maybe bogus: assume this is allowed.
+ LOG.fine("Exception checking robot rules for " + url + ": " + e);
+ }
+
+ InetAddress addr = blockAddr(url);
+ HttpResponse response;
+ try {
+ response = new HttpResponse(urlString, url); // make a request
+ } finally {
+ unblockAddr(addr);
+ }
+
+ int code = response.getCode();
+
+ if (code == 200) { // got a good response
+ return new ProtocolOutput(response.toContent()); // return it
+
+ } else if (code == 410) { // page is gone
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.GONE, "Http: " + code + " url=" + url));
+
+ } else if (code >= 300 && code < 400) { // handle redirect
+ url = new URL(url, response.getHeader("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;
+ }
+ // handle this in the higher layer.
+ return new ProtocolOutput(null, new ProtocolStatus(protocolStatusCode, url));
+ } else if (code == 400) { // bad request, mark as GONE
+ LOG.fine("400 Bad request: " + url);
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.GONE, url));
+ } else if (code == 401) { // requires authorization
+ LOG.fine("401 Authentication Required");
+ if (redirects == MAX_REDIRECTS)
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.REDIR_EXCEED,
+ "Too many redirects: " + urlString));
+ Properties p = response.toContent().getMetadata();
+ if (p instanceof MultiProperties) {
+ auth = HttpAuthenticationFactory.findAuthentication((MultiProperties) p);
+ } else {
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.ACCESS_DENIED, "Authorization required: "
+ + urlString));
+ }
+ redirects++;
+ } else if (code == 404) {
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.NOT_FOUND, url));
+ } else if (code == 410) { // permanently GONE
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.GONE, url));
+ } else {
+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.EXCEPTION, "Http code=" + code + ", url="
+ + url));
+ }
+ }
+ } catch (Throwable e) {
+ e.printStackTrace();
+ return new ProtocolOutput(null, new ProtocolStatus(e));
+ }
+ }
+
+ private static String getAgentString() {
+ NutchConf conf = NutchConf.get();
+ String agentName = conf.get("http.agent.name");
+ String agentVersion = conf.get("http.agent.version");
+ String agentDesc = conf.get("http.agent.description");
+ String agentURL = conf.get("http.agent.url");
+ String agentEmail = conf.get("http.agent.email");
+
+ if ((agentName == null) || (agentName.trim().length() == 0))
+ LOG.severe("No User-Agent string set (http.agent.name)!");
+
+ 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))) {
+ buf.append(" (");
+
+ if ((agentDesc != null) && (agentDesc.length() != 0)) {
+ buf.append(agentDesc);
+ 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();
+ }
+
+ /** For debugging. */
+ public static void main(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
+ TIMEOUT = Integer.parseInt(args[++i]) * 1000;
+ } else if (args[i].equals("-verbose")) { // found -verbose option
+ verbose = true;
+ } else if (i != args.length - 1) {
+ System.err.println(usage);
+ System.exit(-1);
+ } else // root is required parameter
+ url = args[i];
+ }
+
+ Http http = new Http();
+
+ if (verbose) {
+ LOG.setLevel(Level.FINE);
+ }
+
+ ProtocolOutput out = http.getProtocolOutput(url);
+ 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.get("Content-Length"));
+ System.out.println("Content:");
+ String text = new String(content.getContent());
+ System.out.println(text);
+ }
+
+ }
+
+ private static void configureClient() {
+
+ // get a client isntance -- we just need one.
+
+ client = new HttpClient(connectionManager);
+ // this is just to add logging, whenever cookies are added.
+ client.setState(new NutchHttpState());
+
+ // Set up an HTTPS socket factory that accepts self-signed certs.
+ Protocol dummyhttps = new Protocol("https", new DummySSLProtocolSocketFactory(), 443);
+ Protocol.registerProtocol("https", dummyhttps);
+
+ // set up the connection manager
+ // hardcoded for now
+
+ connectionManager.setMaxTotalConnections(MAX_THREADS_TOTAL);
+ //if (MAX_THREADS_TOTAL > MAX_THREADS_PER_HOST) {
+ // connectionManager.setMaxConnectionsPerHost(MAX_THREADS_PER_HOST);
+ //} else {
+ // connectionManager.setMaxConnectionsPerHost(MAX_THREADS_TOTAL);
+ //}
+
+ HttpConnectionParams params = connectionManager.getParams();
+ params.setConnectionTimeout(TIMEOUT);
+ params.setSoTimeout(TIMEOUT);
+ params.setSendBufferSize(BUFFER_SIZE);
+ params.setReceiveBufferSize(BUFFER_SIZE);
+ /*
+ * HostConfiguration hostConf = client.getHostConfiguration(); if (PROXY) {
+ * hostConf.setProxy(PROXY_HOST, PROXY_PORT); }
+ *
+ */
+ if (NTLM_USERNAME.length() > 0) {
+ Credentials ntCreds = new NTCredentials(NTLM_USERNAME, NTLM_PASSWORD, NTLM_HOST, NTLM_DOMAIN);
+ client.getState().setCredentials(null, null, ntCreds);
+
+ LOG.info("Added NTLM credentials for " + NTLM_USERNAME);
+ }
+ LOG.info("Configured Client");
+ }
+}
+
+class NutchHttpState extends HttpState {
+ public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.net.Http.NutchHttpState");
+
+ public void addCookie(Cookie cookie) {
+ LOG.fine(" - setting cookie: " + cookie);
+ super.addCookie(cookie);
+ }
+
+ public void addCookies(Cookie[] cookies) {
+ LOG.fine(" - setting cookies: ");
+ for (int i = 0; i < cookies.length; i++)
+ LOG.fine(" cookie: " + cookies[i]);
+
+ super.addCookies(cookies);
+ }
+}
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
new file mode 100644
index 000000000..137bd7f45
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthentication.java
@@ -0,0 +1,33 @@
+/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.util.List;
+
+/**
+ * The base level of services required for Http Authentication
+ *
+ * @see HttpAuthenticationFactory
+ *
+ * @author Matt Tencati
+ */
+public interface HttpAuthentication {
+
+ /**
+ * Gets the credentials generated by the HttpAuthentication
+ * object. May return null.
+ *
+ * @return The credentials value
+ */
+ public List getCredentials();
+
+ /**
+ * 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
new file mode 100644
index 000000000..2f18c4b73
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationException.java
@@ -0,0 +1,52 @@
+/* Copyright (c) 2003 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+/**
+ * Can be used to identify problems during creation of Authentication objects.
+ * In the future it may be used as a method of collecting authentication
+ * failures during Http protocol transfer in order to present the user with
+ * credentials required during a future fetch.
+ *
+ * @author Matt Tencati
+ */
+public class HttpAuthenticationException extends Exception {
+
+ /**
+ * 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 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);
+ }
+
+}
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
new file mode 100644
index 000000000..b880c6cf3
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java
@@ -0,0 +1,91 @@
+/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
+
+/**
+ * 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 {
+ /** The HTTP Authentication (WWW-Authenticate) header which is returned
+ * by a webserver requiring authentication.
+ */
+ public static final String AUTH_HEADER = "WWW-Authenticate";
+
+ public static final Logger LOG =
+ LogFormatter.getLogger("net.nutch.protocol.http.HttpAuthenticationFactory");
+
+ static {
+ if (NutchConf.get().getBoolean("http.auth.verbose", false))
+ LOG.setLevel(Level.FINE);
+ }
+
+ private static Map auths = new TreeMap();
+
+ private HttpAuthenticationFactory() { }
+
+ public static HttpAuthentication findAuthentication(Properties header) {
+ if (header == null) return null;
+
+ try {
+ Collection challenge = null;
+ if (header instanceof MultiProperties) {
+ Object o = header.get(AUTH_HEADER);
+ if (o instanceof Collection) {
+ challenge = (Collection) o;
+ } else {
+ challenge = new ArrayList();
+ challenge.add(o.toString());
+ }
+ } else {
+ String challengeString = header.getProperty(AUTH_HEADER);
+ if (challengeString != null) {
+ challenge = new ArrayList();
+ challenge.add(challengeString);
+ }
+ }
+ if (challenge == null) {
+ LOG.fine("Authentication challenge is null");
+ return null;
+ }
+
+ Iterator i = challenge.iterator();
+ HttpAuthentication auth = null;
+ while (i.hasNext() && auth == null) {
+ String challengeString = (String)i.next();
+ if (challengeString.equals("NTLM")) {
+ challengeString="Basic realm=techweb";
+ }
+
+ LOG.fine("Checking challengeString=" + challengeString);
+ auth = HttpBasicAuthentication.getAuthentication(challengeString);
+ if (auth != null) return auth;
+
+ //TODO Add additional Authentication lookups here
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+}
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
new file mode 100644
index 000000000..9d4040b4b
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java
@@ -0,0 +1,141 @@
+/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.codec.binary.Base64;
+
+import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.util.NutchConf;
+
+/**
+ * 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 {
+ public static final Logger LOG =
+ LogFormatter.getLogger("net.nutch.net.HttpBasicAuthentication");
+
+ static {
+ if (NutchConf.get().getBoolean("http.auth.verbose", false))
+ LOG.setLevel(Level.FINE);
+ }
+
+ private static Pattern basic = Pattern.compile("[bB][aA][sS][iI][cC] [rR][eE][aA][lL][mM]=\"(\\w*)\"");
+
+ private static Map authMap = new TreeMap();
+
+ private String challenge = null;
+ private ArrayList credentials = null;
+ private String realm = null;
+
+ /**
+ * Construct an HttpBasicAuthentication for the given challenge
+ * parameters. The challenge parameters are returned by the web
+ * 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) throws HttpAuthenticationException {
+ this.challenge = challenge;
+ LOG.fine("BasicAuthentication challenge is " + challenge);
+ credentials = new ArrayList();
+
+ String username = NutchConf.get().get("http.auth.basic." + challenge + ".user");
+ LOG.fine("BasicAuthentication username=" + username);
+ String password = NutchConf.get().get("http.auth.basic." + challenge + ".user");
+ LOG.fine("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)));
+ LOG.fine("Basic credentials: " + credentials);
+ }
+
+ /**
+ * 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 getCredentials() {
+ return credentials;
+ }
+
+
+ /**
+ * Gets the realm attribute of the HttpBasicAuthentication object.
+ * This should have been supplied to the {@link #getAuthentication(String)} 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) {
+ 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);
+ } catch (HttpAuthenticationException hae) {
+ LOG.fine("HttpBasicAuthentication failed for " + challenge);
+ }
+ authMap.put(realm, newAuth);
+ return newAuth;
+ } else {
+ return (HttpBasicAuthentication) auth;
+ }
+ }
+ 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/HttpError.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpError.java
new file mode 100644
index 000000000..3fd5cbbe3
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpError.java
@@ -0,0 +1,19 @@
+/* Copyright (c) 2003 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+/** Thrown for HTTP error codes.
+ */
+public class HttpError extends HttpException {
+
+ private int code;
+
+ public int getCode(int code) { return code; }
+
+ public HttpError(int code) {
+ super("HTTP Error: " + code);
+ this.code = code;
+ }
+
+}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpException.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpException.java
new file mode 100644
index 000000000..118ac29a6
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpException.java
@@ -0,0 +1,26 @@
+/* Copyright (c) 2003 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+import org.apache.nutch.protocol.ProtocolException;
+
+public class HttpException extends ProtocolException {
+
+ public HttpException() {
+ super();
+ }
+
+ public HttpException(String message) {
+ super(message);
+ }
+
+ public HttpException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public HttpException(Throwable cause) {
+ super(cause);
+ }
+
+}
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
new file mode 100644
index 000000000..8561f62cb
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java
@@ -0,0 +1,116 @@
+/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.protocol.ProtocolException;
+
+import org.apache.commons.httpclient.Header;
+
+import org.apache.commons.httpclient.methods.GetMethod;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Properties;
+import java.util.List;
+import java.util.ListIterator;
+
+/**
+ * An HTTP response.
+ */
+public class HttpResponse {
+ private String orig;
+
+ private String base;
+
+ private byte[] content;
+
+ private int code;
+
+ private MultiProperties headers = new MultiProperties();
+
+ /**
+ * Returns the response code.
+ */
+ public int getCode() {
+ return code;
+ }
+
+ /**
+ * Returns the value of a named header.
+ */
+ public String getHeader(String name) {
+ return (String) headers.get(name);
+ }
+
+ public byte[] getContent() {
+ return content;
+ }
+
+ public Content toContent() {
+ String contentType = getHeader("Content-Type");
+ if (contentType == null) contentType = "";
+ return new Content(orig, base, content, contentType, headers);
+ }
+
+ public HttpResponse(URL url) throws ProtocolException, IOException {
+ this(url.toString(), url);
+ }
+
+ public HttpResponse(String orig, URL url) throws IOException {
+ this.orig = orig;
+ this.base = url.toString();
+ GetMethod get = new GetMethod(url.toString());
+ get.setFollowRedirects(false);
+ get.setStrictMode(false);
+ get.setRequestHeader("User-Agent", Http.AGENT_STRING);
+ get.setHttp11(false);
+ get.setMethodRetryHandler(null);
+ try {
+ code = Http.getClient().executeMethod(get);
+
+ Header[] heads = get.getResponseHeaders();
+
+ for (int i = 0; i < heads.length; i++) {
+ headers.put(heads[i].getName(), heads[i].getValue());
+ }
+ if (code == 200) {
+
+ InputStream in = get.getResponseBodyAsStream();
+ byte[] buffer = new byte[Http.BUFFER_SIZE];
+ int bufferFilled = 0;
+ int totalRead = 0;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ int tryAndRead = calculateTryToRead(totalRead);
+ while ((bufferFilled = in.read(buffer, 0, buffer.length)) != -1 && tryAndRead > 0) {
+ totalRead += bufferFilled;
+ out.write(buffer, 0, bufferFilled);
+ tryAndRead = calculateTryToRead(totalRead);
+ }
+
+ content = out.toByteArray();
+ in.close();
+
+ }
+ } catch (org.apache.commons.httpclient.ProtocolException pe) {
+ pe.printStackTrace();
+ throw new IOException(pe.toString());
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ private int calculateTryToRead(int totalRead) {
+ int tryToRead = Http.BUFFER_SIZE;
+ if (Http.MAX_CONTENT <= 0) {
+ return Http.BUFFER_SIZE;
+ } else if (Http.MAX_CONTENT - totalRead < Http.BUFFER_SIZE) {
+ tryToRead = Http.MAX_CONTENT - totalRead;
+ }
+ return tryToRead;
+ }
+
+}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/MultiProperties.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/MultiProperties.java
new file mode 100644
index 000000000..b30868d17
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/MultiProperties.java
@@ -0,0 +1,131 @@
+/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */
+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.util.Properties;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.Vector;
+import java.util.Iterator;
+import java.util.logging.Logger;
+
+import org.apache.nutch.util.LogFormatter;
+
+/**
+ * An extension to {@link Properties} which allows multiple values for a single key.
+ * The {@link #get(Object)} method may return a single value or a
+ * {@link java.util.Collection} of values.
+ *
+ * @author Matt Tencati
+ */
+
+public class MultiProperties extends Properties {
+ public static final Logger LOG = LogFormatter
+ .getLogger("net.nutch.protocol.http.MultiProperties");
+
+ private Map multiMap = null;
+
+ /**
+ * Creates an empty MultiProperties list with no default values.
+ */
+ public MultiProperties() {
+ super();
+ multiMap = new TreeMap();
+ }
+
+ /**
+ * Creates an empty MultiProperties list with the specified defaults.
+ *
+ * @param defaults A Properties object to use as default values
+ */
+ public MultiProperties(Properties defaults) {
+ super(defaults);
+ multiMap = new TreeMap();
+ }
+
+ /**
+ * Adds the given value using the key
+ *
+ * @param key The key for the value
+ * @param value The value to store in the Property map
+ *
+ * @see java.util.Dictionary#put(java.lang.Object, java.lang.Object)
+ */
+ public Object put(Object key, Object value) throws NullPointerException {
+ Object o = multiMap.get(key);
+ Vector values = null;
+ if (o == null || !(o instanceof Vector)) {
+ values = new Vector();
+ multiMap.put(key, values);
+ } else {
+ values = (Vector) o;
+ }
+ values.add(value);
+ multiMap.put(key, values);
+
+ return super.put(key, value);
+ }
+
+ /**
+ * Add all entries of the given map to this MultiProperties list. The
+ * entries will be added using the key retrieved from {@link Map#keySet()}
+ *
+ * @param t The {@link Map} object which containts the values to add.
+ *
+ * @see java.util.Map#putAll(java.util.Map)
+ */
+ public void putAll(Map t) throws NullPointerException {
+ //LOG.info("PUT ALL\n" + t.toString());
+ Iterator i = t.keySet().iterator();
+ while (i.hasNext()) {
+ Object key = i.next();
+ Object value = t.get(key);
+ put(key, value);
+ }
+ }
+
+ /**
+ * Returns the value associated with the given key. The return object
+ * may be either a single value (String) or a Collection of values.
+ *
+ * @param key Used to lookup the value
+ * @return Returns a single value or multiple values if available
+ * @see java.util.Dictionary#get(java.lang.Object)
+ */
+ public Object get(Object key) throws NullPointerException {
+ if (key == null)
+ throw new NullPointerException("Lookup null key");
+ Object o = multiMap.get(key);
+ if (o != null && o instanceof Vector) {
+ if (((Vector) o).size() == 1) {
+ return super.get(key);
+ }
+ }
+ return o;
+ }
+
+ /**
+ * A string representation of this MultiProperties list.
+ *
+ * @return A multi-line String object.
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ Iterator i = multiMap.keySet().iterator();
+ while (i.hasNext()) {
+ String key = (String) i.next();
+ Vector values = (Vector) multiMap.get(key);
+ Iterator valIterator = values.iterator();
+ sb.append(key + " {\n");
+ while (valIterator.hasNext()) {
+ String value = (String) valIterator.next();
+ sb.append("\t" + value + "\n");
+ }
+ sb.append("\t}");
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java
new file mode 100644
index 000000000..d74e575e7
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java
@@ -0,0 +1,473 @@
+/**
+ * Copyright 2005 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.nutch.protocol.httpclient;
+
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.LineNumberReader;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.StringTokenizer;
+
+import java.util.logging.Logger;
+import java.util.logging.Level;
+import java.util.logging.Handler;
+
+import org.apache.nutch.util.NutchConf;
+import org.apache.nutch.util.LogFormatter;
+import org.apache.nutch.protocol.ProtocolException;
+
+/**
+ * This class handles the parsing of <code>robots.txt</code> files.
+ * It emits RobotRules objects, which describe the download permissions
+ * as described in RobotRulesParser.
+ *
+ * @author Tom Pierce
+ * @author Mike Cafarella
+ * @author Doug Cutting
+ */
+public class RobotRulesParser {
+ public static final Logger LOG=
+ LogFormatter.getLogger("org.apache.nutch.fetcher.RobotRulesParser");
+
+ private static final String[] AGENTS = getAgents();
+ private static final Hashtable CACHE = new Hashtable();
+
+ private static final String CHARACTER_ENCODING= "UTF-8";
+ private static final int NO_PRECEDENCE= Integer.MAX_VALUE;
+
+ private static final RobotRuleSet EMPTY_RULES= new RobotRuleSet();
+
+ private static RobotRuleSet FORBID_ALL_RULES =
+ new RobotRulesParser().getForbidAllRules();
+
+ private HashMap robotNames;
+
+ /**
+ * This class holds the rules which were parsed from a robots.txt
+ * file, and can test paths against those rules.
+ */
+ public static class RobotRuleSet {
+ ArrayList tmpEntries;
+ RobotsEntry[] entries;
+ long expireTime;
+
+ /**
+ */
+ private class RobotsEntry {
+ String prefix;
+ boolean allowed;
+
+ RobotsEntry(String prefix, boolean allowed) {
+ this.prefix= prefix;
+ this.allowed= allowed;
+ }
+ }
+
+ /**
+ * should not be instantiated from outside RobotRulesParser
+ */
+ private RobotRuleSet() {
+ tmpEntries= new ArrayList();
+ entries= null;
+ }
+
+ /**
+ */
+ private void addPrefix(String prefix, boolean allow) {
+ if (tmpEntries == null) {
+ tmpEntries= new ArrayList();
+ if (entries != null) {
+ for (int i= 0; i < entries.length; i++)
+ tmpEntries.add(entries[i]);
+ }
+ entries= null;
+ }
+
+ tmpEntries.add(new RobotsEntry(prefix, allow));
+ }
+
+ /**
+ */
+ private void clearPrefixes() {
+ if (tmpEntries == null) {
+ tmpEntries= new ArrayList();
+ entries= null;
+ } else {
+ tmpEntries.clear();
+ }
+ }
+
+ /**
+ * Change when the ruleset goes stale.
+ */
+ public void setExpireTime(long expireTime) {
+ this.expireTime = expireTime;
+ }
+
+ /**
+ * Get expire time
+ */
+ public long getExpireTime() {
+ return expireTime;
+ }
+
+ /**
+ * Returns <code>false</code> if the <code>robots.txt</code> file
+ * prohibits us from accessing the given <code>path</code>, or
+ * <code>true</code> otherwise.
+ */
+ public boolean isAllowed(String path) {
+ try {
+ path= URLDecoder.decode(path, CHARACTER_ENCODING);
+ } catch (Exception e) {
+ // just ignore it- we can still try to match
+ // path prefixes
+ }
+
+ if (entries == null) {
+ entries= new RobotsEntry[tmpEntries.size()];
+ entries= (RobotsEntry[])
+ tmpEntries.toArray(entries);
+ tmpEntries= null;
+ }
+
+ int pos= 0;
+ int end= entries.length;
+ while (pos < end) {
+ if (path.startsWith(entries[pos].prefix))
+ return entries[pos].allowed;
+ pos++;
+ }
+
+ return true;
+ }
+
+ /**
+ */
+ public String toString() {
+ isAllowed("x"); // force String[] representation
+ StringBuffer buf= new StringBuffer();
+ for (int i= 0; i < entries.length; i++)
+ if (entries[i].allowed)
+ buf.append("Allow: " + entries[i].prefix
+ + System.getProperty("line.separator"));
+ else
+ buf.append("Disallow: " + entries[i].prefix
+ + System.getProperty("line.separator"));
+ return buf.toString();
+ }
+ }
+
+
+ public RobotRulesParser() { this(AGENTS); }
+
+ private static String[] getAgents() {
+ //
+ // Grab the agent names we advertise to robots files.
+ //
+ String agentName = NutchConf.get().get("http.agent.name");
+ String agentNames = NutchConf.get().get("http.robots.agents");
+ StringTokenizer tok = new StringTokenizer(agentNames, ",");
+ ArrayList agents = new ArrayList();
+ while (tok.hasMoreTokens()) {
+ agents.add(tok.nextToken().trim());
+ }
+
+ //
+ // If there are no agents for robots-parsing, use our
+ // default agent-string. If both are present, our agent-string
+ // should be the first one we advertise to robots-parsing.
+ //
+ if (agents.size() == 0) {
+ agents.add(agentName);
+ LOG.severe("No agents listed in 'http.robots.agents' property!");
+ } else if (!((String)agents.get(0)).equalsIgnoreCase(agentName)) {
+ agents.add(0, agentName);
+ LOG.severe("Agent we advertise (" + agentName
+ + ") not listed first in 'http.robots.agents' property!");
+ }
+
+ return (String[])agents.toArray(new String[agents.size()]);
+ }
+
+
+ /**
+ * Creates a new <code>RobotRulesParser</code> which will use the
+ * supplied <code>robotNames</code> when choosing which stanza to
+ * follow in <code>robots.txt</code> files. Any name in the array
+ * may be matched. The order of the <code>robotNames</code>
+ * determines the precedence- if many names are matched, only the
+ * rules associated with the robot name having the smallest index
+ * will be used.
+ */
+ public RobotRulesParser(String[] robotNames) {
+ this.robotNames= new HashMap();
+ for (int i= 0; i < robotNames.length; i++) {
+ this.robotNames.put(robotNames[i].toLowerCase(), new Integer(i));
+ }
+ // always make sure "*" is included
+ if (!this.robotNames.containsKey("*"))
+ this.robotNames.put("*", new Integer(robotNames.length));
+ }
+
+ /**
+ * Returns a {@link RobotRuleSet} object which encapsulates the
+ * rules parsed from the supplied <code>robotContent</code>.
+ */
+ RobotRuleSet parseRules(byte[] robotContent) {
+ if (robotContent == null)
+ return EMPTY_RULES;
+
+ String content= new String (robotContent);
+
+ StringTokenizer lineParser= new StringTokenizer(content, "\n\r");
+
+ RobotRuleSet bestRulesSoFar= null;
+ int bestPrecedenceSoFar= NO_PRECEDENCE;
+
+ RobotRuleSet currentRules= new RobotRuleSet();
+ int currentPrecedence= NO_PRECEDENCE;
+
+ boolean addRules= false; // in stanza for our robot
+ boolean doneAgents= false; // detect multiple agent lines
+
+ while (lineParser.hasMoreTokens()) {
+ String line= lineParser.nextToken();
+
+ // trim out comments and whitespace
+ int hashPos= line.indexOf("#");
+ if (hashPos >= 0)
+ line= line.substring(0, hashPos);
+ line= line.trim();
+
+ if ( (line.length() >= 11)
+ && (line.substring(0, 11).equalsIgnoreCase("User-agent:")) ) {
+
+ if (doneAgents) {
+ if (currentPrecedence < bestPrecedenceSoFar) {
+ bestPrecedenceSoFar= currentPrecedence;
+ bestRulesSoFar= currentRules;
+ currentPrecedence= NO_PRECEDENCE;
+ currentRules= new RobotRuleSet();
+ }
+ addRules= false;
+ }
+ doneAgents= false;
+
+ String agentNames= line.substring(line.indexOf(":") + 1);
+ agentNames= agentNames.trim();
+ StringTokenizer agentTokenizer= new StringTokenizer(agentNames);
+
+ while (agentTokenizer.hasMoreTokens()) {
+ // for each agent listed, see if it's us:
+ String agentName= agentTokenizer.nextToken().toLowerCase();
+
+ Integer precedenceInt= (Integer) robotNames.get(agentName);
+
+ if (precedenceInt != null) {
+ int precedence= precedenceInt.intValue();
+ if ( (precedence < currentPrecedence)
+ && (precedence < bestPrecedenceSoFar) )
+ currentPrecedence= precedence;
+ }
+ }
+
+ if (currentPrecedence < bestPrecedenceSoFar)
+ addRules= true;
+
+ } else if ( (line.length() >= 9)
+ && (line.substring(0, 9).equalsIgnoreCase("Disallow:")) ) {
+
+ doneAgents= true;
+ String path= line.substring(line.indexOf(":") + 1);
+ path= path.trim();
+ try {
+ path= URLDecoder.decode(path, CHARACTER_ENCODING);
+ } catch (Exception e) {
+ LOG.warning("error parsing robots rules- can't decode path: "
+ + path);
+ }
+
+ if (path.length() == 0) { // "empty rule"
+ if (addRules)
+ currentRules.clearPrefixes();
+ } else { // rule with path
+ if (addRules)
+ currentRules.addPrefix(path, false);
+ }
+
+ } else if ( (line.length() >= 6)
+ && (line.substring(0, 6).equalsIgnoreCase("Allow:")) ) {
+
+ doneAgents= true;
+ String path= line.substring(line.indexOf(":") + 1);
+ path= path.trim();
+
+ if (path.length() == 0) {
+ // "empty rule"- treat same as empty disallow
+ if (addRules)
+ currentRules.clearPrefixes();
+ } else { // rule with path
+ if (addRules)
+ currentRules.addPrefix(path, true);
+ }
+ }
+ }
+
+ if (currentPrecedence < bestPrecedenceSoFar) {
+ bestPrecedenceSoFar= currentPrecedence;
+ bestRulesSoFar= currentRules;
+ }
+
+ if (bestPrecedenceSoFar == NO_PRECEDENCE)
+ return EMPTY_RULES;
+ return bestRulesSoFar;
+ }
+
+ /**
+ * Returns a <code>RobotRuleSet</code> object appropriate for use
+ * when the <code>robots.txt</code> file is empty or missing; all
+ * requests are allowed.
+ */
+ static RobotRuleSet getEmptyRules() {
+ return EMPTY_RULES;
+ }
+
+ /**
+ * Returns a <code>RobotRuleSet</code> object appropriate for use
+ * when the <code>robots.txt</code> file is not fetched due to a
+ * <code>403/Forbidden</code> response; all requests are
+ * disallowed.
+ */
+ static RobotRuleSet getForbidAllRules() {
+ RobotRuleSet rules= new RobotRuleSet();
+ rules.addPrefix("", false);
+ return rules;
+ }
+
+ public static boolean isAllowed(URL url)
+ throws ProtocolException, IOException {
+
+ String host = url.getHost();
+
+ RobotRuleSet robotRules = (RobotRuleSet)CACHE.get(host);
+
+ if (robotRules == null) { // cache miss
+ System.out.println("cache miss " + url);
+ try {
+ HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"));
+
+ if (response.getCode() == 200) // found rules: parse them
+ robotRules = new RobotRulesParser().parseRules(response.getContent());
+ else if (response.getCode() == 403)
+ robotRules = FORBID_ALL_RULES; // use forbid all
+ else
+ robotRules = EMPTY_RULES; // use default rules
+ } catch (Throwable t) {
+ LOG.info("Couldn't get robots.txt for " + url + ": " + t.toString());
+ robotRules = EMPTY_RULES;
+ }
+
+ CACHE.put(host, robotRules); // cache rules for host
+ }
+
+ String path = url.getPath(); // check rules
+ if ((path == null) || "".equals(path)) {
+ path= "/";
+ }
+
+ return robotRules.isAllowed(path);
+ }
+
+ private final static int BUFSIZE= 2048;
+
+ /** command-line main for testing */
+ public static void main(String[] argv) {
+ if (argv.length != 3) {
+ System.out.println("Usage:");
+ System.out.println(" java <robots-file> <url-file> <agent-name>+");
+ System.out.println("");
+ System.out.println("The <robots-file> will be parsed as a robots.txt file,");
+ System.out.println("using the given <agent-name> to select rules. URLs ");
+ System.out.println("will be read (one per line) from <url-file>, and tested");
+ System.out.println("against the rules.");
+ System.exit(-1);
+ }
+ try {
+ FileInputStream robotsIn= new FileInputStream(argv[0]);
+ LineNumberReader testsIn= new LineNumberReader(new FileReader(argv[1]));
+ String[] robotNames= new String[argv.length - 1];
+
+ for (int i= 0; i < argv.length - 2; i++)
+ robotNames[i]= argv[i+2];
+
+ ArrayList bufs= new ArrayList();
+ byte[] buf= new byte[BUFSIZE];
+ int totBytes= 0;
+
+ int rsize= robotsIn.read(buf);
+ while (rsize >= 0) {
+ totBytes+= rsize;
+ if (rsize != BUFSIZE) {
+ byte[] tmp= new byte[rsize];
+ System.arraycopy(buf, 0, tmp, 0, rsize);
+ bufs.add(tmp);
+ } else {
+ bufs.add(buf);
+ buf= new byte[BUFSIZE];
+ }
+ rsize= robotsIn.read(buf);
+ }
+
+ byte[] robotsBytes= new byte[totBytes];
+ int pos= 0;
+
+ for (int i= 0; i < bufs.size(); i++) {
+ byte[] currBuf= (byte[]) bufs.get(i);
+ int currBufLen= currBuf.length;
+ System.arraycopy(currBuf, 0, robotsBytes, pos, currBufLen);
+ pos+= currBufLen;
+ }
+
+ RobotRulesParser parser=
+ new RobotRulesParser(robotNames);
+ RobotRuleSet rules= parser.parseRules(robotsBytes);
+ System.out.println("Rules:");
+ System.out.println(rules);
+ System.out.println();
+
+ String testPath= testsIn.readLine().trim();
+ while (testPath != null) {
+ System.out.println( (rules.isAllowed(testPath) ?
+ "allowed" : "not allowed")
+ + ":\t" + testPath);
+ testPath= testsIn.readLine();
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/package.html b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/package.html
new file mode 100644
index 000000000..d4c8ea42f
--- /dev/null
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/package.html
@@ -0,0 +1,7 @@
+<html>
+<body>
+<p>Protocol plugin which supports retrieving documents via the HTTP protocol.</p>
+<p>This plugin is based on Jakarta Commons HttpClient library, and handles
+also HTTPS and cookies.</p>
+</body>
+</html>
diff --git a/src/test/org/apache/nutch/fetcher/TestFetcherOutput.java b/src/test/org/apache/nutch/fetcher/TestFetcherOutput.java
index fe76a03cb..dbb64c827 100644
--- a/src/test/org/apache/nutch/fetcher/TestFetcherOutput.java
+++ b/src/test/org/apache/nutch/fetcher/TestFetcherOutput.java
@@ -19,6 +19,8 @@ package org.apache.nutch.fetcher;
import java.io.*;
import org.apache.nutch.io.*;
import org.apache.nutch.pagedb.*;
+import org.apache.nutch.protocol.ProtocolStatus;
+
import junit.framework.TestCase;
/** Unit tests for FetcherOutput. */
@@ -32,7 +34,7 @@ public class TestFetcherOutput extends TestCase {
FetcherOutput o =
new FetcherOutput(new FetchListEntry(true, TestPage.getTestPage(),
anchors),
- TestMD5Hash.getTestHash(), FetcherOutput.SUCCESS);
+ TestMD5Hash.getTestHash(), ProtocolStatus.STATUS_SUCCESS);
TestWritable.testWritable(o);
diff --git a/src/test/org/apache/nutch/parse/TestParseData.java b/src/test/org/apache/nutch/parse/TestParseData.java
index 98058eb6c..09a374942 100644
--- a/src/test/org/apache/nutch/parse/TestParseData.java
+++ b/src/test/org/apache/nutch/parse/TestParseData.java
@@ -40,7 +40,7 @@ public class TestParseData extends TestCase {
metaData.put("Language", "en/us");
metaData.put("Charset", "UTF-8");
- ParseData r = new ParseData(title, outlinks, metaData);
+ ParseData r = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);
TestWritable.testWritable(r);
}
diff --git a/src/test/org/apache/nutch/tools/TestSegmentMergeTool.java b/src/test/org/apache/nutch/tools/TestSegmentMergeTool.java
index ebc4a5fae..28cf7fee4 100644
--- a/src/test/org/apache/nutch/tools/TestSegmentMergeTool.java
+++ b/src/test/org/apache/nutch/tools/TestSegmentMergeTool.java
@@ -22,17 +22,17 @@ import java.util.Random;
import org.apache.nutch.db.Page;
import org.apache.nutch.fetcher.FetcherOutput;
-import org.apache.nutch.io.ArrayFile;
import org.apache.nutch.io.MD5Hash;
import org.apache.nutch.fs.*;
import org.apache.nutch.segment.SegmentReader;
import org.apache.nutch.segment.SegmentWriter;
-import org.apache.nutch.util.*;
import org.apache.nutch.pagedb.FetchListEntry;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.ParseText;
import org.apache.nutch.protocol.Content;
+import org.apache.nutch.protocol.ProtocolStatus;
import junit.framework.TestCase;
@@ -81,7 +81,7 @@ public class TestSegmentMergeTool extends TestCase {
}
url += "/example.html";
FetchListEntry fle = new FetchListEntry(true, new Page(url, 1.0f), new String[] { "test" + rnd });
- FetcherOutput fo = new FetcherOutput(fle, MD5Hash.digest(url), FetcherOutput.SUCCESS);
+ FetcherOutput fo = new FetcherOutput(fle, MD5Hash.digest(url), ProtocolStatus.STATUS_SUCCESS);
StringBuffer content = new StringBuffer("<html><body><h1>Hello from Page " + i + "</h1>");
if (unique) {
content.append("<p>Created at epoch time: " + System.currentTimeMillis() + ", " + r.nextLong() + "</p>");
@@ -95,7 +95,7 @@ public class TestSegmentMergeTool extends TestCase {
meta.setProperty("Host", "http://localhost");
meta.setProperty("Connection", "Keep-alive, close");
Content co = new Content(url, "http://www.example.com", content.toString().getBytes("UTF-8"), "text/html", meta);
- ParseData pd = new ParseData("Hello from Page " + i, new Outlink[0], meta);
+ ParseData pd = new ParseData(ParseStatus.STATUS_SUCCESS, "Hello from Page " + i, new Outlink[0], meta);
StringBuffer text = new StringBuffer("Hello from Page" + i);
if (unique) {
text.append("\nCreated at epoch time: " + System.currentTimeMillis() + ", " + r.nextLong());