Apache Nutch is an extensible and scalable web crawler
First pass for removing deplicated code between protocol-http and protocol-httpclient plusing. Now these two plugins depend on the new lib-http plugin that tries to gather the maximum http logic code.
Jerome Charronea20d5be7a5b
diff --git a/src/java/org/apache/nutch/net/protocols/Response.java b/src/java/org/apache/nutch/net/protocols/Response.javaindex a7143b74d..a991ce112 100644--- a/src/java/org/apache/nutch/net/protocols/Response.java+++ b/src/java/org/apache/nutch/net/protocols/Response.java@@ -13,14 +13,18 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.net.protocols;+// JDK importsimport java.net.URL;+// Nutch imports+import org.apache.nutch.protocol.ContentProperties;-/** A response inteface. Makes all protocols model HTTP. */+/**+ * A response inteface. Makes all protocols model HTTP.+ */public interface Response {/** Returns the URL used to retrieve this response. */@@ -32,19 +36,10 @@ public interface Response {/** Returns the value of a named header. */public String getHeader(String name);+ /** Returns all the headers. */+ public ContentProperties getHeaders();+/** Returns the full content of the response. */public byte[] getContent();- /**- * Returns the compressed version of the content if the server- * transmitted a compressed version, or <code>null</code>- * otherwise.- */- public byte[] getCompressedContent();-- /**- * Returns the number of 100/Continue headers encountered- */- public int getNumContinues();-}diff --git a/src/plugin/build.xml b/src/plugin/build.xmlindex 20df737eb..6ae2fdb00 100755--- a/src/plugin/build.xml+++ b/src/plugin/build.xml@@ -6,13 +6,14 @@<!-- Build & deploy all the plugin jars. --><!-- ====================================================== --><target name="deploy">- <!--ant dir="analysis-de" target="deploy"/-->- <!--ant dir="analysis-fr" target="deploy"/-->+ <ant dir="analysis-de" target="deploy"/>+ <ant dir="analysis-fr" target="deploy"/><ant dir="clustering-carrot2" target="deploy"/><ant dir="creativecommons" target="deploy"/><ant dir="index-basic" target="deploy"/><ant dir="index-more" target="deploy"/><ant dir="languageidentifier" target="deploy"/>+ <ant dir="lib-http" target="deploy"/><ant dir="lib-jakarta-poi" target="deploy"/><ant dir="lib-lucene-analyzers" target="deploy"/><ant dir="nutch-extensionpoints" target="deploy"/>diff --git a/src/plugin/lib-http/build.xml b/src/plugin/lib-http/build.xmlnew file mode 100644index 000000000..f2ee0ef63--- /dev/null+++ b/src/plugin/lib-http/build.xml@@ -0,0 +1,7 @@+<?xml version="1.0"?>++<project name="lib-http" default="jar">++ <import file="../build-plugin.xml"/>++</project>diff --git a/src/plugin/lib-http/plugin.xml b/src/plugin/lib-http/plugin.xmlnew file mode 100644index 000000000..a2134ee71--- /dev/null+++ b/src/plugin/lib-http/plugin.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="UTF-8"?>+<!--+ ! A common framework for http protocol implementations+ !-->+<plugin+ id="lib-http"+ name="HTTP Framework"+ version="1.0"+ provider-name="org.apache.nutch">++ <runtime>+ <library name="lib-http.jar">+ <export name="*"/>+ </library>+ </runtime>++</plugin>diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.javanew file mode 100644index 000000000..00e767849--- /dev/null+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java@@ -0,0 +1,378 @@+/**+ * 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.http.api;++// Nutch imports+import java.io.IOException;+import java.net.InetAddress;+import java.net.URL;+import java.net.UnknownHostException;+import java.util.HashMap;+import java.util.LinkedList;+import java.util.logging.Level;+import java.util.logging.Logger;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;+import org.apache.nutch.net.protocols.Response;+import org.apache.nutch.protocol.Content;+import org.apache.nutch.protocol.Protocol;+import org.apache.nutch.protocol.ProtocolException;+import org.apache.nutch.protocol.ProtocolOutput;+import org.apache.nutch.protocol.ProtocolStatus;+import org.apache.nutch.util.NutchConf;+++/**+ * @author Jérôme Charron+ */+public abstract class HttpBase implements Protocol {+++ public static final int BUFFER_SIZE = 8 * 1024;++ public static String PROXY_HOST =+ NutchConf.get().get("http.proxy.host");++ public static int PROXY_PORT =+ NutchConf.get().getInt("http.proxy.port", 8080);++ public static boolean PROXY =+ (PROXY_HOST != null && PROXY_HOST.length() > 0);++ public static int TIMEOUT =+ NutchConf.get().getInt("http.timeout", 10000);++ public static int MAX_CONTENT =+ NutchConf.get().getInt("http.content.limit", 64 * 1024);++ public static int MAX_DELAYS =+ NutchConf.get().getInt("http.max.delays", 3);++ public static int MAX_THREADS_PER_HOST =+ NutchConf.get().getInt("fetcher.threads.per.host", 1);++ public static String AGENT_STRING =+ getAgentString();++ public static long SERVER_DELAY =+ (long) (NutchConf.get().getFloat("fetcher.server.delay", 1.0f) * 1000);+++ private static final byte[] EMPTY_CONTENT = new byte[0];++ /**+ * 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();++ /** The default logger */+ private final static Logger LOGGER = Logger.getLogger(HttpBase.class.getName());++ /** The specified logger */+ private Logger logger = LOGGER;+++ /** Creates a new instance of HttpBase */+ public HttpBase() {+ this(null);+ }++ /** Creates a new instance of HttpBase */+ public HttpBase(Logger logger) {+ if (logger != null) {+ this.logger = logger;+ }+ logger.info("http.proxy.host = " + PROXY_HOST);+ logger.info("http.proxy.port = " + PROXY_PORT);+ logger.info("http.timeout = " + TIMEOUT);+ logger.info("http.content.limit = " + MAX_CONTENT);+ logger.info("http.agent = " + AGENT_STRING);+ logger.info("fetcher.server.delay = " + SERVER_DELAY);+ logger.info("http.max.delays = " + MAX_DELAYS);+ }++ public ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum) {++ String urlString = url.toString();+ try {+ URL u = new URL(urlString);++ try {+ if (!RobotRulesParser.isAllowed(this, u)) {+ return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.ROBOTS_DENIED, url));+ }+ } catch (Throwable e) {+ // XXX Maybe bogus: assume this is allowed.+ logger.fine("Exception checking robot rules for " + url + ": " + e);+ }++ InetAddress addr = blockAddr(u);+ Response response;+ try {+ response = getResponse(u, datum, false); // make a request+ } finally {+ unblockAddr(addr);+ }++ int code = response.getCode();+ byte[] content = response.getContent();+ Content c = new Content(u.toString(), u.toString(),+ (content == null ? EMPTY_CONTENT : content),+ response.getHeader("Content-Type"),+ response.getHeaders());++ if (code == 200) { // got a good response+ return new ProtocolOutput(c); // return it++ } else if (code == 410) { // page is gone+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, "Http: " + code + " url=" + url));++ } else if (code >= 300 && code < 400) { // handle redirect+ String location = response.getHeader("Location");+ // some broken servers, such as MS IIS, use lowercase header name...+ if (location == null) location = response.getHeader("location");+ if (location == null) location = "";+ u = new URL(u, location);+ int protocolStatusCode;+ switch (code) {+ case 300: // multiple choices, preferred value in Location+ protocolStatusCode = ProtocolStatus.MOVED;+ break;+ case 301: // moved permanently+ case 305: // use proxy (Location is URL of proxy)+ protocolStatusCode = ProtocolStatus.MOVED;+ break;+ case 302: // found (temporarily moved)+ case 303: // see other (redirect after POST)+ case 307: // temporary redirect+ protocolStatusCode = ProtocolStatus.TEMP_MOVED;+ break;+ case 304: // not modified+ protocolStatusCode = ProtocolStatus.NOTMODIFIED;+ break;+ default:+ protocolStatusCode = ProtocolStatus.MOVED;+ }+ // handle this in the higher layer.+ return new ProtocolOutput(c, new ProtocolStatus(protocolStatusCode, u));+ } else if (code == 400) { // bad request, mark as GONE+ logger.fine("400 Bad request: " + u);+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, u));+ } else if (code == 401) { // requires authorization, but no valid auth provided.+ logger.fine("401 Authentication Required");+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.ACCESS_DENIED, "Authentication required: "+ + urlString));+ } else if (code == 404) {+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.NOTFOUND, u));+ } else if (code == 410) { // permanently GONE+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, u));+ } else {+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.EXCEPTION, "Http code=" + code + ", url="+ + u));+ }+ } catch (Throwable e) {+ e.printStackTrace();+ return new ProtocolOutput(null, new ProtocolStatus(e));+ }+ }+++ 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 HttpException("Exceeded http.max.delays: retry later.");++ long done = time.longValue();+ long now = System.currentTimeMillis();+ long sleep = 0;+ if (done == 0) { // address is still in use+ sleep = SERVER_DELAY; // wait at least delay++ } 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 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));+ }+ }+ }++ 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 String getAgentString() {++ String agentName = NutchConf.get().get("http.agent.name");+ String agentVersion = NutchConf.get().get("http.agent.version");+ String agentDesc = NutchConf.get().get("http.agent.description");+ String agentURL = NutchConf.get().get("http.agent.url");+ String agentEmail = NutchConf.get().get("http.agent.email");++ if ( (agentName == null) || (agentName.trim().length() == 0) )+ LOGGER.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();+ }++ protected static void main(HttpBase http, String[] args) throws Exception {+ boolean verbose = false;+ String url = null;++ String usage = "Usage: Http [-verbose] [-timeout N] url";++ if (args.length == 0) {+ System.err.println(usage);+ System.exit(-1);+ }++ for (int i = 0; i < args.length; i++) { // parse command line+ if (args[i].equals("-timeout")) { // found -timeout option+ 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];+ }++ if (verbose) {+ LOGGER.setLevel(Level.FINE);+ }++ ProtocolOutput out = http.getProtocolOutput(new UTF8(url), new CrawlDatum());+ Content content = out.getContent();++ System.out.println("Status: " + out.getStatus());+ if (content != null) {+ System.out.println("Content Type: " + content.getContentType());+ System.out.println("Content Length: " + content.get("Content-Length"));+ System.out.println("Content:");+ String text = new String(content.getContent());+ System.out.println(text);+ }++ }+++ protected abstract Response getResponse(URL url,+ CrawlDatum datum,+ boolean followRedirects)+ throws ProtocolException, IOException;++}diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpException.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.javaold mode 100755new mode 100644similarity index 94%rename from src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpException.javarename to src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.javaindex d08e704f2..3ecb12816--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpException.java+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java@@ -13,11 +13,12 @@* See the License for the specific language governing permissions and* limitations under the License.*/+package org.apache.nutch.protocol.http.api;-package org.apache.nutch.protocol.http;-+// Nutch importsimport org.apache.nutch.protocol.ProtocolException;+public class HttpException extends ProtocolException {public HttpException() {diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.javasimilarity index 97%rename from src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.javarename to src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.javaindex 31728974a..31e74b389 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java@@ -13,31 +13,29 @@* See the License for the specific language governing permissions and* limitations under the License.*/+package org.apache.nutch.protocol.http.api;-package org.apache.nutch.protocol.httpclient;-+// JDK importsimport 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;+// Nutch importsimport org.apache.nutch.util.NutchConf;import org.apache.nutch.util.LogFormatter;import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.net.protocols.Response;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@@ -370,7 +368,7 @@ public class RobotRulesParser {return rules;}- public static boolean isAllowed(URL url)+ public static boolean isAllowed(HttpBase http, URL url)throws ProtocolException, IOException {String host = url.getHost();@@ -380,8 +378,8 @@ public class RobotRulesParser {if (robotRules == null) { // cache missLOG.fine("cache miss " + url);try {- HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"),- new CrawlDatum(), true);+ Response response = http.getResponse(new URL(url, "/robots.txt"),+ new CrawlDatum(), true);if (response.getCode() == 200) // found rules: parse themrobotRules = new RobotRulesParser().parseRules(response.getContent());diff --git a/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestRobotRulesParser.java b/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.javasimilarity index 98%rename from src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestRobotRulesParser.javarename to src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.javaindex 041bb6a11..f5c536e58 100644--- a/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestRobotRulesParser.java+++ b/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java@@ -14,9 +14,9 @@* limitations under the License.*/-package org.apache.nutch.protocol.http;+package org.apache.nutch.protocol.http.api;-import org.apache.nutch.protocol.http.RobotRulesParser.RobotRuleSet;+import org.apache.nutch.protocol.http.api.RobotRulesParser.RobotRuleSet;import junit.framework.TestCase;diff --git a/src/plugin/protocol-http/build.xml b/src/plugin/protocol-http/build.xmlindex 1306e37cb..201c33f5e 100755--- a/src/plugin/protocol-http/build.xml+++ b/src/plugin/protocol-http/build.xml@@ -4,4 +4,10 @@<import file="../build-plugin.xml"/>+ <path id="plugin.deps">+ <fileset dir="../../../build/lib-http">+ <include name="*.jar" />+ </fileset>+ </path>+</project>diff --git a/src/plugin/protocol-http/plugin.xml b/src/plugin/protocol-http/plugin.xmlindex b4834a560..229068dff 100755--- a/src/plugin/protocol-http/plugin.xml+++ b/src/plugin/protocol-http/plugin.xml@@ -13,6 +13,7 @@<requires><import plugin="nutch-extensionpoints"/>+ <import plugin="lib-http"/></requires><extension id="org.apache.nutch.protocol.http"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.javaindex f7fdfcf32..c9d038ffe 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@@ -13,27 +13,24 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.protocol.http;-import java.net.MalformedURLException;+// JDK imports+import java.io.IOException;import java.net.URL;-import java.net.InetAddress;-import java.net.UnknownHostException;-import java.util.HashMap;-import java.util.LinkedList;import java.util.logging.Level;import java.util.logging.Logger;+// Nutch imports+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.net.protocols.Response;+import org.apache.nutch.protocol.ProtocolException;+import org.apache.nutch.protocol.http.api.HttpBase;import org.apache.nutch.util.LogFormatter;import org.apache.nutch.util.NutchConf;-import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.protocol.*;-/** An implementation of the Http protocol. */-public class Http implements Protocol {+public class Http extends HttpBase {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.net.Http");@@ -43,259 +40,18 @@ public class Http implements Protocol {LOG.setLevel(Level.FINE);}- static final int BUFFER_SIZE = 8 * 1024;-- private static final int MAX_REDIRECTS =- NutchConf.get().getInt("http.redirect.max", 3);-- 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 String AGENT_STRING = getAgentString();-- static long SERVER_DELAY =- (long)(NutchConf.get().getFloat("fetcher.server.delay", 1.0f) * 1000);-- 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("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 HttpException("Exceeded http.max.delays: retry later.");-- long done = time.longValue();- long now = System.currentTimeMillis();- long sleep = 0;- if (done == 0) { // address is still in use- sleep = SERVER_DELAY; // wait at least delay-- } 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;- }- }- }+ public Http() {+ super(LOG);}- 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(UTF8 url, CrawlDatum datum) {- String urlString = url.toString();- try {- URL u = new URL(urlString);-- int redirects = 0;- while (true) {-- if (!RobotRulesParser.isAllowed(u))- throw new HttpException("Blocked by robots.txt");-- InetAddress addr = blockAddr(u);- HttpResponse response;- try {- response = new HttpResponse(u, datum); // 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- throw new HttpException("Http: " + code);-- } else if (code >= 300 && code < 400) { // handle redirect- if (redirects == MAX_REDIRECTS)- throw new HttpException("Too many redirects: " + urlString);- u = new URL(u, response.getHeader("Location"));- redirects++;- LOG.fine("redirect to " + u);-- } else { // convert to exception- throw new HttpError(code);- }- }- } catch (Exception e) {- return new ProtocolOutput(null, new ProtocolStatus(e));- }- }-- private static String getAgentString() {- String agentName = NutchConf.get().get("http.agent.name");- String agentVersion = NutchConf.get().get("http.agent.version");- String agentDesc = NutchConf.get().get("http.agent.description");- String agentURL = NutchConf.get().get("http.agent.url");- String agentEmail = NutchConf.get().get("http.agent.email");-- 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);- }-- Content content = http.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();-- 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);+ main(new Http(), args);+ }+ protected Response getResponse(URL url, CrawlDatum datum, boolean redirect)+ throws ProtocolException, IOException {+ return new HttpResponse(url, datum);}}diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpError.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpError.javadeleted file mode 100644index da491c70e..000000000--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpError.java+++ /dev/null@@ -1,32 +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.protocol.http;--/** 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-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.javaindex 6cbe0060f..f209b6885 100644--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java@@ -13,9 +13,9 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package org.apache.nutch.protocol.http;+// JDK importsimport java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.EOFException;@@ -28,45 +28,32 @@ import java.net.Socket;import java.net.URL;import java.util.Map;import java.util.TreeMap;-import java.util.Properties;import java.util.logging.Level;+// Nutch importsimport org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.protocol.Content;+import org.apache.nutch.net.protocols.Response;import org.apache.nutch.protocol.ContentProperties;import org.apache.nutch.protocol.ProtocolException;-+import org.apache.nutch.protocol.http.api.HttpException;import org.apache.nutch.util.GZIPUtils;/** An HTTP response. */-public class HttpResponse {+public class HttpResponse implements Response {+ private URL url;private String orig;private String base;private byte[] content;private int code;private ContentProperties headers = new ContentProperties();- /** 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() {- return new Content(orig, base, content,- getHeader("Content-Type"),- headers);- }public HttpResponse(URL url, CrawlDatum datum)throws ProtocolException, IOException {-++ this.url = url;this.orig = url.toString();this.base = url.toString();@@ -182,6 +169,36 @@ public class HttpResponse {}++ /* ------------------------- *+ * <implementation:Response> *+ * ------------------------- */++ public URL getUrl() {+ return url;+ }++ public int getCode() {+ return code;+ }++ public String getHeader(String name) {+ return (String) headers.get(name);+ }++ public ContentProperties getHeaders() {+ return headers;+ }++ public byte[] getContent() {+ return content;+ }++ /* ------------------------- *+ * <implementation:Response> *+ * ------------------------- */++private void readPlainContent(InputStream in)throws HttpException, IOException {diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.javadeleted file mode 100644index 5dd8d879f..000000000--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java+++ /dev/null@@ -1,488 +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.protocol.http;--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.crawl.CrawlDatum;-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 boolean ALLOW_FORBIDDEN =- NutchConf.get().getBoolean("http.robots.403.allow", false);-- private static final int MAX_REDIRECTS =- NutchConf.get().getInt("http.redirect.max", 3);-- 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- int redirects = 0;- do {- HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"), new CrawlDatum());-- int code = response.getCode();-- if (code == 200) { // found rules: parse them- robotRules = new RobotRulesParser().parseRules(response.getContent());- } else if ( (code == 403) && (!ALLOW_FORBIDDEN) ) {- robotRules = FORBID_ALL_RULES; // use forbid all- } else if (code >= 300 && code < 400) { // handle redirect- if (redirects == MAX_REDIRECTS) {- robotRules = EMPTY_RULES;- } else {- url = new URL(url, response.getHeader("Location"));- LOG.fine("redirect to " + url);- redirects++;- }- } else {- robotRules = EMPTY_RULES; // use default rules- }- } while (robotRules == null);-- 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/build.xml b/src/plugin/protocol-httpclient/build.xmlindex 146415550..d8aba64b0 100644--- a/src/plugin/protocol-httpclient/build.xml+++ b/src/plugin/protocol-httpclient/build.xml@@ -4,4 +4,10 @@<import file="../build-plugin.xml"/>+ <path id="plugin.deps">+ <fileset dir="../../../build/lib-http">+ <include name="*.jar" />+ </fileset>+ </path>+</project>diff --git a/src/plugin/protocol-httpclient/plugin.xml b/src/plugin/protocol-httpclient/plugin.xmlindex ba0b14c8f..e798c26e6 100644--- a/src/plugin/protocol-httpclient/plugin.xml+++ b/src/plugin/protocol-httpclient/plugin.xml@@ -15,6 +15,7 @@<requires><import plugin="nutch-extensionpoints"/>+ <import plugin="lib-http"/></requires><extension id="org.apache.nutch.protocol.httpclient"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.javaindex f11fd5a64..2c3bb5bf5 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java@@ -1,18 +1,28 @@-/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */-/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */-+/**+ * 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.net.InetAddress;-import java.net.MalformedURLException;+// JDK imports+import java.io.IOException;import java.net.URL;-import java.net.UnknownHostException;import java.util.ArrayList;-import java.util.HashMap;-import java.util.LinkedList;import java.util.logging.Level;import java.util.logging.Logger;+// HTTP Client importsimport org.apache.commons.httpclient.Credentials;import org.apache.commons.httpclient.Header;import org.apache.commons.httpclient.HostConfiguration;@@ -22,14 +32,17 @@ import org.apache.commons.httpclient.NTCredentials;import org.apache.commons.httpclient.auth.AuthScope;import org.apache.commons.httpclient.params.HttpConnectionManagerParams;import org.apache.commons.httpclient.protocol.Protocol;++// Nutch importsimport org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.protocol.*;+import org.apache.nutch.net.protocols.Response;+import org.apache.nutch.protocol.ProtocolException;+import org.apache.nutch.protocol.http.api.HttpBase;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 class Http extends HttpBase {public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.net.Http");@@ -42,8 +55,9 @@ public class Http implements org.apache.nutch.protocol.Protocol {}}- static final int BUFFER_SIZE = 8 * 1024;- private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();+ private static MultiThreadedHttpConnectionManager connectionManager =+ new MultiThreadedHttpConnectionManager();+private static HttpClient client;static synchronized HttpClient getClient() {@@ -52,291 +66,30 @@ public class Http implements org.apache.nutch.protocol.Protocol {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 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 HttpException("Exceeded http.max.delays: retry later.");-- long done = time.longValue();- long now = System.currentTimeMillis();- long sleep = 0;- if (done == 0) { // address is still in use- sleep = SERVER_DELAY; // wait at least delay-- } 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 Http() {+ super(LOG);}- public ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum) {- String urlString = url.toString();- try {- URL u = new URL(urlString);-- try {- if (!RobotRulesParser.isAllowed(u))- 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(u);- HttpResponse response;- try {- response = new HttpResponse(u, datum); // make a request- } finally {- unblockAddr(addr);- }-- int code = response.getCode();- Content c = response.toContent();-- if (code == 200) { // got a good response- return new ProtocolOutput(c); // return it-- } else if (code == 410) { // page is gone- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, "Http: " + code + " url=" + url));-- } else if (code >= 300 && code < 400) { // handle redirect- String location = response.getHeader("Location");- // some broken servers, such as MS IIS, use lowercase header name...- if (location == null) location = response.getHeader("location");- if (location == null) location = "";- u = new URL(u, location);- int protocolStatusCode;- switch (code) {- case 300: // multiple choices, preferred value in Location- protocolStatusCode = ProtocolStatus.MOVED;- break;- case 301: // moved permanently- case 305: // use proxy (Location is URL of proxy)- protocolStatusCode = ProtocolStatus.MOVED;- break;- case 302: // found (temporarily moved)- case 303: // see other (redirect after POST)- case 307: // temporary redirect- protocolStatusCode = ProtocolStatus.TEMP_MOVED;- break;- case 304: // not modified- protocolStatusCode = ProtocolStatus.NOTMODIFIED;- break;- default:- protocolStatusCode = ProtocolStatus.MOVED;- }- // handle this in the higher layer.- return new ProtocolOutput(c, new ProtocolStatus(protocolStatusCode, u));- } else if (code == 400) { // bad request, mark as GONE- LOG.fine("400 Bad request: " + u);- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, u));- } else if (code == 401) { // requires authorization, but no valid auth provided.- LOG.fine("401 Authentication Required");- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.ACCESS_DENIED, "Authentication required: "- + urlString));- } else if (code == 404) {- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.NOTFOUND, u));- } else if (code == 410) { // permanently GONE- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, u));- } else {- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.EXCEPTION, "Http code=" + code + ", url="- + u));- }- } 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(new UTF8(url), new CrawlDatum());- Content content = out.getContent();-- System.out.println("Status: " + out.getStatus());- if (content != null) {- System.out.println("Content Type: " + content.getContentType());- System.out.println("Content Length: " + content.get("Content-Length"));- System.out.println("Content:");- String text = new String(content.getContent());- System.out.println(text);- }-+ main(new Http(), args);}+ protected Response getResponse(URL url, CrawlDatum datum, boolean redirect)+ throws ProtocolException, IOException {+ return new HttpResponse(url, datum, redirect);+ }+private static void configureClient() {// get a client isntance -- we just need one.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.javadeleted file mode 100644index 3fd5cbbe3..000000000--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpError.java+++ /dev/null@@ -1,19 +0,0 @@-/* 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.javadeleted file mode 100644index 118ac29a6..000000000--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpException.java+++ /dev/null@@ -1,26 +0,0 @@-/* 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.javaindex 3a5dd10d0..13789f992 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java@@ -1,71 +1,65 @@-/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */-/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */-+/**+ * 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 org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.protocol.ContentProperties;+// JDK imports+import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.net.URL;+// HTTP Client importsimport org.apache.commons.httpclient.Header;import org.apache.commons.httpclient.HttpVersion;-import org.apache.commons.httpclient.cookie.CookiePolicy;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.params.HttpMethodParams;-import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.net.URL;+// Nutch imports+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.net.protocols.Response;+import org.apache.nutch.protocol.ContentProperties;+/*** An HTTP response.*/-public class HttpResponse {+public class HttpResponse implements Response {+ private URL url;+private String orig;private String base;private byte[] content;- private static final byte[] EMPTY_CONTENT = new byte[0];private int code;private ContentProperties headers = new ContentProperties();- /**- * 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() {- return new Content(orig, base,- (content == null ? EMPTY_CONTENT : content),- getHeader("Content-Type"),- headers);- }-+public HttpResponse(URL url, CrawlDatum datum) throws IOException {this(url, datum, false);}+HttpResponse(URL url, CrawlDatum datum, boolean followRedirects) throws IOException {+ this.url = url;this.base = url.toString();this.orig = url.toString();GetMethod get = new GetMethod(this.orig);@@ -120,6 +114,37 @@ public class HttpResponse {}}++ /* ------------------------- *+ * <implementation:Response> *+ * ------------------------- */++ public URL getUrl() {+ return url;+ }++ public int getCode() {+ return code;+ }++ public String getHeader(String name) {+ return (String) headers.get(name);+ }++ public ContentProperties getHeaders() {+ return headers;+ }++ public byte[] getContent() {+ return content;+ }++ /* -------------------------- *+ * </implementation:Response> *+ * -------------------------- */+++private int calculateTryToRead(int totalRead) {int tryToRead = Http.BUFFER_SIZE;if (Http.MAX_CONTENT <= 0) {