You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@avalon.apache.org by do...@apache.org on 2001/02/22 08:51:55 UTC

cvs commit: jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/simpleserver DummyClass.java SimpleServer.java SimpleServer.xinfo SimpleService.java

donaldp     01/02/21 23:51:55

  Added:       src/java/org/apache/cornerstone/demos/helloworldserver
                        HelloWorldHandler.java HelloWorldServer.java
                        HelloWorldServerImpl.java
                        HelloWorldServerImpl.xinfo
               src/java/org/apache/cornerstone/demos/httpproxy
                        AbstractHttpProxyServer.java
                        DefaultHttpAuditingProxyServer.java
                        DefaultHttpAuditingProxyServer.xinfo
                        DefaultHttpFilteringProxyServer.java
                        DefaultHttpFilteringProxyServer.xinfo
                        HttpAuditingProxyHandler.java
                        HttpAuditingProxyServer.java
                        HttpBlockedDomainException.java
                        HttpFilteringProxyHandler.java
                        HttpFilteringProxyServer.java
                        HttpGetRequestWrapper.java
                        HttpPostRequestWrapper.java HttpProxyHandler.java
                        HttpProxyServer.java
                        HttpRequestValidationException.java
                        HttpRequestWrapper.java
               src/java/org/apache/cornerstone/demos/simpleserver
                        DummyClass.java SimpleServer.java
                        SimpleServer.xinfo SimpleService.java
  Log:
  Committing all the cornerstone demos
  
  Revision  Changes    Path
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/helloworldserver/HelloWorldHandler.java
  
  Index: HelloWorldHandler.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.helloworldserver;
  
  import java.io.IOException;
  import java.io.InterruptedIOException;
  import java.io.PrintWriter;
  import java.net.Socket;
  import java.net.SocketException;
  import org.apache.avalon.AbstractLoggable;
  import org.apache.avalon.Component;
  import org.apache.cornerstone.services.connection.ConnectionHandler;
  
  /**
   * This handles an individual incoming request.  It outputs a greeting as html.
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @author Federico Barbieri <sc...@systemy.it>
   * @version 1.0
   */
  public class HelloWorldHandler
      extends AbstractLoggable
      implements Component, ConnectionHandler
  {
      protected static int        c_counter;
  
      protected String            m_greeting;
  
      protected HelloWorldHandler( final String greeting )
      {
          m_greeting = greeting;
      }
  
      /**
       * Handle a connection.
       * This handler is responsible for processing connections as they occur.
       *
       * @param socket the connection
       * @exception IOException if an error reading from socket occurs
       */
      public void handleConnection( final Socket socket )
          throws IOException
      {
          final String remoteHost = socket.getInetAddress().getHostName();
          final String remoteIP = socket.getInetAddress().getHostAddress();
          final PrintWriter out = new PrintWriter( socket.getOutputStream(), true );
  
          try
          {
              out.println( "<html><body><b>" + m_greeting + "!</b><br> Requests so far = " +
                           ++c_counter + "<br>" );
              out.println( "you are " + remoteHost + " at " + remoteIP + "<br>" );
              out.println( "</body></html>" );
  
              socket.close();
          }
          catch( final SocketException se )
          {
              getLogger().debug( "Socket to " + remoteHost + " closed remotely in HelloWorld", se );
          }
          catch( final InterruptedIOException iioe )
          {
              getLogger().debug( "Socket to " + remoteHost + " timeout in HelloWorld", iioe );
          }
          catch( final IOException ioe )
          {
              getLogger().debug( "Exception in HelloWorld handling socket to " + remoteHost , 
                                 ioe );
          }
          catch( final Exception e )
          {
              getLogger().debug( "Exception in HelloWorld opening socket", e );
          }
          finally
          {
              try { socket.close(); }
              catch( final IOException ioe )
              {
                  getLogger().error( "Exception closing socket ", ioe );
              }
          }
  
          getLogger().info( "Connection from " + remoteHost + " (" + remoteIP + ")" );
      }
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/helloworldserver/HelloWorldServer.java
  
  Index: HelloWorldServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.helloworldserver;
  
  import org.apache.phoenix.Service;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public interface HelloWorldServer
      extends Service
  {
      void setGreeting( String greeting );
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/helloworldserver/HelloWorldServerImpl.java
  
  Index: HelloWorldServerImpl.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.helloworldserver;
  
  import java.net.InetAddress;
  import java.net.ServerSocket;
  import java.net.UnknownHostException;
  import org.apache.avalon.AbstractLoggable;
  import org.apache.avalon.ComponentManager;
  import org.apache.avalon.ComponentManagerException;
  import org.apache.avalon.Composer;
  import org.apache.avalon.Context;
  import org.apache.avalon.Contextualizable;
  import org.apache.avalon.Initializable;
  import org.apache.avalon.configuration.Configurable;
  import org.apache.avalon.configuration.Configuration;
  import org.apache.avalon.configuration.ConfigurationException;
  import org.apache.cornerstone.services.connection.ConnectionHandler;
  import org.apache.cornerstone.services.connection.ConnectionHandlerFactory;
  import org.apache.cornerstone.services.connection.ConnectionManager;
  import org.apache.cornerstone.services.sockets.ServerSocketFactory;
  import org.apache.cornerstone.services.sockets.SocketManager;
  import org.apache.phoenix.Block;
  import org.apache.phoenix.BlockContext;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @author  Federico Barbieri <sc...@pop.systemy.it>
   * @version 1.0
   */
  public class HelloWorldServerImpl 
      extends AbstractLoggable
      implements Block, HelloWorldServer, 
      Contextualizable, Composer, Configurable, Initializable, ConnectionHandlerFactory
  {
      protected SocketManager       m_socketManager;
      protected ConnectionManager   m_connectionManager;
  
      protected BlockContext        m_context;
      protected String              m_greeting          = "Hello World";
      protected InetAddress         m_bindTo;
      protected int                 m_port;
  
      public void setGreeting( final String greeting )
      {
          m_greeting = greeting;
      }
  
      public void contextualize( final Context context )
      {
          m_context = (BlockContext)context;
      }
  
      public void configure( final Configuration configuration )
          throws ConfigurationException
      {
          m_port = configuration.getChild("port").getValueAsInt( 8000 );
  
          try 
          { 
              final String bindAddress = configuration.getChild( "bind" ).getValue();
              m_bindTo = InetAddress.getByName( bindAddress ); 
          }
          catch( final UnknownHostException unhe ) 
          {
              throw new ConfigurationException( "Malformed bind parameter", unhe );
          }
      }
  
      public void compose( final ComponentManager componentManager ) 
          throws ComponentManagerException
      {
          getLogger().info("HelloWorldServer.compose()");
  
          m_socketManager = (SocketManager)componentManager.
              lookup( "org.apache.cornerstone.services.sockets.SocketManager" );
  
          m_connectionManager = (ConnectionManager)componentManager.
              lookup( "org.apache.cornerstone.services.connection.ConnectionManager" );
      }
  
      public void init()
          throws Exception
      {
          final ServerSocketFactory factory =
              m_socketManager.getServerSocketFactory( "plain" );
          final ServerSocket serverSocket = factory.createServerSocket( m_port, 5, m_bindTo );
  
          m_connectionManager.connect( "HelloWorldListener", serverSocket, this );
      }
  
      /**
       * Construct an appropriate ConnectionHandler.
       *
       * @return the new ConnectionHandler
       * @exception Exception if an error occurs
       */
      public ConnectionHandler createConnectionHandler()
          throws Exception
      {
          final HelloWorldHandler handler = new HelloWorldHandler( m_greeting );
          setupLogger( handler );
          return handler;
      }   
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/helloworldserver/HelloWorldServerImpl.xinfo
  
  Index: HelloWorldServerImpl.xinfo
  ===================================================================
  <?xml version="1.0"?>
  
  <blockinfo>
  
    <meta>
      <contributors>
        <author name="Paul Hammant" email="Paul_Hammant@yahoo.com"/>
        <author name="Federico Barbieri" email="scoobie@pop.systemy.it"/>
      </contributors>
    </meta>
  
    <!-- services that are offered by this block -->
    <services>
      <service name="org.apache.cornerstone.demos.helloworldserver.HelloWorldServer" 
               version="1.0" />
    </services>
  
    <dependencies>
      <dependency>
        <role>org.apache.cornerstone.services.sockets.SocketManager</role>
        <service name="org.apache.cornerstone.services.sockets.SocketManager" version="1.0"/>
      </dependency>
      <dependency>
        <role>org.apache.cornerstone.services.connection.ConnectionManager</role>
        <service name="org.apache.cornerstone.services.connection.ConnectionManager" 
                 version="1.0"/>
      </dependency>
    </dependencies>  
  
  </blockinfo>
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/AbstractHttpProxyServer.java
  
  Index: AbstractHttpProxyServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.net.InetAddress;
  import java.net.ServerSocket;
  import java.net.UnknownHostException;
  import org.apache.avalon.AbstractLoggable;
  import org.apache.avalon.ComponentManager;
  import org.apache.avalon.ComponentManagerException;
  import org.apache.avalon.Composer;
  import org.apache.avalon.Context;
  import org.apache.avalon.Contextualizable;
  import org.apache.avalon.Initializable;
  import org.apache.avalon.configuration.Configurable;
  import org.apache.avalon.configuration.Configuration;
  import org.apache.avalon.configuration.ConfigurationException;
  import org.apache.cornerstone.services.connection.ConnectionHandler;
  import org.apache.cornerstone.services.connection.ConnectionHandlerFactory;
  import org.apache.cornerstone.services.connection.ConnectionManager;
  import org.apache.cornerstone.services.sockets.ServerSocketFactory;
  import org.apache.cornerstone.services.sockets.SocketManager;
  import org.apache.phoenix.Block;
  import org.apache.phoenix.BlockContext;
  import org.apache.phoenix.Service;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public abstract class AbstractHttpProxyServer
      extends AbstractLoggable
      implements Block, Contextualizable, Composer, Configurable, Service, 
      Initializable, ConnectionHandlerFactory
  {
      protected SocketManager       m_socketManager;
      protected ConnectionManager   m_connectionManager;
  
      protected String              m_name;
      protected String              m_forwardToAnotherProxy;
      protected int                 m_port;
      protected InetAddress         m_bindTo;
      protected BlockContext        m_context;
  
      public AbstractHttpProxyServer( final String name )
      {
          m_name = name;
      }
  
      public void contextualize( final Context context )
      {
          m_context = (BlockContext)context;
      }
  
      public void configure( final Configuration configuration  )
          throws ConfigurationException
      {
          m_port = configuration.getChild( "listen-port" ).getValueAsInt( 8000 );
  
          try 
          { 
              final String bindAddress = configuration.getChild( "bind" ).getValue();
              m_bindTo = InetAddress.getByName( bindAddress ); 
          }
          catch( final UnknownHostException unhe ) 
          {
              throw new ConfigurationException( "Malformed bind parameter", unhe );
          }
  
          final Configuration forward = configuration.getChild( "forward-to-another-proxy" );
          m_forwardToAnotherProxy = forward.getValue("");
      }
  
      public void compose( final ComponentManager componentManager ) 
          throws ComponentManagerException
      {
          getLogger().info( "HttpProxyServer-" + m_name + ".compose()" );
  
          m_socketManager = (SocketManager)componentManager.
              lookup( "org.apache.cornerstone.services.sockets.SocketManager" );
  
          m_connectionManager = (ConnectionManager)componentManager.
              lookup( "org.apache.cornerstone.services.connection.ConnectionManager" );
      }
      
      public void init()
          throws Exception
      {
          final ServerSocketFactory factory =
              m_socketManager.getServerSocketFactory( "plain" );
          final ServerSocket serverSocket = factory.createServerSocket( m_port, 5, m_bindTo );
          
          m_connectionManager.connect( "HttpProxyListener-" + m_name, serverSocket, this );
      }
  
      /**
       * Construct an appropriate ConnectionHandler.
       *
       * @return the new ConnectionHandler
       * @exception Exception if an error occurs
       */
      public ConnectionHandler createConnectionHandler()
          throws Exception
      {
          final HttpProxyHandler handler = newHttpProxyHandler();
          setupLogger( handler );
          return handler;
      }
  
      protected abstract HttpProxyHandler newHttpProxyHandler();
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/DefaultHttpAuditingProxyServer.java
  
  Index: DefaultHttpAuditingProxyServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.net.Socket;
  import org.apache.log.Logger;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class DefaultHttpAuditingProxyServer 
      extends AbstractHttpProxyServer
      implements HttpAuditingProxyServer
  {
      public DefaultHttpAuditingProxyServer() 
      {
          super("Auditing");
      }
  
      /**
       * Method createHttpProxyHandler
       * Factory method, overriding that of parent, to create the right handler for
       * an individual request.
       */
      protected HttpProxyHandler newHttpProxyHandler()
      {
          return new HttpAuditingProxyHandler( m_forwardToAnotherProxy );
      }
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/DefaultHttpAuditingProxyServer.xinfo
  
  Index: DefaultHttpAuditingProxyServer.xinfo
  ===================================================================
  <?xml version="1.0"?>
  
  <blockinfo>
  
    <meta>
      <contributors>
        <author name="Paul Hammant" email="Paul_Hammant@yahoo.com"/>
      </contributors>
    </meta>
  
    <!-- services that are offered by this block -->
    <services>
      <service name="org.apache.cornerstone.demos.httpproxy.HttpAuditingProxyServer" 
               version="1.0" />
    </services>
    <dependencies>
      <dependency>
        <role>org.apache.cornerstone.services.connection.ConnectionManager</role>
        <service name="org.apache.cornerstone.services.connection.ConnectionManager" 
                 version="1.0"/>
      </dependency>
      <dependency>
        <role>org.apache.cornerstone.services.sockets.SocketManager</role>
        <service name="org.apache.cornerstone.services.sockets.SocketManager" version="1.0"/>
      </dependency>
    </dependencies>  
  
  </blockinfo>
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/DefaultHttpFilteringProxyServer.java
  
  Index: DefaultHttpFilteringProxyServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.net.Socket;
  import java.util.HashSet;
  import java.util.Iterator;
  import org.apache.avalon.configuration.Configuration;
  import org.apache.avalon.configuration.ConfigurationException;
  import org.apache.log.Logger;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class DefaultHttpFilteringProxyServer
      extends AbstractHttpProxyServer
      implements HttpFilteringProxyServer
  {
      // a site may be x.y.z.p.p.hello.com, only check the last two and three parts
      protected HashSet     blockedTwoPartDomains             = new HashSet();
      protected HashSet     blockedThreePartDomains           = new HashSet();
      protected HashSet     cookiesAllowedForTwoPartDomains   = new HashSet();
      protected HashSet     cookiesAllowedForThreePartDomains = new HashSet();
  
      /**
       * Constructor DefaultHttpFilteringProxyServer
       * This is A proxy server that will filter requests.
       */
      public DefaultHttpFilteringProxyServer()
      {
          super( "Filtering" );
      }
  
      public void configure( final Configuration configuration )
          throws ConfigurationException
      {
          super.configure( configuration );
  
          // block listed domains
          final Configuration blockedDomains = configuration.getChild( "blocked-domains" );
          configureBlockedDomains( blockedDomains.getChildren( "blocked-domain" ) );
  
          // mark some domains as having no cookies sent.
          final Configuration cookieDomains = configuration.getChild( "cookies-allowed-domains" );
          configureCookieDomains( cookieDomains.getChildren("cookies-allowed-domain") );
      }
  
      protected void configureBlockedDomains( final Configuration[] domains )
          throws ConfigurationException
      {
          for( int i = 0; i < domains.length; i++ )
          {
              blockAllContentFrom( domains[ i ].getAttribute( "domain-name" ), true );
          }
      }
  
      protected void configureCookieDomains( final Configuration[] domains )
          throws ConfigurationException
      {
          for( int i = 0; i < domains.length; i++ )
          {
              allowCookiesFrom( domains[ i ].getAttribute( "domain-name" ), true );
          }
      }
  
      public boolean domainAllowed( final String domainName )
      {
          return !isDomainInList( domainName,
                                  blockedTwoPartDomains,
                                  blockedThreePartDomains );
      }
  
      public boolean cookieAllowed( final String domainName )
      {
          return isDomainInList( domainName,
                                 cookiesAllowedForTwoPartDomains,
                                 cookiesAllowedForThreePartDomains );
      }
  
      private boolean isDomainInList( String domainName,
                                      final HashSet twoPart,
                                      final HashSet threePart )
      {
          domainName = domainName.toLowerCase();
  
          int dCount = dotCount( domainName );
  
          if( 0 == dCount )
          {
              // no dot, must mean it's inside the intranet.
              return false;
          }
          else
          {
              String domainName2p = domainName;
  
              if( dCount >= 2 )
              {
                  // three or more parts to the domain name.
                  String domainName3p = trimToThreePartDomainName(domainName, dCount);
  
                  if( threePart.contains(domainName3p) )
                  {
                      return true; // it's in the three part list
                  }
  
                  // get rid of first part to make a two part domain name.
                  domainName2p = domainName3p.substring( domainName3p.indexOf('.') + 1,
                                                         domainName3p.length() );
              }
  
              if( twoPart.contains( domainName2p ) )
              {
                  return true; // it's in the two part list.
              }
          }
  
          return false; // default (Homer's two favorite words).
      }
  
      /**
       * Method createHttpProxyHandler
       * Factory method, overriding that of parent, to create the right handler for
       * an individual request.
       */
      protected HttpProxyHandler newHttpProxyHandler()
      {
          return new HttpFilteringProxyHandler( this, m_forwardToAnotherProxy );
      }
  
      public void blockAllContentFrom( final String domainName, final boolean onOff )
      {
          addOrRemoveFromList( domainName,
                               onOff,
                               blockedTwoPartDomains,
                               blockedThreePartDomains );
          getLogger().debug( "blockAllContentFrom " + domainName );
      }
  
      public void allowCookiesFrom( final String domainName,
                                    final boolean onOff )
      {
          addOrRemoveFromList( domainName,
                               onOff,
                               cookiesAllowedForTwoPartDomains,
                               cookiesAllowedForThreePartDomains );
          getLogger().debug( "allowCookiesFrom " + domainName );
      }
  
      private void addOrRemoveFromList( String domainName,
                                        final boolean onOff,
                                        final HashSet twoPart,
                                        final HashSet threePart )
      {
          domainName = domainName.toLowerCase();
  
          int dCount = dotCount( domainName );
  
          if( onOff )
          {
              if( 1 == dCount ) twoPart.add(domainName);
              else if( dCount >= 2 )
              {
                  threePart.add( trimToThreePartDomainName( domainName, dCount ) );
              }
          }
          else
          {
              if( 1 == dCount ) twoPart.remove( domainName );
              else if( dCount >= 2 )
              {
                  threePart.remove( trimToThreePartDomainName( domainName, dCount ) );
              }
          }
      }
  
      private int dotCount( final String domainName )
      {
          int count = 0;
          int ix = domainName.indexOf('.', 0);
  
          while( -1 != ix )
          {
              count++;
              ix = domainName.indexOf( '.', ix + 1 );
          }
  
          return count;
      }
  
      private String trimToThreePartDomainName( final String domainName, int dotCount )
      {
          if( 2 == dotCount ) return domainName;
          else
          {
              int bIx = 0;
  
              while( dotCount-- > 2 )
              {
                  bIx = domainName.indexOf('.', bIx) + 1;
              }
  
              return domainName.substring( bIx, domainName.length() );
          }
      }
  
      public String[] getBlockedDomains() 
      {
          return new String[] {"TODO"}; // TODO PH
      }
  
      /**
       * List the domains for which cookies are not sent.
       */
      public String[] getCookieSuppressedDomains() 
      {
          return new String[] {"TODO"}; // TODO PH
      }
  
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/DefaultHttpFilteringProxyServer.xinfo
  
  Index: DefaultHttpFilteringProxyServer.xinfo
  ===================================================================
  <?xml version="1.0"?>
  
  <blockinfo>
  
    <meta>
      <contributors>
        <author name="Paul Hammant" email="Paul_Hammant@yahoo.com"/>
      </contributors>
    </meta>
  
    <!-- services that are offered by this block -->
    <services>
      <service name="org.apache.cornerstone.demos.httpproxy.HttpFilteringProxyServer" 
               version="1.0" />
    </services>
    <dependencies>
      <dependency>
        <role>org.apache.cornerstone.services.connection.ConnectionManager</role>
        <service name="org.apache.cornerstone.services.connection.ConnectionManager" 
                 version="1.0"/>
      </dependency>
      <dependency>
        <role>org.apache.cornerstone.services.sockets.SocketManager</role>
        <service name="org.apache.cornerstone.services.sockets.SocketManager" version="1.0"/>
      </dependency>
    </dependencies>  
  
  
  </blockinfo>
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpAuditingProxyHandler.java
  
  Index: HttpAuditingProxyHandler.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.net.Socket;
  import org.apache.log.Logger;
  
  /**
   * This handles an individual incoming request.  It outputs a greeting as html.
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class HttpAuditingProxyHandler 
      extends HttpProxyHandler
  {
      protected HttpAuditingProxyHandler( final String forwardToAnotherProxy )
      {
          super( forwardToAnotherProxy);
      }
  
      protected void validateRequest() 
          throws HttpRequestValidationException
      {
          // no validate, just log.
          getLogger().info("Connection to " + httpRequestWrapper.getURL());
      }
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpAuditingProxyServer.java
  
  Index: HttpAuditingProxyServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public interface HttpAuditingProxyServer 
      extends HttpProxyServer 
  {
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpBlockedDomainException.java
  
  Index: HttpBlockedDomainException.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class HttpBlockedDomainException 
      extends HttpRequestValidationException
  {
      /**
       * Constructor HttpBlockedDomainException
       * The domain in question is not allowed to be connected to given the
       * rules of the filter.
       */
      public HttpBlockedDomainException( final String domainName )
      {
          super( "Access to " + domainName + "has been blocked" );
      }
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpFilteringProxyHandler.java
  
  Index: HttpFilteringProxyHandler.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.net.URL;
  import java.util.StringTokenizer;
  
  /**
   * This handles an individual incoming request.  It outputs a greeting as html.
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class HttpFilteringProxyHandler 
      extends HttpProxyHandler
  {
      // used for callbacks
      protected HttpFilteringProxyServer   proxyServer;
  
      /**
       * Constructor HttpFilteringProxyHandler
       *
       */
      protected HttpFilteringProxyHandler( final HttpFilteringProxyServer proxyServer,
                                           final String forwardToAnotherProxy )
      {
          super( forwardToAnotherProxy );
  
          // used for callbacks
          this.proxyServer = proxyServer;
      }
  
      /**
       * Method validateRequest
       * Check to see whether domain name in blocked list.
       *
       * @throws HttpRequestValidationException
       *
       */
      protected void validateRequest() 
          throws HttpRequestValidationException
      {
          final String domainName = httpRequestWrapper.getServerName();
  
          if( !proxyServer.domainAllowed( domainName ) )
          {
              throw new HttpBlockedDomainException( domainName );
              // perhaps this should be:
              // 1) test for image as mime type
              // 2) return 1x1 gif instead.
          }
      }
  
      /**
       * Method getOutgoingHttpRequest
       * Overrides that of parent, adding cookie removal functionality for the
       * filtering proxy server.
       *
       * @param anotherProxy
       *
       * @return
       *
       */
      public String getOutgoingHttpRequest( final boolean anotherProxy )
      {
          final String domainName = httpRequestWrapper.getServerName();
          final String httpRequest = super.getOutgoingHttpRequest( anotherProxy );
  
          if( !proxyServer.cookieAllowed( domainName ) ) 
          {
              final String request = 
                  getHttpRequestWithoutCookie( httpRequest, httpRequestWrapper.getURL() );
              return request.trim() + "\r\n\r\n";
          } 
          else
          {
              return httpRequest;
          }
      }
  
      private String getHttpRequestWithoutCookie( final String httpRequest, final URL url )
      {
          final StringBuffer newHttpRequest = new StringBuffer();
          final StringTokenizer rqstTokens = new StringTokenizer( httpRequest, "\n\r" );
  
          while( rqstTokens.hasMoreTokens() )
          {
              final String line = rqstTokens.nextToken();
  
              if( !line.startsWith("Cookie:") )
              {
                  newHttpRequest.append( line ).append( "\r\n" );
              } 
              else
              {
                  getLogger().info( "Cookie supressed for url :" + url.toString() );
              }
          }
  
          return newHttpRequest.toString().trim() + "\n\r";
      }
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpFilteringProxyServer.java
  
  Index: HttpFilteringProxyServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public interface HttpFilteringProxyServer
      extends HttpProxyServer
  {
      /**
       * Method blockAllContentFrom No requests will reach this site.
       */
      void blockAllContentFrom( String domainName, boolean onOff );
  
      /**
       * Method allowCookiesFrom Allows Cookies to be sent to this site.
       * This is kinda redundant with some of the features of Netscape 4.x and 6.x
       */
      void allowCookiesFrom( String domainName, boolean onOff );
  
      /**
       * Method domainAllowed Check to see whether the appl domain should be blocked
       */
      boolean domainAllowed( String domainName );
  
      /**
       * Method cookieAllowed Check to see whether the appl domain can be sent cookies
       */
      boolean cookieAllowed( String domainName );
  
      /**
       * List the domains that are completely blocked.
       */
      String[] getBlockedDomains();
  
      /**
       * List the domains for which cookies are not sent.
       */
      String[] getCookieSuppressedDomains();
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpGetRequestWrapper.java
  
  Index: HttpGetRequestWrapper.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.io.IOException;
  import java.io.InputStream;
  import org.apache.log.Logger;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class HttpGetRequestWrapper 
      extends HttpRequestWrapper
  {
      protected HttpGetRequestWrapper( final Logger logger, final String rq ) 
          throws IOException
      {
          super( logger, rq );
      }
  
      protected HttpGetRequestWrapper( final Logger logger, final InputStream is ) 
          throws IOException
      {
          super( logger );
  
          String wholeBuffer = "GET";
          byte[] bytes = new byte[ SEGLEN ];
          int bytesRead = is.read( bytes );
  
          do 
          {
              wholeBuffer += new String( bytes, 0, bytesRead );
  
              if( !wholeBuffer.endsWith( EOF ) )
              {
                  bytesRead = is.read( bytes );
              }
          } 
          while( !wholeBuffer.endsWith( EOF ) );
  
          super.setRequest( wholeBuffer );
      }
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpPostRequestWrapper.java
  
  Index: HttpPostRequestWrapper.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.io.IOException;
  import java.io.InputStream;
  import org.apache.log.Logger;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class HttpPostRequestWrapper extends HttpRequestWrapper {
  
      protected HttpPostRequestWrapper( final Logger logger, final String rq ) 
          throws IOException
      {
          super( logger, rq );
      }
  
      protected HttpPostRequestWrapper( final Logger logger, final InputStream is )
          throws IOException
      {
          super( logger );
  
          String wholeBuffer = "POST";
  
          is.read( new byte[1] ); // T from post
  
          byte[] bytes = new byte[SEGLEN];
          int bytesRead = is.read( bytes );
          int contLen;
          int lenAfterContent;
  
          do 
          {
              wholeBuffer += new String( bytes, 0, bytesRead );
  
              String tmpRqst = wholeBuffer.toUpperCase();
  
              contLen = getContentLength( tmpRqst );
              lenAfterContent = getLengthAfterContent( tmpRqst );
  
              if( -1 == wholeBuffer.indexOf( EOF ) ) 
              {
                  bytesRead = is.read( bytes );
              }
          } 
          while( ( lenAfterContent < contLen ) && 
                 ( -1 == wholeBuffer.indexOf( EOF ) ) );
  
          super.setRequest( wholeBuffer );
      }
  
      private int getContentLength( final String rqst ) 
      {
          int firstDigit = rqst.indexOf("CONTENT-LENGTH:") + 16;
  
          if( -1 != firstDigit )
          {
              final int lastDigit = rqst.indexOf( "\n", firstDigit );
              return Integer.parseInt( rqst.substring( firstDigit, lastDigit ).trim() );
          }
  
          return 0;
      }
  
      private int getLengthAfterContent( final String rqst )
      {
          int firstDigit = rqst.indexOf( "CONTENT-LENGTH:" ) + 16;
  
          if( -1 != firstDigit )
          {
              return rqst.length() - firstDigit;
          }
  
          return 0;
      }
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpProxyHandler.java
  
  Index: HttpProxyHandler.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.io.*;
  import java.net.ConnectException;
  import java.net.Socket;
  import java.net.SocketException;
  import java.net.UnknownHostException;
  import org.apache.avalon.AbstractLoggable;
  import org.apache.avalon.Component;
  import org.apache.cornerstone.services.connection.ConnectionHandler;
  
  /**
   * This handles an individual incoming request.  It returns a bytes etc from remote server.
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public abstract class HttpProxyHandler
      extends AbstractLoggable
      implements Component, ConnectionHandler
  {
      protected Socket              clientSocket;
      protected Socket              serverSocket;
      protected String              clientHost;
      protected String              clientIP;
      protected String              forwardToAnotherProxy;
      protected HttpRequestWrapper  httpRequestWrapper;
  
      protected HttpProxyHandler( final String forwardToAnotherProxy )
      {
          this.forwardToAnotherProxy = forwardToAnotherProxy;
      }
  
      /**
       * Handle a connection.
       * This handler is responsible for processing connections as they occur.
       *
       * @param socket the connection
       * @exception IOException if an error reading from socket occurs
       */
      public void handleConnection( final Socket socket )
          throws IOException
      {
          this.clientSocket = socket;
          clientHost = clientSocket.getInetAddress().getHostName();
          clientIP = clientSocket.getInetAddress().getHostAddress();
  
          try
          {
              httpRequestWrapper =
                  HttpRequestWrapper.createHttpRequestWrapper( getLogger(),
                                                               clientSocket.getInputStream() );
  
              validateRequest();
              forwardRequest();
          } 
          catch( final HttpRequestValidationException hrve ) 
          {
              write403Page();
              getLogger().info( hrve.getMessage() );
          } 
          catch( final SocketException se ) 
          {
              getLogger().debug( "Socket to " + clientHost + " closed remotely.", se );
          } 
          catch( final InterruptedIOException iioe ) 
          {
              getLogger().debug( "Socket to " + clientHost + " timeout.", iioe );
          } 
          catch( final IOException ioe ) 
          {
              getLogger().debug( "Exception in proxy handling socket to " + clientHost, ioe );
          } 
          catch( final Exception e )
          {
              getLogger().debug( "Exception in proxy opening socket", e );
          } 
          finally
          {
              try { clientSocket.close(); } 
              catch( final IOException ioe )
              {
                  getLogger().error( "Exception closing client socket ", ioe );
              }
  
              if( null != serverSocket )
              {
                  try { serverSocket.close(); } 
                  catch( final IOException ioe )
                  {
                      getLogger().error( "Exception closing server socket ", ioe );
                  }
              }
          }
      }
  
      protected Socket makeOutgoingSocket() 
          throws IOException
      {
          if( !forwardToAnotherProxy.equals("") )
          {
              int colon = forwardToAnotherProxy.indexOf(':');
              String toName = forwardToAnotherProxy.substring(0, colon);
              int toPort = Integer.
                  parseInt( forwardToAnotherProxy.substring( colon + 1,
                                                             forwardToAnotherProxy.length() ) );
  
              return new Socket( toName, toPort );
          } 
          else
          {
              return new Socket( httpRequestWrapper.getServerInetAddress(),
                                 httpRequestWrapper.getServerPort() );
          }
      }
  
      public String getOutgoingHttpRequest( final boolean anotherProxy )
      {
          if( anotherProxy )
          {
              return httpRequestWrapper.getNakedHttpRequest().trim() + "\r\n\r\n";
          } 
          else
          {
              return httpRequestWrapper.getHttpRequest().trim() + "\r\n\r\n";
          }
      }
  
      public final void forwardRequest() 
          throws IOException
      {
          String request = getOutgoingHttpRequest( ( !forwardToAnotherProxy.equals("") ) );
  
          try
          {
              serverSocket = makeOutgoingSocket();
  
              serverSocket.getOutputStream().write( request.getBytes() );
  
              byte[] page = new byte[2048];
              int pLength;
              BufferedOutputStream bufToClient =
                  new BufferedOutputStream( clientSocket.getOutputStream() );
              InputStream serverIS = serverSocket.getInputStream();
  
              do
              {
                  pLength = serverIS.read( page );
  
                  if( -1 != pLength ) 
                  {
                      bufToClient.write( page, 0, pLength );
                  }
              } 
              while( -1 != pLength );
  
              bufToClient.close();
          } 
          catch( final Exception e )
          {
              // general catch is deliberate, see writeErrorPage(..)
              writeErrorPage( e );
          }
      }
  
      private void writeErrorPage( final Exception e ) 
          throws IOException
      {
          final PrintWriter output = new PrintWriter( clientSocket.getOutputStream() );
          
          output.println( "<html><body>Unable to reach <b>" + httpRequestWrapper.getServerName() + 
                          ":" + httpRequestWrapper.getServerPort() + "</b> at the moment." );
          output.println( "<br />This Message is bought to you by the Avalon demo proxy server." );
          output.println( "<br />If you had a direct connection to the net, you would not see " + 
                          "this message, your browser would instead tell you it could not reach" +
                          " the site.<br />");
  
          if( e instanceof UnknownHostException )
          {
              output.println( "<br />The probable cause is that the domain name does not exist," + 
                              " of the route to it is severed." );
          } 
          else if( e instanceof ConnectException )
          {
              output.println( "<br />The probable cause is that the machine at domain name is" +
                              " not running a service at the port number in question (HTTP or" +
                              " any other)." );
          } 
          else
          {
              output.println( "<br />The cause is unknown, this may help though: " + 
                              e.getMessage() );
          }
  
          output.println( "</body></head>" );
          output.flush();
          output.close();
      }
  
      // Block the resource, buy using http code 403.
      // "403 Forbidden Resource is not available, regardless of authorization."
      private void write403Page() 
      {
          try
          {
              final PrintWriter output = new PrintWriter( clientSocket.getOutputStream() );
  
              output.println( "<html><head><title>Blocked</title></head>" + 
                              "<body>Blocked</body></html>" );
              output.flush();
              output.close();
          } 
          catch( final IOException ioe ) {}
      }
  
      protected abstract void validateRequest() 
          throws HttpRequestValidationException;
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpProxyServer.java
  
  Index: HttpProxyServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import org.apache.phoenix.Service;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public interface HttpProxyServer
      extends Service
  {
   // nothing here yet, but there could be a way of chaining proxy servers
   // without sockets.....
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpRequestValidationException.java
  
  Index: HttpRequestValidationException.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class HttpRequestValidationException 
      extends Exception
  {
      /**
       * Constructor HttpRequestValidationException
       * Thrown when somethod failed during the handlers validation stage.
       */
      public HttpRequestValidationException( final String message ) 
      {
          super( message );
      }
  }
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/httpproxy/HttpRequestWrapper.java
  
  Index: HttpRequestWrapper.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.httpproxy;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.InetAddress;
  import java.net.MalformedURLException;
  import java.net.URL;
  import java.net.UnknownHostException;
  import org.apache.log.Logger;
  
  /**
   * @author  Paul Hammant <Pa...@yahoo.com>
   * @version 1.0
   */
  public class HttpRequestWrapper 
  {
      protected final static String     EOF        = "\r\n\r\n";
      protected final static int        SEGLEN     = 2048;
  
      protected final Logger            m_logger;
      protected String                  m_request;
      protected URL                     m_url;
  
      protected HttpRequestWrapper( final Logger logger ) 
      {
          m_logger = logger;
      }
  
      protected HttpRequestWrapper( final Logger logger, final String request ) 
          throws IOException
      {
          this( logger );
          setRequest( request );
      }
  
      protected void setRequest( final String request ) 
          throws IOException
      {
          m_request = request;
  
          try
          {
              m_url = new URL( getURLFromHttpHeader() );
          } 
          catch( final MalformedURLException mfue )
          {
              m_logger.error( "URL from http header is malformed", mfue );
          }
      }
  
      public final URL getURL() 
      {
          return m_url;
      }
  
      /**
       * Method getServerInetAddress
       * The server's internet address.
       */
      public final InetAddress getServerInetAddress() 
          throws UnknownHostException
      {
          return InetAddress.getByName( m_url.getHost() );
      }
  
      private String getURLFromHttpHeader() 
      {
          try
          {
              int hostStart = m_request.indexOf( " " ) + 1;
  
              return m_request.substring( hostStart, 
                                          m_request.indexOf( " ", hostStart ) );
          } 
          catch( final StringIndexOutOfBoundsException sioobe )
          {
              m_logger.error( "Unable to find URL in http header", sioobe );
          }
  
          return null;
      }
  
      /**
       * Method getServerName
       * The server's domain name
       */
      public String getServerName() 
      {
          return m_url.getHost();
      }
  
      /**
       * Method getServerPort
       * The port on the server where the http requests should be sent.
       */
      public int getServerPort() 
      {
          final int port = m_url.getPort();
  
          return ((port == -1) ? 80 : port);
      }
  
      /**
       * Method getNakedHttpRequest
       * Used to forward requests to another proxy server
       */
      public final String getNakedHttpRequest() 
      {
          return m_request;
      }
  
      /**
       * Method getHttpRequest
       * Get the address without the proxy extras
       */
      public String getHttpRequest() 
      {
          // strip out proxy info.
          int hostEnd = 1 + 
              m_request.indexOf( "/", m_request.indexOf( "//" ) + 2 );
          
          return 
              m_request.substring( 0, m_request.indexOf("http://") ) + "/" + 
              m_request.substring( hostEnd, m_request.length() );
      }
  
      /**
       * Method createHttpRequestWrapper
       * Factory to create the right sub class of HttpRequestWrapper.
       *
       */
      static HttpRequestWrapper createHttpRequestWrapper( final Logger logger, 
                                                          final InputStream is )
          throws IOException 
      {
          byte[] threeBytes = new byte[3];
          int bytes = is.read( threeBytes );
  
          if( 3 != bytes )
          {
              throw new RuntimeException( "not three bytes?" );
          }
  
          final String reqType = new String( threeBytes, 0, bytes );
  
          if( reqType.equals("POS") ) 
          {
              return new HttpPostRequestWrapper( logger, is );
          } 
          else
          {
              return new HttpGetRequestWrapper( logger, is );
          }
      }
  }
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/simpleserver/DummyClass.java
  
  Index: DummyClass.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.simpleserver;
  
  import java.io.Serializable;
  
  /**
   * This is a dummy class to test Store. If this is in a seperate bar
   * from the masterstore classes, reading it from disc will throw a
   * ClassNotFoundException.
   *
   * @author Charles Benett <ch...@benett1.demon.co.uk>
   */
  public class DummyClass 
      implements Serializable
  {
      private String    m_name;
  
      public void setName( final String name )
      {
          m_name = name;
      }
  
      public String getName() 
      {
          return m_name;
      }
  }
  
  
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/simpleserver/SimpleServer.java
  
  Index: SimpleServer.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.simpleserver;
  
  import java.io.*;
  import java.net.ServerSocket;
  import java.net.ProtocolException;
  import java.net.Socket;
  import java.net.SocketException;
  import java.util.Iterator;
  import java.util.StringTokenizer;
  import org.apache.avalon.AbstractLoggable;
  import org.apache.avalon.Component;
  import org.apache.avalon.ComponentManager;
  import org.apache.avalon.ComponentManagerException;
  import org.apache.avalon.Composer;
  import org.apache.avalon.configuration.Configurable;
  import org.apache.avalon.configuration.Configuration;
  import org.apache.avalon.configuration.ConfigurationException;
  import org.apache.avalon.Initializable;
  import org.apache.phoenix.Block;
  import org.apache.cornerstone.services.Store;
  import org.apache.cornerstone.services.sockets.SocketManager;
  import org.apache.cornerstone.services.sockets.ServerSocketFactory;
  import org.apache.cornerstone.services.connection.ConnectionHandler;
  import org.apache.cornerstone.services.connection.ConnectionHandlerFactory;
  import org.apache.cornerstone.services.connection.ConnectionManager;
  import org.apache.cornerstone.services.scheduler.TimeScheduler;
  import org.apache.cornerstone.services.scheduler.Target;
  import org.apache.cornerstone.services.scheduler.CronTimeTrigger;
  import org.apache.cornerstone.services.scheduler.PeriodicTimeTrigger;
  import org.apache.cornerstone.services.scheduler.TimeTrigger;
  
  /**
   * This is a demo block used to demonstrate a simple server using Avalon. The
   * server listens on a port specified in .confs. All commands are one line
   * commands. It understands three commands: PUT, COUNT, LIST.
   * <br>PUT <string> stores the given string on the file system
   * <br>COUNT counts the number of strings stored
   * <br>LIST responds with all the strings, one per line.
   *
   * @author Charles Benett <ch...@benett1.demon.co.uk>
   * @author Federico Barbieri <fe...@apache.org>
   * @author <a href="mailto:donaldp@apache.org">Peter Donald</a>
   */
  public class SimpleServer 
      extends AbstractLoggable 
      implements Block, SimpleService, Composer, Configurable, Initializable,
      ConnectionHandlerFactory, ConnectionHandler, Target
  {
      protected TimeScheduler           m_timeScheduler;
      protected Configuration           m_configuration;
      protected SocketManager           m_socketManager;
      protected ConnectionManager       m_connectionManager;
      protected Store                   m_testStore;
      protected Store.ObjectRepository  m_repository;
  
      protected PrintWriter             m_out;
      protected int                     m_count;
  
      public void compose( final ComponentManager componentManager )
          throws ComponentManagerException
      {
          m_testStore = 
              (Store)componentManager.lookup( "org.apache.cornerstone.services.Store" );
  
          m_socketManager = (SocketManager)componentManager.
              lookup( "org.apache.cornerstone.services.sockets.SocketManager" );
  
          m_connectionManager = (ConnectionManager)componentManager.
              lookup( "org.apache.cornerstone.services.connection.ConnectionManager" );
  
          m_timeScheduler = (TimeScheduler)componentManager.
              lookup( "org.apache.cornerstone.services.scheduler.TimeScheduler" );
      }
  
      public void configure( final Configuration configuration )
          throws ConfigurationException
      {
          m_configuration = configuration;
      }
  
      public void init() 
          throws Exception
      {
          getLogger().info( "init Demo ..." );
  
          final Configuration repConf = m_configuration.getChild( "repository" );
          getLogger().info( "Want to use repository in:" + 
                            repConf.getAttribute( "destinationURL" ) );
          m_repository = (Store.ObjectRepository)m_testStore.select( repConf );
          getLogger().info( "Got repository" );
  
          TimeTrigger trigger = null;
  
          trigger = new PeriodicTimeTrigger( -1, 2 * 1000 );
          m_timeScheduler.addTrigger( "try", trigger, this );
  
          trigger = new PeriodicTimeTrigger( 9 * 1000, -1 );
          m_timeScheduler.addTrigger( "do", trigger, this );
  
          //trigger = new CronTimeTrigger( -1, -1, -1, -1, -1, false );
          //m_timeScheduler.addTrigger( "cron-trigger", trigger, this );
  
          final int port = m_configuration.getChild( "port" ).getValueAsInt();
          getLogger().info( "Want to open port on:" + port );
  
          final ServerSocketFactory factory = 
              m_socketManager.getServerSocketFactory( "plain" );
          final ServerSocket serverSocket = factory.createServerSocket( port );
  
          m_connectionManager.connect( "DemoListener", serverSocket, this );
  
          getLogger().info( "Got socket" );
  
          getLogger().info( "...Demo init" );
      }
  
      /**
       * Construct an appropriate ConnectionHandler.
       *
       * @return the new ConnectionHandler
       * @exception Exception if an error occurs
       */
      public ConnectionHandler createConnectionHandler()
          throws Exception
      {
          //Can return this because the ConnectionHandler is thread safe
          return this;
      }    
  
      /**
       * Handle a connection.
       * This handler is responsible for processing connections as they occur.
       *
       * @param socket the connection
       * @exception IOException if an error reading from socket occurs
       * @exception ProtocolException if an error handling connection occurs
       */
      public void handleConnection( final Socket socket )
          throws IOException, ProtocolException
      {
          String remoteHost = null;
          String remoteIP = null;
  
          try
          {
              final BufferedReader in = 
                  new BufferedReader( new InputStreamReader( socket.getInputStream() ), 1024 );
              m_out = 
                  new PrintWriter( new BufferedOutputStream( socket.getOutputStream()), true );
  
              remoteHost = socket.getInetAddress().getHostName();
              remoteIP = socket.getInetAddress().getHostAddress();
  
              getLogger().info( "Connection from " + remoteHost + " ( " + remoteIP + " )" );
             
              //Greet connection
              m_out.println( "Welcome to the Avalon Demo Server!" );
             
              // Handle connection
              while( parseCommand( in.readLine()) )
              {
                  // timeServer.resetAlarm(this.toString());
              }
             
              //Finish
              m_out.flush();
              socket.close();
          } 
          catch( final SocketException se )
          {
              getLogger().info( "Socket to " + remoteHost + " closed remotely." );
          } 
          catch( final InterruptedIOException iioe )
          {
              getLogger().info( "Socket to " + remoteHost + " timeout." );
          }
          catch( IOException ioe ) 
          {
              getLogger().info( "Exception handling socket to " + remoteHost + ":" + 
                                ioe.getMessage() );
          } 
          catch( final Exception e )
          {
              getLogger().info( "Exception on socket: " + e.getMessage() );
          } 
          finally
          {
              try { socket.close(); } 
              catch( final IOException ioe )
              {
                  getLogger().error( "Exception closing socket: " + ioe.getMessage() );
              }
          }
      }
  
      public void targetTriggered( final String triggerName )
      {
          if( triggerName.equals( "do" ) )
          {
              try
              {
                  m_timeScheduler.removeTrigger( "try" );
              } 
              catch( final Exception e )
              {
                  e.printStackTrace();
              }
          }
  
          System.out.println( "Target triggered: " + triggerName );
      }
  
      protected boolean parseCommand( String command )
          throws Exception 
      {
          if( null == command )
          {
              return false;
          }
  
          getLogger().info( "Command received: " + command );
  
          StringTokenizer commandLine = new StringTokenizer( command.trim() );
          int arguments = commandLine.countTokens();
          String argument = null;
          if( 0 == arguments ) 
          {
              return true;
          }
  
          String fullcommand = command;
          command = commandLine.nextToken();
          if( arguments > 1 ) 
          {
              argument = fullcommand.substring(command.length() + 1);
          }
         
          if( command.equalsIgnoreCase( "TEST" ) )
          {
              m_out.println( "You said 'TEST'" );
  
              final DummyClass write = new DummyClass();
              write.setName( argument );
  
              try { m_repository.put( argument, write ); } 
              catch( final Exception e )
              {
                  getLogger().warn( "Exception putting into repository: " + e );
              }
  
              m_out.println( "Dummy written, trying for read" );
              try  { final Iterator it = m_repository.list(); } 
              catch( Exception e )
              {
                  getLogger().warn( "Exception reading from repository: " + e, e );
              }
  
              DummyClass read = null;
              try { read = (DummyClass) m_repository.get(argument); } 
              catch( final Exception e )
              {
                  getLogger().warn( "Exception reading from repository: " + e, e );
              }
  
              m_out.println( "Recovered: " + read.getName() );
              return true;
          } 
          else if( command.equalsIgnoreCase( "PUT" ) )
          {
              m_out.println( "You said 'PUT'" );
              final String key = "AMsg" + ++m_count;
              m_repository.put( key, argument );
              return true;
          }
          else if( command.equalsIgnoreCase( "LIST" ) ) 
          {
              m_out.println( "You said 'LIST'" );
  
              final Iterator it = m_repository.list();
              
              while( it.hasNext() )
              {
                  String k = (String)it.next();
                  String txt = (String) m_repository.get( k );
                  m_out.println( "Msg " + k + " was " + txt );
              }
              m_out.println( "That's All folks!" );
              return true;
          } 
          else if( command.equalsIgnoreCase( "COUNT" ) )
          {
              m_out.println( "You said 'COUNT'" );
              Iterator it = m_repository.list();
              int c = 0;
              
              while( it.hasNext() )
              {
                  Object ignore = it.next();
                  c=c+1;
              }
  
              m_out.println( "Number of messages in repository is: " + c );
              return true;
          } 
          else
          {
              m_out.println( "Only valid commands are: PUT, LIST or COUNT." );
              return true;
          }
      }
  }
  
  
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/simpleserver/SimpleServer.xinfo
  
  Index: SimpleServer.xinfo
  ===================================================================
  <?xml version="1.0"?>
  
  <blockinfo>
  
    <meta>
  
      <contributors>
        <author name="Charles Benett" email="charles@benett1.demon.co.uk"/>
        <author name="Federico Barbieri" email="fede@apache.org"/>
        <author name="Peter Donald" email="donaldp@apache.org"/>
      </contributors>
  
    </meta>
  
    <!-- services that are offered by this block -->
    <services>
      <service name="org.apache.cornerstone.demos.simpleserver.SimpleService" version="1.0" />
    </services>
  
    <dependencies>
      <dependency>
        <role>org.apache.cornerstone.services.Store</role>
        <service name="org.apache.cornerstone.services.Store" version="1.0"/>
      </dependency>
      <dependency>
        <role>org.apache.cornerstone.services.connection.ConnectionManager</role>
        <service name="org.apache.cornerstone.services.connection.ConnectionManager" 
                 version="1.0"/>
      </dependency>
      <dependency>
        <role>org.apache.cornerstone.services.sockets.SocketManager</role>
        <service name="org.apache.cornerstone.services.sockets.SocketManager" version="1.0"/>
      </dependency>
      <dependency>
        <role>org.apache.cornerstone.services.scheduler.TimeScheduler</role>
        <service name="org.apache.cornerstone.services.scheduler.TimeScheduler" version="1.0"/>
      </dependency>
    </dependencies>
  </blockinfo>
  
  
  
  1.1                  jakarta-avalon-cornerstone/src/java/org/apache/cornerstone/demos/simpleserver/SimpleService.java
  
  Index: SimpleService.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.cornerstone.demos.simpleserver;
  
  import org.apache.phoenix.Service;
  
  /**
   * This is an empty service interface for the SimpleServer demo block
   *
   * @author Charles Benett <ch...@benett1.demon.co.uk>
   */
  public interface SimpleService 
      extends Service
  {
  }