morgand     01/08/13 12:43:23

  Added:       latka/src/java/org/apache/commons/latka/http Request.java
                        RequestImpl.java Response.java ResponseImpl.java
                        Session.java SessionImpl.java
  Log:
  initial Latka files, more batch scripts and stuff to come
  
  Revision  Changes    Path
  1.1                  
jakarta-commons-sandbox/latka/src/java/org/apache/commons/latka/http/Request.java
  
  Index: Request.java
  ===================================================================
  package org.apache.commons.latka.http;
  
  
  import java.net.URL;
  import java.io.IOException;
  import java.util.Map;
  
  import org.apache.commons.httpclient.HttpMethod;
  
  
  /**
   * A Latka Request represents a request from an HTTP server.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]";>Doug Sale</a>
   * @author <a href="mailto:[EMAIL PROTECTED]";>Morgan Delagrange</a>
   */
  public interface Request {
  
    /** An integer representing the HTTP GET method */
    public static final int HTTP_METHOD_GET = 0;
    /** An integer representing the HTTP POST method */
    public static final int HTTP_METHOD_POST = 1;
  
    /**
     * Execute this HTTP request.
     *
     * @return a Response object represnting the HTTP response to the request
     *
     * @throws java.io.IOException ...
     */
    public Response execute() throws IOException;
  
    /**
     * @return the label associated with this request
     */
    public String getLabel();
  
    /**
     * @return the URL associated with this HTTP request
     */
    public URL getURL();
  
    /**
     * Associate a parameter with this request.
     *
     * @param name  the lvalue of the parameter
     * @param name  the rvalue of the parameter
     *
     * @throws java.lang.IllegalArgumentException  if a parameter is null or not a 
String
     */
    public void setParameter(String name, String value);
  
    /**
     * Associate a group of parameters with this request.
     *
     * @param parameters  a map of parameters (lvalues -> rvalues)
     *
     * @throws java.lang.IllegalArgumentException  if a parameter is null or not a 
String
     */
    public void setParameters(Map parameters);
  
    /**
     * Retrieve the session associated with this request.
     *
     * @return a <code>Session</code> object
     */
    public Session getSession();
  
    /**
     * The amount of time it took to execute the
     * request in milliseconds, or -1 if the request has not
     * been executed successfully
     *
     * @return time it took to execute the request in millis
     */
    public int getRequestTiming();
  }
  
  
  
  1.1                  
jakarta-commons-sandbox/latka/src/java/org/apache/commons/latka/http/RequestImpl.java
  
  Index: RequestImpl.java
  ===================================================================
  package org.apache.commons.latka.http;
  
  
  import java.net.URL;
  import java.io.IOException;
  import java.util.Map;
  import java.util.Date;
  import java.util.Iterator;
  
  import org.apache.commons.httpclient.State;
  import org.apache.commons.httpclient.HttpMethod;
  import org.apache.commons.httpclient.methods.GetMethod;
  import org.apache.commons.httpclient.methods.PostMethod;
  
  import org.apache.log4j.Category;
  
  /**
   * An implementation of a Latka Request interface based on the Jakarta Commons 
HttpClient package.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]";>Doug Sale</a>
   * @author <a href="mailto:[EMAIL PROTECTED]";>Morgan Delagrange</a>
   */
  public class RequestImpl implements Request {
  
    protected SessionImpl _session    = null;
    protected HttpMethod  _httpMethod = null;
    protected URL         _targetURL  = null;
    protected long        _requestTiming = -1;
    protected String      _label      = null;
  
    protected static final Category cat = Category.getInstance(RequestImpl.class);
  
    RequestImpl(URL url, int httpMethod, SessionImpl session) {
      this(null,url,httpMethod,session,true);
    }
  
    /**
     * Create a RequestImpl
     *
     * @param url         the url that this request embodies
     * @param httpMethod  the method by which this request should be executed
     * @param session     the session that the request should be executed in
     */
    RequestImpl(String label, URL url, int httpMethod, SessionImpl session, boolean 
followRedirects) {
      _label = label;
      String query = url.getQuery();
  
      _session = session;
      _targetURL = url;
  
      switch (httpMethod) {
        case HTTP_METHOD_GET:
          _httpMethod = new GetMethod(url.getPath());
          ((GetMethod) _httpMethod).setUseDisk(false);
          break;
        case HTTP_METHOD_POST:
          _httpMethod = new PostMethod(url.getPath());
          ((PostMethod) _httpMethod).setUseDisk(false);
          break;
        default:
          throw new IllegalArgumentException("Unsupported HTTP Method");
      }
  
  
      if (query != null) {
        _httpMethod.setQueryString(query);
      }
      _httpMethod.setFollowRedirects(followRedirects);
    }
  
    /**
     * @return the underlying HttpMethod object representing the request/respose pair.
     */
    HttpMethod getHttpMethod() {
      return _httpMethod;
    }
  
  
    ///////////////////////////////
    // Request Interface Methods //
    ///////////////////////////////
  
  
    /**
     * Execute this HTTP request.
     *
     * @return a Response object represnting the HTTP response to the request
     *
     * @throws java.io.IOException ...
     */
    public Response execute() throws IOException {
      // for timing
      Date startDate = new Date();
  
      Response response = _session.execute(this);
      _requestTiming = ((new java.util.Date()).getTime() - startDate.getTime());
      cat.info("request executed");
      cat.debug("response obtained:");
      cat.debug(response.getResource());
      return response;
    }
  
    /**
     * @return the URL associated with this HTTP request
     */
    public URL getURL() {
      return _targetURL;
    }
  
    public String getLabel() {
      return _label;
    }
  
    /**
     * Associate a parameter with this request.
     *
     * @param name  the lvalue of the parameter
     * @param name  the rvalue of the parameter
     *
     * @throws java.lang.IllegalArgumentException  if a parameter is null
     */
    public void setParameter(String name, String value) {
  
      cat.info("adding parameter, name:");
      cat.info(name);
      cat.info("value:");
      cat.info(value);
  
      try {
        if (_httpMethod instanceof PostMethod) {
          // addParameter adds to POST Entity, not URL
          ((PostMethod) _httpMethod).addParameter(name, value);
        } else {
          // setParameter adds to URL as query string
          _httpMethod.setParameter(name, value);
        }
      } catch (NullPointerException nullX) {
        throw new IllegalArgumentException(nullX.toString());
      }
    }
  
    /**
     * Associate a group of parameters with this request.
     *
     * @param parameters  a map of parameters (lvalues -> rvalues)
     *
     * @throws java.lang.IllegalArgumentException  if a parameter is null or not a 
String
     */
    public void setParameters(Map parameters) {
      String name, value;
      Iterator iter = parameters.keySet().iterator();
  
      while (iter.hasNext()) {
        try {
          name = (String) iter.next();
          value = (String) parameters.get(name);
  
          if (_httpMethod instanceof PostMethod) {
            // addParameter adds to POST Entity, not URL
            ((PostMethod) _httpMethod).addParameter(name, value);
          } else {
            // setParameter adds to URL as query string
            _httpMethod.setParameter(name, value);
          }
        } catch (ClassCastException classX) {
          throw new IllegalArgumentException(classX.toString());
        } catch (NullPointerException nullX) {
          throw new IllegalArgumentException(nullX.toString());
        }
      }
    }
  
    /**
     * protected for now.  Currently used only for setting the
     * referer in session requests
     * 
     * @param headerName name of any HTTP request header
     * @param headerValue value of that header
     */
    protected void setHeader(String headerName, String headerValue) {
      _httpMethod.setHeader(headerName,headerValue);
    }
  
    /**
     * Retrieve the session associated with this request.
     *
     * @return a <code>Session</code> object
     */
    public Session getSession() {
      return _session;
    }
  
    /**
     * @return the amount of time it took to execute this request (in milliseconds)
     */
    public int getRequestTiming() {
      return(int) _requestTiming;
    }
  
  }
  
  
  
  1.1                  
jakarta-commons-sandbox/latka/src/java/org/apache/commons/latka/http/Response.java
  
  Index: Response.java
  ===================================================================
  package org.apache.commons.latka.http;
  
  
  /**
   * A Latka Response represents a response from an HTTP server.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]";>Doug Sale</a>
   * @author <a href="mailto:[EMAIL PROTECTED]";>Morgan Delagrange</a>
   */
  public interface Response {
  
    /**
     * @return the integer status code provided by the HTTP server.
     */
    public int getStatusCode();
  
    /**
     * @return the resource, in string form, provided by the HTTP server.
     */
    public String getResource();
  
    /**
     * @return the length (in bytes) of the resource provided by the HTTP server.
     */
    public int getByteLength();
  
    /**
     * The request that generated this response
     */
    public Request getRequest();
  }
  
  
  
  1.1                  
jakarta-commons-sandbox/latka/src/java/org/apache/commons/latka/http/ResponseImpl.java
  
  Index: ResponseImpl.java
  ===================================================================
  package org.apache.commons.latka.http;
  
  
  import java.io.IOException;
  
  import org.apache.commons.httpclient.HttpMethod;
  import org.apache.commons.httpclient.methods.GetMethod;
  import org.apache.commons.httpclient.methods.PostMethod;
  
  
  /**
   * An implementation of a Latka Response interface based on the Jakarta Commons 
HttpClient package.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]";>Doug Sale</a>
   * @author <a href="mailto:[EMAIL PROTECTED]";>Morgan Delagrange</a>
   */
  public class ResponseImpl implements Response {
  
    protected RequestImpl _request;
    protected HttpMethod  _httpMethod;
  
    /**
     * Create a Response
     *
     * @param request  the request that motivated this response
     * @param session  the session in which this response was received
     */
    ResponseImpl(RequestImpl request) {
      _request = request;
      _httpMethod = request.getHttpMethod();
    }
  
    public Request getRequest() {
      return _request;
    }
  
    ////////////////////////////////
    // Response Interface Methods //
    ////////////////////////////////
  
  
    /**
     * @return the integer status code provided by the HTTP server.
     */
    public int getStatusCode() {
      return _httpMethod.getStatusCode();
    }
  
    /**
     * @return the resource, in string format, provided by the HTTP server (or null if 
not possible).
     */
    public String getResource() {
      String resource;
  
      // is there a reason that these are separate cases?
      // does PostMethod override GetMethod's getDataAsString()?
  
      if (_httpMethod instanceof GetMethod) {
        try {
          resource = ((GetMethod) _httpMethod).getDataAsString();
        }
        catch (IOException ioX) {
          resource = null;
        }
      }
      else if (_httpMethod instanceof PostMethod) {
        try {
          resource = ((PostMethod) _httpMethod).getDataAsString();
        }
        catch (IOException ioX) {
          resource = null;
        }
      }
      else {
        resource = null;
      }
  
      return resource;
    }
  
    /**
     * Returns the length of the Response stream (as bytes),
     * or -1 if no stream is available
     * 
     * @return Byte length of the response stream
     */
    public int getByteLength() {
      // note: PostMethod is derived from GetMethod
      if (_httpMethod instanceof GetMethod) {
        try {
          // keep an eye on this.  it may not be adequate
          // if httpclient stops using bytearrayinputstream
          return ((GetMethod) _httpMethod).getData().available();
        }
        catch (IOException ioX) {
          return -1;
        }
      }
      else {
        return -1;
      }
    }
  }
  
  
  
  1.1                  
jakarta-commons-sandbox/latka/src/java/org/apache/commons/latka/http/Session.java
  
  Index: Session.java
  ===================================================================
  package org.apache.commons.latka.http;
  
  
  import java.net.URL;
  
  
  /**
   * A Latka Session is a container that manages state information
   * over 1+ HTTP request/response pairs over 1+ HTTP servers.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]";>Doug Sale</a>
   * @author <a href="mailto:[EMAIL PROTECTED]";>Morgan Delagrange</a>
   */
  public interface Session {
  
    /**
     * Creates a request object with the specified URL and HTTP Method.
     *
     * @param url         The URL to request of the HTTP server.
     * @param httpMethod  An integer representing the HTTP method (e.g. GET, PUT) used 
to communicate with server.
     * {@link} org.apache.commons.latka.http.Request.HTTP_METHOD_GET
     * {@link} org.apache.commons.latka.http.Request.HTTP_METHOD_POST
     *
     * @return a new <code>Request</code> object representing the <code>url</code> and 
<code>httpMethod</code>
     */
    public Request createRequest(URL url, int httpMethod);
    public Request createRequest(String label, URL url, int httpMethod,boolean 
followRedirects);
  
    /**
     * Adds a cookie to all HTTP requests whose domain and path match (according to 
RFC2109).
     *
     * @param domain  the domain to which the cookie should apply
     * @param path    the path to which the cookie should apply
     * @param name    the name of the cookie
     * @param value   the value of the cookie
     */
    public void addCookie(String domain, String path,
                          String name, String value);
  
    /**
     * Returns the value of cookie <code>name</code>.
     *
     * @param name  the name of the cookie
     *
     * @return the value of the cookie, or null if the cookie isn't set
     */
    public String getCookieValue(String name);
  }
  
  
  
  1.1                  
jakarta-commons-sandbox/latka/src/java/org/apache/commons/latka/http/SessionImpl.java
  
  Index: SessionImpl.java
  ===================================================================
  package org.apache.commons.latka.http;
  
  import java.net.URL;
  import java.io.IOException;
  import java.util.LinkedList;
  import java.util.Vector;
  import java.util.Enumeration;
  
  import org.apache.commons.httpclient.State;
  import org.apache.commons.httpclient.Cookie;
  import org.apache.commons.httpclient.HttpClient;
  import org.apache.commons.httpclient.HttpMethod;
  import org.apache.commons.httpclient.HttpException;
  import org.apache.commons.httpclient.methods.GetMethod;
  import org.apache.commons.httpclient.methods.PostMethod;
  
  
  /**
   * An implementation of a Latka Session interface based on the Jakarta Commons 
HttpClient package.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]";>Doug Sale</a>
   * @author <a href="mailto:[EMAIL PROTECTED]";>Morgan Delagrange</a>
   */
  public class SessionImpl implements Session {
  
    /** Standard HTTP Port */
    public static final int HTTP_PORT = 80;
  
    /** Standard HTTPS Port */
    public static final int HTTPS_PORT = 443;
  
    // the central class of the HTTP client library
    protected HttpClient _httpClient;
  
    /** 
     * tracks URLs treated by this session
     * Session will automatically set the referer
     * header for a request to the URL of the
     * previous request
     */
    protected LinkedList _urls = new LinkedList();
  
  
    // this state object 'belongs' to HttpClient
    // we maintain a reference in SessionImpl for
    // simplicity
    protected State      _state;
  
    protected String  _host;
    protected int     _port;
    protected boolean _sessionExists = false;
           
    /**
     *
     */
    public SessionImpl() {
      _httpClient = new HttpClient();
      _state = new State();
    }
  
    /**
     * Executes a RequestImpl, returning a Response
     *
     * @param request  a <code>Request</code> object, representing an HTTP request to 
a server
     *
     * @return returns a <code>Response</code> object, representing an HTTP response 
from a server
     *
     * @throws java.io.IOException ...
     */
    Response execute(RequestImpl request) throws IOException {
      Response   response = null;
      HttpMethod httpMethod = request.getHttpMethod();
  
      try {
        _httpClient.executeMethod(httpMethod);
        response = new ResponseImpl(request);
      }
      catch (HttpException httpX) {
        throw new IOException(httpX.toString());
      }
  
      return response;
    }
  
  
    ///////////////////////////////
    // Session Interface Methods //
    ///////////////////////////////
  
  
    /**
     * Creates a request object with the specified URL and HTTP Method.
     *
     * @param url         The URL to request of the HTTP server.
     * @param httpMethod  An integer representing the HTTP method (e.g. GET, PUT) used 
to communicate with server.
     * {@link} org.apache.commons.latka.http.Request.HTTP_METHOD_GET
     * {@link} org.apache.commons.latka.http.Request.HTTP_METHOD_POST
     *
     * @return a new <code>Request</code> object representing the <code>url</code> and 
<code>httpMethod</code>
     */
    public Request createRequest(URL url, int httpMethod) {
       return createRequest(null,url,httpMethod,true);
    }
  
    public Request createRequest(String label, URL url, int httpMethod, boolean 
followRedirects) {
  
      String protocol = url.getProtocol();
      String host = url.getHost();
      int port = url.getPort();
  
      // explicitly set port if not in url,
      // just for storing away and comparison
      if (port == -1) {
        if (protocol.equals("http")) {
          port = HTTP_PORT;
        }
        else if (protocol.equals("https")) {
          port = HTTPS_PORT;
        }
        else {
          throw new IllegalArgumentException("Unsupported Protocol");
        }
      }
  
      if (_sessionExists) {
  
        // if a session exists and this request's host or port
        // varies from an earlier session, start new HttpClient
        // session, but maintain state
        if ( !host.equals(_host) || port != _port ) {
  
          try {
            _sessionExists = false;
            _httpClient.endSession();
          }
          catch (IOException ioX) {
            // if and exception occurs, no matter
            // create new HttpClient
            _httpClient = new HttpClient();
          }
  
          // save session values
          _host = host;
          _port = port;
  
          // start session, maintain state
          _httpClient.startSession(url);
          _httpClient.setState(_state);
          _sessionExists = true;
        }
        // else maintain current session
      }
      else {
        // save session values
        _host = host;
        _port = port;
  
        // start session
        _httpClient.startSession(url);
        _httpClient.setState(_state);
        _sessionExists = true;
      }
  
      RequestImpl request = 
        new RequestImpl(label,url, httpMethod, this,  followRedirects);
  
      if (_urls.size() > 0) {
        request.setHeader("Referer", ((URL)_urls.getLast()).toString());
      }
  
      _urls.add(url);
  
      return request;
    }
  
    /**
     * Adds a cookie to all HTTP requests whose domain and path match (according to 
RFC2109).
     *
     * @param domain  the domain to which the cookie should apply
     * @param path    the path to which the cookie should apply
     * @param name    the name of the cookie
     * @param value   the value of the cookie
     */
    public void addCookie(String domain, String path,
                          String name, String value) {
  
      Cookie cookie = new Cookie(domain, name, value);
      cookie.setPath(path);
  
      _state.addCookie(cookie);
    }
  
    /**
     * Returns the value of cookie <code>name</code>.
     *
     * @param name  the name of the cookie
     *
     * @return the value of the cookie, or null if the cookie isn't set
     */
    public String getCookieValue(String name) {
      String  value = null;
      boolean done  = false;
  
      Vector cookies = _state.getCookies();
  
      if (cookies != null) {
  
        Enumeration enum = cookies.elements();
  
        while (enum.hasMoreElements() && !done) {
          Cookie cookie = (Cookie) enum.nextElement();
  
          if (cookie.getName().equals(name)) {
            value = cookie.getValue();
            done = true;
          }
        }
      }
  
      return value;
    }
  
  }
  
  
  

Reply via email to