You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nutch.apache.org by je...@apache.org on 2006/01/09 01:14:07 UTC

svn commit: r367137 - in /lucene/nutch/trunk/src: java/org/apache/nutch/net/protocols/ plugin/ plugin/lib-http/ plugin/lib-http/src/ plugin/lib-http/src/java/ plugin/lib-http/src/java/org/ plugin/lib-http/src/java/org/apache/ plugin/lib-http/src/java/o...

Author: jerome
Date: Sun Jan  8 16:13:42 2006
New Revision: 367137

URL: http://svn.apache.org/viewcvs?rev=367137&view=rev
Log:
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.

Added:
    lucene/nutch/trunk/src/plugin/lib-http/
    lucene/nutch/trunk/src/plugin/lib-http/build.xml   (with props)
    lucene/nutch/trunk/src/plugin/lib-http/plugin.xml   (with props)
    lucene/nutch/trunk/src/plugin/lib-http/src/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java   (with props)
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java   (with props)
    lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java   (with props)
    lucene/nutch/trunk/src/plugin/lib-http/src/test/
    lucene/nutch/trunk/src/plugin/lib-http/src/test/org/
    lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/
    lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/
    lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/
    lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/
    lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/
    lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java   (with props)
Removed:
    lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpError.java
    lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpException.java
    lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java
    lucene/nutch/trunk/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestRobotRulesParser.java
    lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpError.java
    lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpException.java
    lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java
Modified:
    lucene/nutch/trunk/src/java/org/apache/nutch/net/protocols/Response.java
    lucene/nutch/trunk/src/plugin/build.xml
    lucene/nutch/trunk/src/plugin/protocol-http/build.xml
    lucene/nutch/trunk/src/plugin/protocol-http/plugin.xml
    lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
    lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
    lucene/nutch/trunk/src/plugin/protocol-httpclient/build.xml
    lucene/nutch/trunk/src/plugin/protocol-httpclient/plugin.xml
    lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
    lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java

Modified: lucene/nutch/trunk/src/java/org/apache/nutch/net/protocols/Response.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/java/org/apache/nutch/net/protocols/Response.java?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/java/org/apache/nutch/net/protocols/Response.java (original)
+++ lucene/nutch/trunk/src/java/org/apache/nutch/net/protocols/Response.java Sun Jan  8 16:13:42 2006
@@ -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 imports
 import 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 @@
   /** 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();
 
 }

Modified: lucene/nutch/trunk/src/plugin/build.xml
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/build.xml?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/build.xml (original)
+++ lucene/nutch/trunk/src/plugin/build.xml Sun Jan  8 16:13:42 2006
@@ -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"/>

Added: lucene/nutch/trunk/src/plugin/lib-http/build.xml
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/lib-http/build.xml?rev=367137&view=auto
==============================================================================
--- lucene/nutch/trunk/src/plugin/lib-http/build.xml (added)
+++ lucene/nutch/trunk/src/plugin/lib-http/build.xml Sun Jan  8 16:13:42 2006
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+
+<project name="lib-http" default="jar">
+
+  <import file="../build-plugin.xml"/>
+
+</project>

Propchange: lucene/nutch/trunk/src/plugin/lib-http/build.xml
------------------------------------------------------------------------------
    svn:eol-style = native

Added: lucene/nutch/trunk/src/plugin/lib-http/plugin.xml
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/lib-http/plugin.xml?rev=367137&view=auto
==============================================================================
--- lucene/nutch/trunk/src/plugin/lib-http/plugin.xml (added)
+++ lucene/nutch/trunk/src/plugin/lib-http/plugin.xml Sun Jan  8 16:13:42 2006
@@ -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>

Propchange: lucene/nutch/trunk/src/plugin/lib-http/plugin.xml
------------------------------------------------------------------------------
    svn:eol-style = native

Added: lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java?rev=367137&view=auto
==============================================================================
--- lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java (added)
+++ lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java Sun Jan  8 16:13:42 2006
@@ -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&eacute;r&ocirc;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;
+  
+}

Propchange: lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java?rev=367137&view=auto
==============================================================================
--- lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java (added)
+++ lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java Sun Jan  8 16:13:42 2006
@@ -0,0 +1,40 @@
+/**
+ * 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 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);
+  }
+
+}

Propchange: lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpException.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java?rev=367137&view=auto
==============================================================================
--- lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java (added)
+++ lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java Sun Jan  8 16:13:42 2006
@@ -0,0 +1,476 @@
+/**
+ * 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;
+
+// JDK imports
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.LineNumberReader;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.StringTokenizer;
+import java.util.logging.Logger;
+
+// Nutch imports
+import 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
+ * 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 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(HttpBase http, URL url)
+    throws ProtocolException, IOException {
+
+    String host = url.getHost();
+
+    RobotRuleSet robotRules = (RobotRuleSet)CACHE.get(host);
+
+    if (robotRules == null) {                     // cache miss
+      LOG.fine("cache miss " + url);
+      try {
+        Response response = http.getResponse(new URL(url, "/robots.txt"),
+                                             new CrawlDatum(), true);
+
+        if (response.getCode() == 200)               // found rules: parse them
+          robotRules = new RobotRulesParser().parseRules(response.getContent());
+        else if ( (response.getCode() == 403) && (!ALLOW_FORBIDDEN) )
+          robotRules = 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();
+    }
+  }
+
+}

Propchange: lucene/nutch/trunk/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java?rev=367137&view=auto
==============================================================================
--- lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java (added)
+++ lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java Sun Jan  8 16:13:42 2006
@@ -0,0 +1,246 @@
+/**
+ * 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;
+
+import org.apache.nutch.protocol.http.api.RobotRulesParser.RobotRuleSet;
+
+import junit.framework.TestCase;
+
+public class TestRobotRulesParser extends TestCase {
+  private static final String LF= "\n";
+  private static final String CR= "\r";
+  private static final String CRLF= "\r\n";
+  
+
+  private static final String[] ROBOTS_STRINGS= new String[] {
+    "User-Agent: Agent1 #foo" + CR 
+    + "Disallow: /a" + CR 
+    + "Disallow: /b/a" + CR 
+    + "#Disallow: /c" + CR 
+    + "" + CR 
+    + "" + CR 
+    + "User-Agent: Agent2 Agent3#foo" + CR 
+    + "User-Agent: Agent4" + CR 
+    + "Disallow: /d" + CR 
+    + "Disallow: /e/d/" + CR
+    + "" + CR 
+    + "User-Agent: *" + CR 
+    + "Disallow: /foo/bar/" + CR,
+  };
+
+  private static final String[] AGENT_STRINGS= new String[] {
+    "Agent1",
+    "Agent2",
+    "Agent3",
+    "Agent4",
+    "Agent5",
+  };
+
+  private static final boolean[][] NOT_IN_ROBOTS_STRING= new boolean[][] {
+    { 
+      false, 
+      false,
+      false,
+      false,
+      true,
+    }
+  };
+
+  private static final String[] TEST_PATHS= new String[] {
+    "/a",
+    "/a/",
+    "/a/bloh/foo.html",
+    "/b",
+    "/b/a",
+    "/b/a/index.html",
+    "/b/b/foo.html",
+    "/c",
+    "/c/a",
+    "/c/a/index.html",
+    "/c/b/foo.html",
+    "/d",
+    "/d/a",
+    "/e/a/index.html",
+    "/e/d",
+    "/e/d/foo.html",
+    "/e/doh.html",
+    "/f/index.html",
+    "/foo/bar/baz.html",  
+    "/f/",
+  };
+
+  private static final boolean[][][] ALLOWED= new boolean[][][] {
+    { // ROBOTS_STRINGS[0]
+      { // Agent1
+	false,  // "/a",	      
+	false,  // "/a/",	      
+	false,  // "/a/bloh/foo.html"
+	true,   // "/b",	      
+	false,  // "/b/a",	      
+	false,  // "/b/a/index.html",
+	true,   // "/b/b/foo.html",  
+	true,   // "/c",	      
+	true,   // "/c/a",	      
+	true,   // "/c/a/index.html",
+	true,   // "/c/b/foo.html",  
+	true,   // "/d",	      
+	true,   // "/d/a",	      
+	true,   // "/e/a/index.html",
+	true,   // "/e/d",	      
+	true,   // "/e/d/foo.html",  
+	true,   // "/e/doh.html",    
+	true,   // "/f/index.html",  
+	true,   // "/foo/bar.html",  
+	true,   // "/f/",  
+      }, 
+      { // Agent2
+	true,   // "/a",	      
+	true,   // "/a/",	      
+	true,   // "/a/bloh/foo.html"
+	true,   // "/b",	      
+	true,   // "/b/a",	      
+	true,   // "/b/a/index.html",
+	true,   // "/b/b/foo.html",  
+	true,   // "/c",	      
+	true,   // "/c/a",	      
+	true,   // "/c/a/index.html",
+	true,   // "/c/b/foo.html",  
+	false,  // "/d",	      
+	false,  // "/d/a",	      
+	true,   // "/e/a/index.html",
+	true,   // "/e/d",	      
+	false,  // "/e/d/foo.html",  
+	true,   // "/e/doh.html",    
+	true,   // "/f/index.html",  
+	true,   // "/foo/bar.html",  
+	true,   // "/f/",  
+      },
+      { // Agent3
+	true,   // "/a",	      
+	true,   // "/a/",	      
+	true,   // "/a/bloh/foo.html"
+	true,   // "/b",	      
+	true,   // "/b/a",	      
+	true,   // "/b/a/index.html",
+	true,   // "/b/b/foo.html",  
+	true,   // "/c",	      
+	true,   // "/c/a",	      
+	true,   // "/c/a/index.html",
+	true,   // "/c/b/foo.html",  
+	false,  // "/d",	      
+	false,  // "/d/a",	      
+	true,   // "/e/a/index.html",
+	true,   // "/e/d",	      
+	false,  // "/e/d/foo.html",  
+	true,   // "/e/doh.html",    
+	true,   // "/f/index.html",  
+	true,   // "/foo/bar.html",  
+	true,   // "/f/",  
+      },
+      { // Agent4
+	true,   // "/a",	      
+	true,   // "/a/",	      
+	true,   // "/a/bloh/foo.html"
+	true,   // "/b",	      
+	true,   // "/b/a",	      
+	true,   // "/b/a/index.html",
+	true,   // "/b/b/foo.html",  
+	true,   // "/c",	      
+	true,   // "/c/a",	      
+	true,   // "/c/a/index.html",
+	true,   // "/c/b/foo.html",  
+	false,  // "/d",	      
+	false,  // "/d/a",	      
+	true,   // "/e/a/index.html",
+	true,   // "/e/d",	      
+	false,  // "/e/d/foo.html",  
+	true,   // "/e/doh.html",    
+	true,   // "/f/index.html",  
+	true,   // "/foo/bar.html",  
+	true,   // "/f/",  
+      },
+      { // Agent5/"*"
+	true,   // "/a",	      
+	true,   // "/a/",	      
+	true,   // "/a/bloh/foo.html"
+	true,   // "/b",	      
+	true,   // "/b/a",	      
+	true,   // "/b/a/index.html",
+	true,   // "/b/b/foo.html",  
+	true,   // "/c",	      
+	true,   // "/c/a",	      
+	true,   // "/c/a/index.html",
+	true,   // "/c/b/foo.html",  
+	true,   // "/d",	      
+	true,   // "/d/a",	      
+	true,   // "/e/a/index.html",
+	true,   // "/e/d",	      
+	true,   // "/e/d/foo.html",  
+	true,   // "/e/doh.html",    
+	true,   // "/f/index.html",  
+	false,  // "/foo/bar.html",  
+	true,   // "/f/",  
+      }
+    }
+  };
+ 
+  public TestRobotRulesParser(String name) {
+    super(name);
+  }
+
+  public void testRobotsOneAgent() {
+    for (int i= 0; i < ROBOTS_STRINGS.length; i++) {
+      for (int j= 0; j < AGENT_STRINGS.length; j++) {
+	testRobots(i, new String[] { AGENT_STRINGS[j] },
+		   TEST_PATHS, ALLOWED[i][j]);
+      }
+    }
+  }
+
+  public void testRobotsTwoAgents() {
+    for (int i= 0; i < ROBOTS_STRINGS.length; i++) {
+      for (int j= 0; j < AGENT_STRINGS.length; j++) {
+	for (int k= 0; k < AGENT_STRINGS.length; k++) {
+	  int key= j;
+	  if (NOT_IN_ROBOTS_STRING[i][j])
+	    key= k;
+	  testRobots(i, new String[] { AGENT_STRINGS[j], AGENT_STRINGS[k] },
+		     TEST_PATHS, ALLOWED[i][key]);
+	}
+      }
+    }
+  }
+
+  // helper
+
+  public void testRobots(int robotsString, String[] agents, String[] paths, 
+			 boolean[] allowed) {
+    String agentsString= agents[0];
+    for (int i= 1; i < agents.length; i++)
+      agentsString= agentsString + "," + agents[i];
+    RobotRulesParser p= new RobotRulesParser(agents);
+    RobotRuleSet rules= p.parseRules(ROBOTS_STRINGS[robotsString].getBytes());
+    for (int i= 0; i < paths.length; i++) {
+      assertTrue("testing robots file "+robotsString+", on agents ("
+		 + agentsString + "), and path " + TEST_PATHS[i] + "; got " 
+		 + rules.isAllowed(TEST_PATHS[i]) + ", rules are: " + LF
+				   + rules,
+		 rules.isAllowed(TEST_PATHS[i]) == allowed[i]);
+    }
+  }
+
+}

Propchange: lucene/nutch/trunk/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: lucene/nutch/trunk/src/plugin/protocol-http/build.xml
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-http/build.xml?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-http/build.xml (original)
+++ lucene/nutch/trunk/src/plugin/protocol-http/build.xml Sun Jan  8 16:13:42 2006
@@ -4,4 +4,10 @@
 
   <import file="../build-plugin.xml"/>
 
+  <path id="plugin.deps">
+    <fileset dir="../../../build/lib-http">
+      <include name="*.jar" />
+    </fileset>
+  </path>
+
 </project>

Modified: lucene/nutch/trunk/src/plugin/protocol-http/plugin.xml
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-http/plugin.xml?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-http/plugin.xml (original)
+++ lucene/nutch/trunk/src/plugin/protocol-http/plugin.xml Sun Jan  8 16:13:42 2006
@@ -13,6 +13,7 @@
 
    <requires>
       <import plugin="nutch-extensionpoints"/>
+      <import plugin="lib-http"/>
    </requires>
 
    <extension id="org.apache.nutch.protocol.http"

Modified: lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java (original)
+++ lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java Sun Jan  8 16:13:42 2006
@@ -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 @@
       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);
   }
 
 }

Modified: lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java (original)
+++ lucene/nutch/trunk/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java Sun Jan  8 16:13:42 2006
@@ -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 imports
 import java.io.BufferedInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.EOFException;
@@ -28,45 +28,32 @@
 import java.net.URL;
 import java.util.Map;
 import java.util.TreeMap;
-import java.util.Properties;
 import java.util.logging.Level;
 
+// Nutch imports
 import 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();
 
@@ -181,6 +168,36 @@
     }
 
   }
+
+  
+  /* ------------------------- *
+   * <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 {

Modified: lucene/nutch/trunk/src/plugin/protocol-httpclient/build.xml
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-httpclient/build.xml?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-httpclient/build.xml (original)
+++ lucene/nutch/trunk/src/plugin/protocol-httpclient/build.xml Sun Jan  8 16:13:42 2006
@@ -4,4 +4,10 @@
 
   <import file="../build-plugin.xml"/>
 
+  <path id="plugin.deps">
+    <fileset dir="../../../build/lib-http">
+      <include name="*.jar" />
+    </fileset>
+  </path>
+
 </project>

Modified: lucene/nutch/trunk/src/plugin/protocol-httpclient/plugin.xml
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-httpclient/plugin.xml?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-httpclient/plugin.xml (original)
+++ lucene/nutch/trunk/src/plugin/protocol-httpclient/plugin.xml Sun Jan  8 16:13:42 2006
@@ -15,6 +15,7 @@
 
    <requires>
       <import plugin="nutch-extensionpoints"/>
+      <import plugin="lib-http"/>
    </requires>
 
    <extension id="org.apache.nutch.protocol.httpclient"

Modified: lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java (original)
+++ lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java Sun Jan  8 16:13:42 2006
@@ -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 imports
 import 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.auth.AuthScope;
 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
 import org.apache.commons.httpclient.protocol.Protocol;
+
+// Nutch imports
 import 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 @@
     }
   }
 
-  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 @@
     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++;
-    }
+  public Http() {
+    super(LOG);
   }
 
-  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(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.

Modified: lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java
URL: http://svn.apache.org/viewcvs/lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java?rev=367137&r1=367136&r2=367137&view=diff
==============================================================================
--- lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java (original)
+++ lucene/nutch/trunk/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java Sun Jan  8 16:13:42 2006
@@ -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 imports
 import 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);
@@ -119,6 +113,37 @@
       get.releaseConnection();
     }
   }
+
+  
+  /* ------------------------- *
+   * <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;



Re: svn commit: r367137 - in /lucene/nutch/trunk/src: java/org/apache/nutch/net/protocols/ plugin/ plugin/lib-http/ plugin/lib-http/src/ plugin/lib-http/src/java/ plugin/lib-http/src/java/org/ plugin/lib-http/src/java/org/apache/ plugin/lib-http/src/java/o...

Posted by Doug Cutting <cu...@nutch.org>.
jerome@apache.org wrote:
> --- lucene/nutch/trunk/src/plugin/build.xml (original)
> +++ lucene/nutch/trunk/src/plugin/build.xml Sun Jan  8 16:13:42 2006
> @@ -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"/>

Was this change intentional?  It looks unrelated.

Otherwise, this looks great!

Doug