Login | Register
My pages Projects Community openCollabNet

Discussions > cvs > CVS update: MODIFIED: publish ...

Project highlights: Architectural Overview

joist
Discussion topic

Back to topic list

CVS update: MODIFIED: publish ...

Author stack
Full name Michael Stack
Date 2001-06-18 18:57:09 PDT
Message User: stack
  Date: 01/06/18 18:57:09

  Modified: java/org/joist/publish ProxyModule.java
  Log:
  Clean up.
  
  Revision Changes Path
  1.13 +345 -218 joist/java/org/joist​/publish/ProxyModule​.java
  
  http://joist.tigris.​org/source/browse/jo​ist/java/org/joist/p​ublish/ProxyModule.j​ava.diff?r1=1.12​&r2=1.13
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: ProxyModule.java
  ====================​====================​====================​=======
  RCS file: /usr/local/tigris/da​ta/helm/cvs/reposito​ry/joist/java/org/jo​ist/publish/ProxyMod​ule.java,v
  retrieving revision 1.12
  retrieving revision 1.13
  diff -u -b -r1.12 -r1.13
  --- ProxyModule.java 2001/06/18 18:22:23 1.12
  +++ ProxyModule.java 2001/06/19 01:57:09 1.13
  @@ -1,5 +1,3 @@
  -package org.joist.publish;
  -
   /* ====================​====================​====================​====
    * Copyright (c) 2000 Collab.Net. All rights reserved.
    *
  @@ -45,243 +43,188 @@
    * This software consists of voluntary contributions made by many
    * individuals on behalf of Collab.Net.
    */
  +package org.joist.publish;
   
  -// don't import .* because we are replacing
  -// HttpURLConnection
  +// Don't import .* because we are replacing HttpURLConnection.
  +//
   import java.net.URL;
   import java.net.MalformedURLException;
   
  -// replacement for HttpURLConnection
  +// Replacement for HttpURLConnection.
  +//
   import HTTPClient.*;
   
   import java.io.*;
   import java.util.*;
   
   // Java Servlet Classes
  +//
   import javax.servlet.*;
   import javax.servlet.http.*;
   
   import org.apache.turbine.util.Log;
   
  -/**
  - This is the core class for Noodle that does most of the work
  - of actually being a proxy.
       
  - @author <a href="mailto:jon@col​lab.net">Jon S. Stevens</a>
  -*/
  +/**
  + * Proxy a request for Noodle.
  + *
  + * This is the core class for Noodle; it does the actual proxying of
  + * the request.
  + *
  + * TODO: This class looks like it needs to be rewritten so it can be
  + * instantiated. All methods are unsynchronized statics. Check.
  + * TODO: Read the SERVER_NAME, SERVER_PORT and SCHEME from token.
  + *
  + * @author <a href="mailto:jon@col​lab.net">Jon S. Stevens</a>
  + * @author <a href="mailto:stack@c​ollab.net">St.Ack​</a>
  + * @version $Id: ProxyModule.java,v 1.13 2001/06/19 01:57:09 stack Exp $
  + */
   public class ProxyModule
   {
  - /** debug flag.
  + /**
  + * Debug flag. Set to 'true' to see debug logging.
       */
       private static final boolean DEBUG = false;
   
  -
  - /** default server to connect to */
  + /**
  + * Default server to connect to.
  + */
       private static String SERVER_NAME = "localhost";
  - /** default port to connect to */
  +
  + /**
  + * Default port to connect to.
  + */
       private static int SERVER_PORT = 80;
  - /** default scheme. you can't change it right now. */
  +
  + /**
  + * Default scheme. You can't change it right now.
  + */
       private static final String SCHEME = "http";
  - /** used when no content type is set on the proxy return */
  +
  + /**
  + * Used when no content type is set on the proxy return.
  + */
       private static final String DEFAULT_CONTENT_TYPE = "text/html";
   
  - /** Key to pull what Noodle is to proxy from the query string.
  - * Public rather than private so could be used by
  - * other classes (its read-only anyways).
  + /**
  + * Key to pull what Noodle is to proxy from the query string.
  + *
  + * Public rather than private so it can be used by other classes.
         */
       public static final String PAGE_VAR = "page";
   
  + /**
  + * Define for the string 'POST'.
  + */
       public static final String POST = "POST";
  - public static final String GET = "GET";
  - public static final String PUT = "PUT";
  - public static final String HEAD = "HEAD";
       
  -
       /**
  - Allows one to override the default server name which is "localhost".
  + * Define for the string 'GET'.
       */
  - public static void setServerName(String name)
  - {
  - SERVER_NAME = name;
  - }
  + public static final String GET = "GET";
   
       /**
  - Allows one to override the default server port which is 80.
  -
  - Changed visibility from 'package' to public so i can use
  - this methods outside of org.joist.publish. In particular,
  - org.tigris.helm.Noodle. St.Ack 10/26/2000.
  + * Define for the string 'PUT'.
       */
  - public static void setServerPort(int port)
  - {
  - SERVER_PORT = port;
  - }
  + public static final String PUT = "PUT";
   
       /**
  - returns a URL used for making the connection to the remote location
  - page must be a URLEncoded string.
  + * Define for the string 'HEAD'.
       */
  - public static URL getURL(String page)
  - throws MalformedURLException
  - {
  - if (page == null)
  - throw new MalformedURLException("Noodle: page variable could not be found");
  + public static final String HEAD = "HEAD";
   
  - URL url = new URL(SCHEME, SERVER_NAME, SERVER_PORT, page);
  - return url;
  - }
       
  +
       /**
  - This is the meat of everything. It does the proxy of the request including
  - applying the pre/post filters when necessary.
  + * Proxy a request.
  + *
  + * This is the meat of everything. It does the proxy of the request
  + * including applying the pre/post filters when necessary.
  + *
  + * @param noodleData Noodle Data. Has what we need to make the request
  + * and its in here that we put the the request results.
  + *
  + * @exception Exception
  + *
  + * @see #proxyRequest( NoodleData, String )
       */
  - public static final void proxyRequest(NoodleData noodleData)
  + public static final void proxyRequest( NoodleData noodleData )
           throws Exception
       {
           proxyRequest( noodleData, null );
       }
   
       /**
  - * This is the meat of everything. It does the proxy of the request including
  - * applying the pre/post filters when necessary.
  + * Proxy a request.
       *
  - * @param noodleData Noodle Data
  - * @param inSavedOffQuery req.getQueryString can return a null
  - * query string in circumstance where not logged in to Helm.
  - * If the caller has squirreled away the original query, pass it
  - * here. May be null.
  + * This is the meat of everything. It does the proxy of the request
  + * including applying the pre/post filters when necessary.
       *
  + * @param noodleData Noodle Data. Has what we need to make the request
  + * and its in here that we put the the request results.
  + * @param inSavedOffQuery req.getQueryString can return a null query
  + * string in circumstance where not logged in to Helm. If the
  + * caller has squirreled away the original query, pass it here.
  + * May be null.
  + *
       * @exception Exception
       */
  - public static final void proxyRequest(NoodleData noodleData,
  - String inSavedOffQuery)
  + public static final void proxyRequest( NoodleData noodleData,
  + String inSavedOffQuery )
           throws Exception
  - {
  - // setup some shortcuts
  - HttpServletRequest req = noodleData.getRequest();
  - HttpServletResponse res = noodleData.getResponse();
  -
  - boolean methodGet = req.getMethod().equa​lsIgnoreCase(GET);
  - boolean methodPost = req.getMethod().equa​lsIgnoreCase(POST);
  - boolean methodHEAD = req.getMethod().equa​lsIgnoreCase(HEAD);
  - boolean methodPUT = req.getMethod().equa​lsIgnoreCase(PUT);
  -
  - // deal with QUERYSTRING data.
  - //
  - // Note, req.getQueryString( ) can return
  - // null in case where we've been bounced
  - // off to TLogin because we weren't logged in...
  - // and then TLogin comes back to Noodle. Put
  - // in check for null and alternate query
  - // string source, if one. St.Ack 10/27/2000
  - //
  - String page = null;
  - String query = req.getQueryString();
  - if( query == null )
  - {
  - query = inSavedOffQuery;
  - if( query == null )
               {
  - throw new NullPointerException(
  - "query [req.getQueryString( )] is null" );
  - }
  - }
  + HttpServletRequest req = noodleData.getRequest( );
  + HttpServletResponse res = noodleData.getResponse( );
   
  - if( DEBUG )
  - Log.debug( "QUERY: " + query );
  + String query = getQueryString( req, inSavedOffQuery );
  + String queryMinusPAGE_VAR = stripQueryString( query, PAGE_VAR );
  + noodleData.setQueryData( queryMinusPAGE_VAR );
  +
  + String page
  + = noodleData.postProcessPageName( getPageToProxy( req, query ) );
  + URL url = getURL( page );
  + noodleData.setURL( url );
                   
  - try
  - {
  - page = req.getParameter(PAGE_VAR);
  - }
  - catch (Exception e)
  - {
  - page = getPageFromQueryStr( query );
  - }
  - if (page == null)
  + // Make up a URI that is the page to get plus the query string
  + // stripped of PAGE_VAR item.
  + //
  + StringBuffer proxyURI = new StringBuffer( url.getFile( ) );
  + if( queryMinusPAGE_VAR.length( ) > 0 )
           {
  - page = getPageFromQueryStr( query );
  + proxyURI.append("?");
  + proxyURI.append( queryMinusPAGE_VAR );
           }
   
  - page = noodleData.postProce​ssPageName(page);
  -
  - // build up the request URL
  - noodleData.setURL( getURL(page) );
  -
  - // strip out the page= variable from the query data
  - if (query.length()>0)
  - query = stripPage(query).trim();
  - // set the QueryData
  - noodleData.setQueryData(query);
  -
  - // EXECUTE PRE FILTERS!
  + // EXECUTE PRE-FILTERS
  + //
           NoodleFilterLoader.g​etInstance().doExecu​tePreFilters(noodleD​ata);
   
  - // execute a connection to the remote machine
  - // we currently only handle GET/POST data
  - HTTPConnection conn = null;
  -
  - // append the query string to the request
  - StringBuffer sb = new StringBuffer();
  - sb.append (noodleData.getURL()​.getFile());
  - if (noodleData.getQuery​Data().length()>0​)
  - {
  - sb.append("?");
  - sb.append(noodleData​.getQueryData());
  - }
  -
  - conn = new HTTPConnection(noodl​eData.getURL());
  - HTTPResponse httpResponse = null;
  -
  - if (methodGet)
  - {
  - httpResponse = conn.Get(sb.toString(), new String(),
  - noodleData.getHeader​sToSendAsNVPair());
  - }
  - else if (methodPost)
  - {
  - httpResponse = conn.Post(sb.toString(), noodleData.getPostData(),
  - noodleData.getHeader​sToSendAsNVPair());
  - }
  - else if( methodHEAD )
  - {
  - httpResponse = conn.Head(sb.toString(), new String(),
  - noodleData.getHeader​sToSendAsNVPair());
  - }
  - else if( methodPUT )
  - {
  - httpResponse = conn.Put(sb.toString(), new String(),
  - noodleData.getHeader​sToSendAsNVPair());
  - }
  - else
  - {
  - throw new java.net.ProtocolException( "UNSUPPORTED HTTP method: "
  - + req.getMethod( ) );
  - }
  -
  + // Proxy.
  + //
  + HTTPResponse httpResponse = proxyRequestMethod( req, url,
  + proxyURI.toString( ), noodleData.getHeader​sToSendAsNVPair( ),
  + noodleData.getPostData( ) );
           noodleData.setHTTPResponse( httpResponse );
           
  - // get the content from the response to the connection
           byte[] data = null;
           String ct = null;
           try
           {
               data = readFully(
                   new BufferedInputStream( httpResponse.getInpu​tStream()));
  - // i think the above line is more efficient than what
  + // I think the above line is more efficient than what
               // HTTPClient.Response is trying to do....ie:
               // data = httpResponse.getData();
   
  - // get the content type
               ct = httpResponse.getHead​er("Content-Type");
  - // case for Content-Type: being missing for some reason
               if (ct == null || ct.length() == 0)
                   ct = DEFAULT_CONTENT_TYPE;
           }
  +
           catch (Exception e)
           {
               Log.error( "Error occurred while accessing content:"
  - + noodleData.getURL( ).toString( ), e );
  + + url.toString( ), e );
               Vector v = noodleData.getHeadersToSend( );
               StringBuffer strbuf = new StringBuffer( );
               for( int i = 0; i < v.size( ); i++ )
  @@ -291,46 +234,175 @@
                   strbuf.append( ( ( NVPair )v.get( i ) ).getValue( ) );
                   strbuf.append( "===" );
               }
  - Log.error( "REQUEST HEADERS: " + strbuf.toString( ) );
  + Log.error( "Request Headers: " + strbuf.toString( ) );
               data = "Error occurred while accessing content.".getBytes();
               ct = DEFAULT_CONTENT_TYPE;
           }
   
  - // set the response data into the noodleData for filter processing
  - noodleData.setRespon​seData(data);
  -
  - // set the content type for the Servlet response
  + // Set the content type for the Servlet response.
  + //
           res.setContentType(ct);
   
           // EXECUTE POST FILTERS!
  + // Set the response data into the noodleData for filter processing.
  + //
  + noodleData.setRespon​seData(data);
           NoodleFilterLoader.g​etInstance().doExecu​tePostFilters(noodle​Data);
       }
   
  - /** Try to get the page value from the passed in query
  + /**
  + * Do the actual proxy w/ appropriate method (GET, POST, etc.).
       *
  - * @param inQueryStr Query string we're to pull PAGE_VAR
  - * value from.
  + * @param inRequest The servlet request object.
  + * @param inURL Basic url w/ host and port information. Used to
  + * set up the HTTPClient connection.
  + * @param inProxyURI File we're to request along w/ whats left of
  + * query string after stripping page to request (If any).
  + * @param inHeaders2Send HTTP headers to send on the proxy request.
  + * @param inPostData Data to use w/ POST requests, if thats what
  + * we're doing here.
  + *
  + * @return A HTTPClient HTTPResponse object.
  + *
  + * @exception IOException
  + * @exception ModuleException
  + * @exception java.net.ProtocolException If we get a method request
  + * that we do not support.
  + *
  + */
  + private static HTTPResponse proxyRequestMethod(
  + HttpServletRequest inRequest, URL inURL, String inProxyURI,
  + NVPair[] inHeaders2Send, byte[] inPostData )
  + throws java.net.ProtocolException, IOException, ModuleException
  + {
  + HTTPResponse httpResponse = null;
  + String emptyStr = new String( );
  +
  + HTTPConnection conn = new HTTPConnection( inURL );
  +
  + if( inRequest.getMethod( ).equalsIgnoreCase( GET ) )
  + {
  + httpResponse = conn.Get( inProxyURI, emptyStr, inHeaders2Send );
  + }
  + else if( inRequest.getMethod( ).equalsIgnoreCase( POST ) )
  + {
  + httpResponse = conn.Post( inProxyURI, inPostData, inHeaders2Send );
  + }
  + else if( inRequest.getMethod( ).equalsIgnoreCase( HEAD ) )
  + {
  + httpResponse = conn.Head( inProxyURI, emptyStr, inHeaders2Send );
  + }
  + else if( inRequest.getMethod( ).equalsIgnoreCase( PUT ) )
  + {
  + httpResponse = conn.Put( inProxyURI, emptyStr, inHeaders2Send );
  + }
  + else
  + {
  + throw new java.net.ProtocolException( "UNSUPPORTED HTTP method: "
  + + inRequest.getMethod( ) );
  + }
  +
  + return httpResponse;
  + }
  +
  + /**
  + * Get the query string.
  + *
  + * inRequest.getQueryString( ) can return null. Put in check for null and
  + * use alternate query string source, if one supplied.
       *
  - * @exception NullPointerException If we can't find
  - * PAGE_VAR value in passed string.
  + * @param inRequest Our incoming request.
  + * @parm inSavedOffQuery Last chance query string. May be null.
  + *
  + * @return The query string.
  + *
  + * @exception NullPointerException Throw NPE if we can't get query string.
       */
  - private static String getPageFromQueryStr( String inQueryStr )
  + private static String getQueryString( HttpServletRequest inRequest,
  + String inSavedOffQuery )
  + throws NullPointerException
  + {
  + String query = inRequest.getQueryString();
  +
  + if( query == null )
       {
  + query = inSavedOffQuery;
  + if( query == null )
  + {
  + throw new NullPointerException(
  + "query [req.getQueryString( )] is null" );
  + }
  + }
  +
  + if( DEBUG )
  + {
  + Log.debug( "QUERY: " + query );
  + }
  +
  + return query.trim( );
  + }
  +
  + /**
  + * Get page we're to proxy.
  + *
  + * Pull from the HttpServletRequest or from query string.
  + *
  + * @param inRequest The servlet request object.
  + * @parm inQueryString Request query string.
  + *
  + * @return Page we're to proxy.
  + *
  + * @exception NullPointerException If we can't get a page to proxy.
  + *
  + */
  + private static String getPageToProxy( HttpServletRequest inRequest,
  + String inQueryString )
  + throws NullPointerException
  + {
  + String page = null;
  +
  + try
  + {
  + page = inRequest.getParamet​er(PAGE_VAR);
  + }
  +
  + finally
  + {
  + if( page == null )
  + {
  + page = getValueFromQueryString( PAGE_VAR, inQueryString );
  + }
  + }
  +
  + return page;
  + }
  +
  + /**
  + * Get value from the passed in query string.
  + *
  + * @param inKey Key we use pulling value from inQueryStr.
  + * @param inQueryStr Query string to pull value on the end of inKey from.
  + *
  + * @exception NullPointerException If we can't find inKey value in passed
  + * string.
  + */
  + private static String getValueFromQueryString( String inKey,
  + String inQueryStr )
  + throws NullPointerException
  + {
           String strReturn = null; // PAGE_VAR argument to return
           int indexStart = -1;
           int indexEnd = -1;
           
           if( inQueryStr == null )
               throw new NullPointerException( "inQueryStr is null" );
  - indexStart = inQueryStr.indexOf( PAGE_VAR );
  + indexStart = inQueryStr.indexOf( inKey );
           if( indexStart < 0 ) // A bit of misuse of NullPointerException
  - throw new NullPointerException( "No PAGE_VAR in inQueryStr" );
  - indexStart += PAGE_VAR.length( ); // Put index past PAGE_VAR
  + throw new NullPointerException( inKey + " not in inQueryStr" );
  + indexStart += inKey.length( ); // Put index past inKey
       indexStart += 1; // Put index past the '='
  -
  - // End of PAGE_VAR is at end of string or at first
  - // first occurance past current index of a '&'
  - // -- the query args seperator.
  + // End of inKey is at end of string or at first first occurance past
  + // current index of a '&' -- the query args seperator.
           //
           indexEnd = inQueryStr.indexOf( indexStart, '&' );
           if( indexEnd > 0 )
  @@ -341,39 +413,54 @@
           return strReturn;
       }
   
  -
       /**
  - this method strips the "page" variable from
  - the querystring.
  + * Strip key and its value from the querystring.
  + *
  + * @param inQueryString Query string.
  + *
  + * @return New query string absent 'page=VALUE'.
       */
  - public static final String stripPage(String page)
  + public static final String stripQueryString(
  + String inQueryString, String inKey )
       {
  - StringBuffer sb = new StringBuffer();
  - sb.append (page);
  - int start = page.indexOf ("page=");
  - int end = page.indexOf("&", start);
  - if (end == -1)
  - end = page.length();
  -
  - if (start > 0)
  + StringBuffer sb = new StringBuffer( inQueryString );
  + int start = inQueryString.indexOf( inKey + "=" );
  + int end = inQueryString.indexOf( "&", start );
  + if( end == -1 )
  + end = inQueryString.length();
  + if( start > 0 )
               start = start - 1;
  - else if (start == 0 && ((end + 1) < page.length()))
  + else if( start == 0 && ( ( end + 1 ) < inQueryString.length( ) ) )
               end = end + 1;
  -
  - return page.substring(0,start) +
  - page.substring(end,p​age.length());
  + return inQueryString.substring( 0, start ) +
  + inQueryString.substring( end, inQueryString.length( ) );
       }
   
       /**
  - not used yet, but here for future reference
  + * Parse the protocol.
  + *
  + * Not used yet, but here for future reference
  + *
  + * @param value Protocol to parse.
  + *
  + * @return
  + *
       */
       private static String parseProtocol(String value)
       {
           return value.substring(0,va​lue.indexOf("/"));
       }
  +
       /**
  - reads all the data from a stream even if you don't know the
  - total length of the stream. reads 4096 bytes at a time
  + * Read all data from stream even if total length is unknown.
  + *
  + * Reads 4096 bytes at a time.
  + *
  + * @param is Stream to read from.
  + *
  + * @return Byte array of all read from stream.
  + *
  + * @exception IOException
       */
       public static byte[] readFully ( InputStream is )
           throws IOException
  @@ -387,5 +474,45 @@
           }
           baos.close();
           return baos.toByteArray();
  + }
  +
  + /**
  + * Override the default server name ("localhost").
  + *
  + * @param name Server name
  + */
  + public static void setServerName(String name)
  + {
  + SERVER_NAME = name;
  + }
  +
  + /**
  + * Override the default server port (80).
  + *
  + * @param port Port to use.
  + */
  + public static void setServerPort(int port)
  + {
  + SERVER_PORT = port;
  + }
  +
  + /**
  + * URL for making the connection to the remote location.
  + *
  + * @param page The page param must be an URLEncoded string.
  + *
  + * @return Returns page as an url.
  + *
  + * @exception MalformedURLException
  + */
  + public static URL getURL(String page)
  + throws MalformedURLException
  + {
  + if (page == null)
  + {
  + throw new MalformedURLException( "Noodle page variable not found");
  + }
  +
  + return new URL(SCHEME, SERVER_NAME, SERVER_PORT, page);
       }
   }
  
  
  

--------------------​--------------------​--------------------​---------
To unsubscribe, e-mail: cvs-unsubscribe@jois​t.tigris.org
For additional commands, e-mail: cvs-help at joist dot tigris dot org

« Previous message in topic | 1 of 1 | Next message in topic »

Messages

Show all messages in topic

CVS update: MODIFIED: publish ... stack Michael Stack 2001-06-18 18:57:09 PDT
Messages per page: