axis-java-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From hawk...@apache.org
Subject cvs commit: ws-axis/c/tests/utils/monitor/org/apache/test ClientReturner.java StopRequestException.java StopTCPMonitor.java TestClientListener.java TCPMonitor.java TestClientThread.java
Date Mon, 06 Jun 2005 17:07:42 GMT
hawkeye     2005/06/06 10:07:42

  Modified:    c/tests/utils/monitor/org/apache/test StopTCPMonitor.java
                        TestClientListener.java TCPMonitor.java
                        TestClientThread.java
  Added:       c/tests/utils/monitor/org/apache/test ClientReturner.java
                        StopRequestException.java
  Log:
  Altered The Monitor so that it only creates threads when it needs them. it's a lot more
efficient now than it used to be.
  
  Revision  Changes    Path
  1.5       +4 -1      ws-axis/c/tests/utils/monitor/org/apache/test/StopTCPMonitor.java
  
  Index: StopTCPMonitor.java
  ===================================================================
  RCS file: /home/cvs/ws-axis/c/tests/utils/monitor/org/apache/test/StopTCPMonitor.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- StopTCPMonitor.java	19 Apr 2005 16:29:33 -0000	1.4
  +++ StopTCPMonitor.java	6 Jun 2005 17:07:42 -0000	1.5
  @@ -31,15 +31,18 @@
   	}
   
   	public void stopMonitor() {
  +	    System.out.println( "StopTCPMonitor#stopMonitor(): Sending stop message to monitor");
   		Socket socket = null;
   		BufferedWriter dos = null;
   		try {
   		socket = new Socket(hostname, port);
   			dos = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
   			dos.write(STOPTCPMON);
  +			dos.flush();
   		} catch (UnknownHostException uhe) {
   			uhe.printStackTrace();
   		} catch (ConnectException ce) {
  +		    ce.printStackTrace();
   		} catch (IOException ie) {
   			ie.printStackTrace();
   		} finally {
  @@ -47,7 +50,7 @@
   				dos.close();
   				socket.close();
   			} catch (Exception exe) {
  -				;
  +			    exe.printStackTrace();
   			}
   		}
   	}
  
  
  
  1.8       +107 -189  ws-axis/c/tests/utils/monitor/org/apache/test/TestClientListener.java
  
  Index: TestClientListener.java
  ===================================================================
  RCS file: /home/cvs/ws-axis/c/tests/utils/monitor/org/apache/test/TestClientListener.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- TestClientListener.java	19 Apr 2005 16:29:33 -0000	1.7
  +++ TestClientListener.java	6 Jun 2005 17:07:42 -0000	1.8
  @@ -21,230 +21,148 @@
   /**
    * TestClientListener runs as a thread of the
    * 
  - * @see TestSingleton class and creates a ServerSocket object on port <b>6323
  - *      <b>and from this creates a socket that accepts incoming requests. When a
  - *      request is received new threads are created of type
  + * @see TestSingleton class and creates a ServerSocket object on a port and from
  + *      this creates a socket that accepts incoming requests. When a request is
  + *      received new threads are created of type
    * @see TestClientThread which do all the communication.
  - * @author Andrew Perry
  + * @author Andrew Perry, hawkeye
    * @since 1.0
    */
   
   public class TestClientListener implements Runnable
   {
  -    private int             CREATE_SOCKET_TO_SERVER_RETRY =5;
  -    int                     listenPort                    =0;
  -    int                     servicePort                   =0;
  -    String                  serviceHost                   =null;
  -    boolean                 stayAlive                     =false;
  -    ServerSocket            server                        =null;
  -    Thread                  thisThread                    =null;
  -
  -    public static final int CAPTURE_REQUEST               =1;
  -    public static final int CAPTURE_RESPONSE              =2;
  -
  -    public TestClientListener( )
  -    {}
  +    private int     servicePort    =0;
  +    private String  serviceHostNme =null;
  +    private boolean stayAlive      =false;
  +    ServerSocket    serverSocket   =null;
   
  +    /**
  +     * 
  +     * @param listenPort the port to listen for clients requests on
  +     * @param serviceHost the host that the service is on.
  +     * @param servicePort the port that the service is on
  +     * @throws IOException if we can't create a server socket listening for the
  +     *             client to send us a request
  +     */
       public TestClientListener(int listenPort, String serviceHost,
  -            int servicePort)
  +            int servicePort) throws IOException
       {
  -        this.listenPort=listenPort;
  -        this.serviceHost=serviceHost;
  +        this.serviceHostNme=serviceHost;
           this.servicePort=servicePort;
  -    }
  -
  -    public void startListener( )
  -    {
  -        if (thisThread!=null&&thisThread.isAlive( ))
  -            throw new IllegalStateException("ServerManager already running");
   
  -        try
  -        {
  -            server=new ServerSocket(listenPort);
  -            thisThread=new Thread(this);
  -            thisThread.start( );
  -        }
  -        catch (Exception ioe)
  -        {
  -            ioe.printStackTrace(System.err);
  -        }
  -    }
  -
  -    public void stopListener( )
  -    {
  -        stayAlive=false;
  -        if (thisThread.isAlive( ))
  -        {
  -            try
  -            {
  -                thisThread.join( );
  -            }
  -            catch (InterruptedException interruptedException)
  -            {
  -                // this is fine
  -                interruptedException.printStackTrace( );
  -            }
  -        }
  +        // no point in carrying on if we can't listen to the client !
  +        serverSocket=new ServerSocket(listenPort);
       }
   
       /**
  -     * Implementation of
  -     * 
  -     * @see Runnable run method required for
  +     *
  +     * Sits waiting for a client thread and when one connects we start up a new TestClientThread
to handle
  +     * the request. This method then goes round again waiting for future requests.
  +     *  
        * @see Thread
        */
       public void run( )
       {
           stayAlive=true;
           Socket clientSocket=null;
  -        Socket serviceSocket=null;
  -        try
  -        {
  -            TestClientThread requestReader=null;
  -            TestClientThread responseReader=null;
  -            while (stayAlive==true)
  -            {
  -                // server.setSoTimeout(500);
  -                try
  -                {
  -                    clientSocket=server.accept( );
  -                    serviceSocket = createSocketToServer();
  -
  -                    if (serviceSocket==null)
  -                    {
  -                        continue;
  -                    }
  -
  -                    requestReader=new TestClientThread(clientSocket,
  -                            serviceSocket, CAPTURE_REQUEST);
  -                    
  -                    responseReader=new TestClientThread(clientSocket,
  -                            serviceSocket, CAPTURE_RESPONSE);
  -                    requestReader.start( );
  -                    // wait for it to receive a request before starting the responsereader
  -                    int bytes =0;
  -                    while((bytes=requestReader.getBytes())==0)
  -                    {
  -                        // sleep here while waiting for them to receive their first bytes.
  -                        thisThread.sleep(100);
  -                    }
  -                    
  -                    // OK so the requestreader has some bytes; Now see whether they have
the number of
  -                    // bytes that we expect them to get for a stoptcpmon request
  -                    if(bytes==StopTCPMonitor.STOPTCPMON.length())
  -                    {
  -                        // probably means that they have got a stop request
  -                        // yield to the other threads and see if they stop
  -                        thisThread.yield();
  -                        
  -                        // now see if they are still alive
  -                        // if they've been told to stop then we should stop listening for
  -                        // new requests
  -                        stayAlive = requestReader.continueToRun;
  -                    }
  -                    else
  -                    {
  -                        responseReader.start( );
  -                    }
  -                    
  -                    try
  -                    {
  -                        // If the response reader is still running then
  -                        // ask it to stop and wait for it.
  -                        if (responseReader.isAlive( ))
  -                        {
  -                            responseReader.cease( );
  -                            // Wait for upto another .5 secs for the request
  -                            // reader to finish
  -//                            responseReader.join(2000);
  -                            responseReader.join();
  -                        }
  -                    }
  -                    catch (Exception me)
  -                    {
  -                        me.printStackTrace(System.err);
  -                    }
  -                    finally
  -                    {
  -                        try
  -                        {
  -                            if (clientSocket!=null)
  -                                clientSocket.close( );
  -                            if (serviceSocket!=null)
  -                                serviceSocket.close( );
  -                        }
  -                        catch (IOException mie)
  -                        {
  -                            mie.printStackTrace(System.err);
  -                        }
  -                    }
  -                }
  -                catch (SocketTimeoutException ste)
  -                {
  -                    ste.printStackTrace();
  -                }
  -            }
  -        }
  -        catch (Exception e)
  +        //        try
  +        //        {
  +        //            //serverSocket.setSoTimeout(2000);
  +        //        }
  +        //        catch(SocketException exception)
  +        //        {
  +        //            exception.printStackTrace();
  +        //        }
  +        while (stayAlive==true)
           {
  -            System.err.println("TestClientListener exception: "+e.getMessage( ));
  -        }
  -        if (server!=null)
               try
               {
  -                if (clientSocket!=null)
  -                    clientSocket.close( );
  -                if (serviceSocket!=null)
  -                    serviceSocket.close( );
  -                server.close( );
  -            }
  -            catch (IOException ioe)
  -            {
  -                //ioe.printStackTrace(System.err);
  +//                System.out
  +//                        .println("TestClientListener#run(): Waiting for a new client
request");
  +                clientSocket=serverSocket.accept( );
  +//                System.out
  +//                        .println("TestClientListener#run():Got a client new client request");
               }
  -        server=null;
  -        stayAlive=false;
  -    }
  -    
  -    public Socket createSocketToServer()
  -    {
  -        Socket serviceSocket=null;
  -        int retry=CREATE_SOCKET_TO_SERVER_RETRY;
  -        do
  -        {
  -            try
  +            catch (SocketTimeoutException socketTimeoutException)
               {
  -                serviceSocket=new Socket(serviceHost, servicePort);
  +                // System.out.println( "socket timedout");
  +                // that's fine - this is what helps us get out of this loop
               }
  -            catch (Exception se)
  +            catch (IOException exception)
               {
                   System.err
  -                        .println("Failed to open socket to service: "
  -                                +se);
  -                if (retry<=0)
  +                        .println("IOException when accepting a connection from the client:
"
  +                                +exception);
  +                throw new RuntimeException(
  +                        "IOException when accepting a connection from the client: "
  +                                +exception);
  +            }
  +
  +            if (clientSocket!=null)
  +            {
  +                // Wait until we have received our first bytes from the
  +                // client before we create the connection to the service.
  +                TestClientThread connectionToServer=null;
  +                try
                   {
  +
  +                        connectionToServer=new TestClientThread(clientSocket,
  +                                serviceHostNme, servicePort);
  +                    connectionToServer.start( );
  +                }
  +                catch (StopRequestException stopRequestException)
  +                {
  +                    System.out
  +                            .println("TestClientListener got a Stop monitor message");
                       stayAlive=false;
  -                    continue;
                   }
  -                else
  +                catch (ConnectException connectException)
  +                {
  +                    // OK, well for whatever reasons the socket is closed so go
  +                    // around and try and listen again !
  +                    System.err
  +                            .println("Connection exception when reading in bytes from the
client : "
  +                                    +connectException);
  +                }
  +                catch (IOException exception)
                   {
  -                    // go to sleep
  -                    System.err.println("Going to sleep");
  -                    try
  -                    {
  -                        Thread.currentThread( ).sleep(2500);
  -                    }
  -                    catch(InterruptedException interruptedException)
  -                    {
  -                        // don't this is an issue?
  -                        System.out.println( "Got an interruptedxception sleeping on this
thread "+interruptedException);
  -                    }
  -                    System.err.println("Woke up ");
  +                    System.err
  +                            .println("IOException when creating the connection to the server
or getting the connection stream back to the client: "
  +                                    +exception);
  +                    throw new RuntimeException(
  +                            "IOException when creating the connection to the server or
getting the connection stream back to the client: "
  +                                    +exception);
                   }
               }
           }
  -        while (serviceSocket==null&&retry-->0);
  -        return serviceSocket;
  +        System.out.println("Stopping monitor");
  +        // We've been told to stop
  +        // cleanup - hmm, well, we haven't created a connectionToServerThread
  +        // because that's what returned the Stop exception
  +        // therefore it hasn't created a thread either so nothing to do there
  +        // Tell the Monitor to stop writing things out and to tidy itself up
  +        try
  +        {
  +            TCPMonitor.stop( );
  +        }
  +        catch (IOException exception)
  +        {
  +            System.err
  +                    .println("Caught an IOException when stopping the monitor: "
  +                            +exception);
  +        }
  +
  +        // release our server socket
  +        try
  +        {
  +            serverSocket.close( );
  +        }
  +        catch (IOException exception)
  +        {
  +            System.err.println("IOException when closing serverSocket: "
  +                    +exception);
  +        }
       }
  +
   }
   
  
  
  
  1.6       +206 -136  ws-axis/c/tests/utils/monitor/org/apache/test/TCPMonitor.java
  
  Index: TCPMonitor.java
  ===================================================================
  RCS file: /home/cvs/ws-axis/c/tests/utils/monitor/org/apache/test/TCPMonitor.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- TCPMonitor.java	19 Apr 2005 16:29:33 -0000	1.5
  +++ TCPMonitor.java	6 Jun 2005 17:07:42 -0000	1.6
  @@ -13,148 +13,218 @@
   // See the License for the specific language governing permissions and
   // limitations under the License.
   
  -
   package org.apache.test;
   
  +import java.io.BufferedWriter;
   import java.io.FileWriter;
  +import java.io.IOException;
   
   /**
  - * @author perryan
  - * This class is designed to listen on a given port and send the request received on that
  - * port to the given RequestHandler. 
  - * This class is meant to be used in a test suite scenario. where an instance of this class
  - * is created per call to a test.
  - * 
  + * @author perryan,hawkeye 
  + * This class is designed to listen on a given port and send the
  + * request received on that port to the given RequestHandler. This class
  + * is meant to be used in a test suite scenario. where an instance of
  + * this class is created per call to a test.
    */
  -public class TCPMonitor {
  +public class TCPMonitor
  +{
   
  -	private static TCPMonitor singleton = null;
  -	private static FileWriter requestFileWriter;
  -	private static FileWriter responseFileWriter;
  -	private static boolean responseFileWriterOpen = false;
  -	private static TestClientListener testClientListener = null;
  -
  -	/**
  -	 * Creates a new TCPMonitor listening on the given port for incoming requests (this is
always on localhost of course!)
  -	 * 
  -	 * @param listenerPort the port to listen for incoming requests
  -	 * @throws IOException if any issues occur listening for connections or supporting them.

  -	 */
  -	private TCPMonitor(
  -		int listenerPort,
  -		String serviceHost,
  -		int servicePort,
  -		String requestFile,
  -		String responseFile)
  -		throws Exception {
  -
  -		requestFileWriter = new FileWriter(requestFile);
  -		if(! responseFile.equals("")) {
  -			responseFileWriter = new FileWriter(responseFile);
  -			responseFileWriterOpen = true;
  -		}
  -
  -		/*
  -		 * Create a thread which listens for incoming requests
  -		 */
  -		testClientListener = new TestClientListener(listenerPort, serviceHost, servicePort);
  -		testClientListener.startListener();
  -	}
  -
  -	public static TCPMonitor getInstance() throws Exception {
  -		if(singleton == null) {
  -			throw new Exception("TCPMonitor has not been initialised.");
  -		}
  -		return singleton;
  -	}
  -
  -	public static TCPMonitor getInstance(
  -		int listenerPort,
  -		String serviceHost,
  -		int servicePort,
  -		String requestFile,
  -		String responseFile) throws Exception {
  -		if(singleton == null) {
  -			singleton = new TCPMonitor(listenerPort,serviceHost,servicePort,requestFile,responseFile);
  -		}
  -		return singleton;
  -	}
  -
  -	public static void stop() {
  -		testClientListener.stopListener();
  -		try {
  -			requestFileWriter.close();
  -			responseFileWriter.close();
  -		} catch (Exception e) {
  -		    e.printStackTrace();
  -			
  -		}
  -		singleton=null;
  -	}
  -
  -	public void writeRequest(String inputLine) {
  -		try {
  -			requestFileWriter.write(inputLine);
  -			requestFileWriter.flush();
  -		} catch (Exception e) {
  -			e.printStackTrace();
  -		}
  -	}
  -
  -	public void writeResponse(String inputLine) {
  -		try {
  -			if(responseFileWriterOpen) {
  -				responseFileWriter.write(inputLine);
  -				responseFileWriter.flush();
  -			}
  -		} catch (Exception e) {
  -			e.printStackTrace();
  -		}
  -	}
  -
  -	public static void main(String[] args) {
  -
  -		try {
  -			int listener_port = 0;
  -			int forward_port = 0;
  -			String forward_host = "";
  -			String request_file = "";
  -			String response_file = "";
  -			for (int i = 0; i < args.length; i++) {
  -				if (args[i].equals("-l")) {
  -					listener_port = Integer.parseInt(args[++i]);
  -					continue;
  -				}
  -				if (args[i].equals("-p")) {
  -					forward_port = Integer.parseInt(args[++i]);
  -					continue;
  -				}
  -				if (args[i].equals("-h")) {
  -					forward_host = new String(args[++i]);
  -					continue;
  -				}
  -				if (args[i].equals("-o")) {
  -					request_file = new String(args[++i]);
  -					continue;
  -				}
  -				if (args[i].equals("-r")) {
  -					response_file = new String(args[++i]);
  -					continue;
  -				}
  -			}
  -			if (listener_port == 0
  -				|| forward_port == 0
  -				|| forward_host.equals("")
  -				|| request_file.equals("")) {
  -				System.out.println(
  -					"usage: TCPMonitor <-l listen port> <-p forward port> <-h forward host>
<-o request output file> [-r response output file]");
  -				return;
  -			}
  -			TCPMonitor monitor =
  -				TCPMonitor.getInstance(listener_port, forward_host, forward_port, request_file, response_file);
  -		} catch (Exception exception) {
  -			exception.printStackTrace();
  -		}
  -	}
  +    private static TCPMonitor         singleton              =null;
  +    private static BufferedWriter     requestFileWriter;
  +    private static BufferedWriter     responseFileWriter;
  +    private static boolean            responseFileWriterOpen =false;
  +    private static TestClientListener testClientListener     =null;
  +
  +    
  +    /**
  +     * Creates a new TCPMonitor listening on the given port for incoming
  +     * requests (this is always on localhost of course!)
  +     * 
  +     * @param listenerPort the port to listen for incoming requests
  +     * @throws IOException if any issues occur listening for connections or
  +     *             supporting them.
  +     */
  +    private TCPMonitor(int listenerPort, String serviceHost, int servicePort,
  +            String requestFile, String responseFile) throws IOException
  +    {
  +      try
  +      {
  +          requestFileWriter=new BufferedWriter(new FileWriter(requestFile));
  +      }
  +      catch (IOException exception)
  +      {
  +          System.err
  +                  .println("IOEXCeption when creating filewriter to requestfile: "
  +                          +exception);
  +          throw exception;
  +      }
  +      if (!responseFile.equals(""))
  +      {
  +          try
  +          {
  +              responseFileWriter=new BufferedWriter(new FileWriter(
  +                      responseFile));
  +          }
  +          catch (IOException exception)
  +          {
  +              System.err
  +                      .println("IOException when creating writer to response file: "
  +                              +exception);
  +              throw exception;
  +          }
  +          responseFileWriterOpen=true;
  +      }
  +        /*
  +         * Create a thread which listens for incoming requests
  +         */
  +        testClientListener=new TestClientListener(listenerPort, serviceHost,
  +                servicePort);
  +        Thread testClientListenerThread=new Thread(testClientListener);
  +        testClientListenerThread.start( );
  +    }
  +
  +
  +    public static TCPMonitor getInstance( )
  +    {
  +        if (singleton==null)
  +        {
  +            throw new RuntimeException("TCPMonitor has not been initialised.");
  +        }
  +        return singleton;
  +    }
  +
  +    public static TCPMonitor getInstance(int listenerPort, String serviceHost,
  +            int servicePort, String requestFile, String responseFile)
  +            throws IOException
  +    {
  +        if (singleton==null)
  +        {
  +            singleton=new TCPMonitor(listenerPort, serviceHost, servicePort,
  +                    requestFile, responseFile);
  +        }
  +        return singleton;
  +    }
  +    
  +    
  +
  +    /**
  +     * We've been told to stop by an incoming Stop request so clean up.
  +     */
  +    public static void stop( ) throws IOException
  +    {
  +        // close() should flush() the streams but let's just be sure !
  +        System.out.println( "TCPMonitor#stop(): Flushing and closing the output files");
  +        IOException exception=null;
  +        try
  +        {
  +            requestFileWriter.flush( );
  +            requestFileWriter.close( );
  +
  +            responseFileWriter.flush( );
  +            responseFileWriter.close( );
  +        }
  +        catch (IOException ioException)
  +        {
  +            exception=ioException;
  +        }
  +        finally
  +        {
  +            singleton=null;
  +        }
  +        if (exception!=null)
  +        {
  +            throw exception;
  +        }
  +    }
  +
  +    public void writeRequest(char[] buffer, int howManyChars)
  +    {
  +        try
  +        {
  +            requestFileWriter.write(buffer, 0, howManyChars);
  +        }
  +        catch (IOException e)
  +        {
  +            e.printStackTrace( );
  +        }
  +    }
  +
  +    public void writeResponse(char[] buffer, int howManyChars)
  +    {
  +        try
  +        {
  +            if (responseFileWriterOpen)
  +            {
  +                responseFileWriter.write(buffer, 0, howManyChars);
  +            }
  +        }
  +        catch (IOException e)
  +        {
  +            e.printStackTrace( );
  +        }
  +    }
  +    
  +    public static void main(String[] args)
  +    {
  +
  +        try
  +        {
  +            int listener_port=0;
  +            int forward_port=0;
  +            String forward_host="";
  +            String request_file="";
  +            String response_file="";
  +            String serverResponse_file = null;
  +            for(int i=0; i<args.length; i++)
  +            {
  +                if (args[i].equalsIgnoreCase("-l"))
  +                {
  +                    listener_port=Integer.parseInt(args[++i]);
  +                    System.out.println( "TCPMonitor Listening on port "+listener_port);
  +                    continue;
  +                }
  +                if (args[i].equalsIgnoreCase("-p"))
  +                {
  +                    forward_port=Integer.parseInt(args[++i]);
  +                    continue;
  +                }
  +                if (args[i].equalsIgnoreCase("-h"))
  +                {
  +                    forward_host=new String(args[++i]);
  +                    continue;
  +                }
  +                if (args[i].equalsIgnoreCase("-o"))
  +                {
  +                    request_file=new String(args[++i]);
  +                    continue;
  +                }
  +                if (args[i].equalsIgnoreCase("-r"))
  +                {
  +                    response_file=new String(args[++i]);
  +                    continue;
  +                }
  +                if (args[i].equalsIgnoreCase("-s"))
  +                {
  +                    serverResponse_file=new String(args[++i]);
  +                    continue;
  +                }
  +            }
  +            if (listener_port==0||forward_port==0||forward_host.equals("")
  +                    ||request_file.equals(""))
  +            {
  +                System.out
  +                        .println("usage: TCPMonitor <-l listen port> <-p forward
port> <-h forward host> <-o request output file> [-r response output file]");
  +                return;
  +            }
  +            TCPMonitor monitor=TCPMonitor.getInstance(listener_port,
  +                    forward_host, forward_port, request_file, response_file);
  +        }
  +        catch (Throwable exception)
  +        {
  +            exception.printStackTrace( );
  +        }
  +    }
  +    
  +    
   }
   
  
  
  
  1.5       +181 -110  ws-axis/c/tests/utils/monitor/org/apache/test/TestClientThread.java
  
  Index: TestClientThread.java
  ===================================================================
  RCS file: /home/cvs/ws-axis/c/tests/utils/monitor/org/apache/test/TestClientThread.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- TestClientThread.java	19 Apr 2005 16:29:33 -0000	1.4
  +++ TestClientThread.java	6 Jun 2005 17:07:42 -0000	1.5
  @@ -18,55 +18,118 @@
   import java.io.*;
   import java.net.*;
   
  -/**
  - * TestClientThread is a child thread of TestClientListener and handles all
  - * communication between the original requestor and the TCPMonitor class.
  - * 
  - * @author Andrew Perry
  - * @since 1.0
  - * @see TestClientListener
  - */
  -
   public class TestClientThread extends Thread
   {
  +    private boolean          continueToRun                 =true;
  +    // the responder back to the client
  +    private ClientReturner   clientReturner                =null;
  +
  +    // I didn't want to make this global but it has to be for the constructor
  +    // pattern to work :-(
  +    private int              bytesRead                     =0;
  +    private static final int READ_BUFFER_SIZE              =10000;                    
// 4096=4k
  +    private char[]           readBuffer                    =new char[READ_BUFFER_SIZE];
  +
  +    // the request from the client 
  +    private BufferedReader   clientRequestStream           =null;
  +    // the connection to the server where we forwaard the clients request to.
  +    private BufferedWriter   streamToServer                =null;
   
  -    private Socket          clientSocket     =null;
  -    private Socket          serviceSocket    =null;
  -    private int             mode             =0;
  -    private int             clientPort       =0;
  -    boolean         continueToRun    =true;
  -    private int             totalBytesRead   =0;
  -
  -    public static final int CAPTURE_REQUEST  =1;
  -    public static final int CAPTURE_RESPONSE =2;
  +    // How many times to try to connect to the server before giving in
  +    private static final int CREATE_SOCKET_TO_SERVER_RETRY =5;
   
       /**
  -     * Class constructor with the client socket used to communitate with the
  -     * client.
  +     * Class constructor with the client socket used to communicate with the
  +     * client. This is quite a powerful constructor it actually reads in bytes
  +     * from the client socket to work out whether it should stay alive or not if
  +     * not then it throws an exception
        * 
        * @param socket reference to the socket connected to the client
  +     * @exception StopRequestException if a stoprequest is received from the
  +     *                client
  +     * @exception ConnectException if the first read off the wire gave us -1
  +     *                i.e. the stream from the client is closed
        */
  -    public TestClientThread(Socket clientSocket, Socket serviceSocket, int mode)
  +    public TestClientThread(Socket clientSocket, String serviceHostName,
  +            int servicePort) throws StopRequestException , IOException ,
  +            ConnectException
       {
  -        this.clientSocket=clientSocket;
  -        this.serviceSocket=serviceSocket;
  -        this.mode=mode;
  +        //        System.out.println( "TestClientThread(3): entry");
  +        IsStopMessage(clientSocket);
  +        Socket serviceSocket=createSocketToServer(serviceHostName, servicePort);
  +        writeToServer(readBuffer, bytesRead);
  +
  +        // OK, now we've done that we can create the new thread to stream
  +        // the result back to the client
  +        clientReturner=new ClientReturner(clientSocket, serviceSocket);
  +        clientReturner.start( );
  +
       }
   
  -    public void cease( )
  +    private void IsStopMessage(Socket clientSocket) throws IOException,
  +            StopRequestException
       {
  -        // we only cease if we have are capturing the request from the client
  -        // if we are capturing the request from the server, and we have got some already
  -        // then we must continue to capture the request and end nicely
  -        if(mode == CAPTURE_REQUEST)
  +        // Get the input stream from the client
  +        clientRequestStream=new BufferedReader(new InputStreamReader(
  +                clientSocket.getInputStream( )));
  +
  +        // Read in the first few bytes to ensure that we are not being told to
  +        // stop
  +        try
  +        {
  +            bytesRead=clientRequestStream.read(readBuffer, 0,
  +                    StopTCPMonitor.STOPTCPMON.length( ));
  +        }
  +        catch (ConnectException connectException)
  +        {
  +            // did we manage to read any bytes in?
  +            if (bytesRead>0)
  +            {
  +                // Well we did !
  +                System.err
  +                        .println("Got a connectException when reading in the first few
bytes from the stream");
  +                System.err
  +                        .println("Read in some bytes but not enough to work out whether
we should stop or not");
  +                System.err
  +                        .println("Highly unlikely this is good so we'll stop !");
  +                throw connectException;
  +            }
  +            else
  +            {
  +                System.err
  +                        .println("Read in zero bytes before the client shut the connection");
  +                System.err.println("Continuing to read in future requests");
  +            }
  +        }
  +        catch (IOException exception)
  +        {
  +            System.err
  +                    .println("IOException when reading the clients initial request: "
  +                            +exception);
  +        }
  +        if (bytesRead!=-1)
           {
  -            continueToRun=false;
  -//            System.out.println( "been told to cease");
  +            String inputLine=new String(readBuffer, 0, bytesRead);
  +            if (inputLine.startsWith(StopTCPMonitor.STOPTCPMON))
  +            {
  +                clientRequestStream=null;
  +                throw new StopRequestException(
  +                        "Received a stop monitor message");
  +            }
  +            else
  +            {
  +                // now put the line into the request file for later processing
  +                TCPMonitor.getInstance( ).writeRequest(readBuffer, bytesRead);
  +            }
           }
           else
           {
  -//            System.out.println( "been told to cease but ignoring because I haven't finished");
  +            // looks like they closed the connection so throw an exception to
  +            // say we have closed
  +            throw new ConnectException(
  +                    "Connection closed when reading first few bytes of client's request");
           }
  +
       }
   
       /**
  @@ -81,105 +144,113 @@
        */
       public void run( )
       {
  -        BufferedWriter dos=null;
  -        BufferedReader dis=null;
  -        String strMode="unknown";
  -        int readReturn=0;
  -
           try
           {
  -            char[] buffer=new char[4096]; // 4K buffer
  +            while (continueToRun
  +                    &&(bytesRead=clientRequestStream.read(readBuffer, 0,
  +                            READ_BUFFER_SIZE))!=-1)
  +            {
  +                //                System.out.println( "About to write some bytes to the
  +                // server");
  +                writeToServer(readBuffer, bytesRead);
  +                System.out.println("Wrote some bytes to the server: "
  +                        +new String(readBuffer, 0, bytesRead));
  +
  +                TCPMonitor.getInstance( ).writeRequest(readBuffer, bytesRead);
  +            }
  +            // so we've either got continueToRun=false or read =-1;
  +            //            System.out.println( "TestClientThread#run(): TestClientThread
  +            // bytesRead = "+bytesRead);
  +            //            System.out.println( "TestClientThread#run(): continueToRun =
  +            // "+continueToRun);
  +        }
  +        catch (SocketException socketException)
  +        {
  +            System.err
  +                    .println("TestClientThread#run(): SocketException when reading client
request:");
  +            socketException.printStackTrace(System.err);
  +        }
  +        catch (IOException exception)
  +        {
  +            System.err
  +                    .println("TestClientThread#run(): IOException when reading clients
request: "
  +                            +exception);
  +            throw new RuntimeException(
  +                    "TestClientThread#run(): IOException when reading clients request:
"
  +                            +exception);
  +        }
  +
  +        // need to ensure we close down the clientFileReturner we created for
  +        // this connection
  +        clientReturner.continueToRun=false;
  +
  +        //        System.out.println( "TestClientThread#run(): exit");
  +    }
   
  -            if (mode==CAPTURE_REQUEST)
  +    public Socket createSocketToServer(String serviceHostName, int servicePort)
  +            throws IOException
  +    {
  +        Socket serviceSocket=null;
  +        int retry=CREATE_SOCKET_TO_SERVER_RETRY;
  +        do
  +        {
  +            try
               {
  -                strMode="REQUEST - ";
  -                dos=new BufferedWriter(new OutputStreamWriter(serviceSocket
  -                        .getOutputStream( )));
  -                dis=new BufferedReader(new InputStreamReader(clientSocket
  -                        .getInputStream( )));
  +                serviceSocket=new Socket(serviceHostName, servicePort);
               }
  -            else
  -                if (mode==CAPTURE_RESPONSE)
  -                {
  -                    strMode="RESPONSE - ";
  -                    dos=new BufferedWriter(new OutputStreamWriter(clientSocket
  -                            .getOutputStream( )));
  -                    dis=new BufferedReader(new InputStreamReader(serviceSocket
  -                            .getInputStream( )));
  -                }
  -            while (continueToRun && (readReturn=dis.read(buffer, 0, 4096))!=-1)
  +            catch (UnknownHostException unknownHostException)
  +            {
  +                // oh dear !
  +                throw unknownHostException;
  +            }
  +            catch (Exception se)
               {
  -                totalBytesRead+=readReturn;
  -                String inputLine=new String(buffer, 0, readReturn);
  -                try
  +                System.err.println("Failed to open socket to service: "+se);
  +                if (retry>0)
                   {
  -                    if (inputLine.startsWith(StopTCPMonitor.STOPTCPMON))
  +                    // go to sleep
  +                    System.err.println("Going to sleep before retrying");
  +                    try
                       {
  -                        continueToRun=false;
  -                        TCPMonitor.getInstance( ).stop( );
  +                        Thread.currentThread( ).sleep(2500);
                       }
  -                    else
  +                    catch (InterruptedException interruptedException)
                       {
  -                        if (mode==CAPTURE_REQUEST)
  -                        {
  -                            TCPMonitor.getInstance( ).writeRequest(inputLine);
  -                        }
  -                        else
  -                        {
  -                            if (mode==CAPTURE_RESPONSE)
  -                        {
  -                                TCPMonitor.getInstance( ).writeResponse(inputLine);
  -                        	}
  -                        }
  +                        // don't know if this is an issue?
  +                        System.out
  +                                .println("Got an interruptedxception sleeping on this thread
"
  +                                        +interruptedException);
                       }
  -                }
  -                catch (Exception exception)
  -                {
  -                    exception.printStackTrace();
  -                }
  -                if(continueToRun)
  -                {
  -                    dos.write(inputLine);
  -                    dos.flush( );
  +                    System.err.println("Woke up ");
                   }
               }
           }
  -        catch (EOFException eof)
  +        while (serviceSocket==null&&retry-->0);
  +
  +        try
           {
  -            eof.printStackTrace( );
  +            streamToServer=new BufferedWriter(new OutputStreamWriter(
  +                    serviceSocket.getOutputStream( )));
           }
  -        catch (IOException e)
  +        catch (IOException exception)
           {
  -            // ignore these becuase we haven't quite managed to make this system as nice

  -            // as we would like so we get these (when it's working correctly) when
  -            // the readers and writers have been closed by the TCPMonitor instance
  -            // this is fine because it's when the system is shuuting down and we don't
need them
  -        }
  -        finally
  -        {
  -            try
  -            {
  -                dis.close( );
  -                dos.close( );
  -            }
  -            catch (Exception e)
  -            {
  -                e.printStackTrace( );
  -            }
  +            System.err
  +                    .println("IOEXception when getting the writer to the service "
  +                            +exception);
  +            throw exception;
           }
  +
  +        return serviceSocket;
       }
   
  -    /**
  -     * This method tells the starting thread whether this objec has started to
  -     * read in bytes yet. If it has then the requestor of this method can tell
  -     * how many bytes have been received and thus see whether the bytes are a
  -     * message to stop or not
  -     * 
  -     * @return the number of bytes received by this reader
  -     */
  -    public int getBytes( )
  +    private void writeToServer(char[] request, int bytesToWrite)
  +            throws IOException
       {
  -        return totalBytesRead;
  +        //System.out.println( "writeToServer: "+new String(request, 0,
  +        // bytesToWrite));
  +        streamToServer.write(request, 0, bytesToWrite);
  +        streamToServer.flush( );
       }
  +
   }
   
  
  
  
  1.1                  ws-axis/c/tests/utils/monitor/org/apache/test/ClientReturner.java
  
  Index: ClientReturner.java
  ===================================================================
  // Copyright 2003-2004 The Apache Software Foundation.
  // (c) Copyright IBM Corp. 2004, 2005 All Rights Reserved
  // 
  // Licensed under the Apache License, Version 2.0 (the "License");
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  // 
  //        http://www.apache.org/licenses/LICENSE-2.0
  // 
  // Unless required by applicable law or agreed to in writing, software
  // distributed under the License is distributed on an "AS IS" BASIS,
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  // See the License for the specific language governing permissions and
  // limitations under the License.
  
  package org.apache.test;
  
  import java.io.*;
  import java.net.*;
  
  
  /**
   * TestClientThread is a child thread of TestClientListener and handles all
   * communication between the original requestor and the TCPMonitor class.
   * 
   * @author Andrew Perry
   * @since 1.0
   * @see TestClientListener
   */
  
  public class ClientReturner extends Thread
  {
      boolean                 continueToRun    =true;
      private static int number=0;
      
  //    private char[] readBuffer=new char[READ_BUFFER_SIZE];
      
      // the response from the server
      protected BufferedReader serverResponseStream = null;
      
      // the writer back to the client
      protected BufferedWriter streamToClient=null;
  
      private static final int READ_BUFFER_SIZE=4091; // 4k
      
      
      /**
       * convenience constructor for ClientFileReturner
       *
       */
      
      protected ClientReturner()
      {
          number++;
      }
  
      protected ClientReturner(Socket clientSocket)throws IOException
      {
          number++;
          streamToClient = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
      }
      /**
       * 
       * @param clientSocket the socket to the client
       * @param serviceSocket the socket to the server (service)
       * @throws IOException
       */
      public ClientReturner(Socket clientSocket, Socket serviceSocket) throws IOException
      {
          this(clientSocket);
  //        System.out.println( "ClientReturner(): entry");
          // create the reader from the server
          serverResponseStream = new BufferedReader(new InputStreamReader(serviceSocket.getInputStream()));
          
      }
  
  
      /**
       * Reads the request from the client and if of a valid format will extract
       * the test ID and required data and call the TestSingleton class to set or
       * get the information. It is assumed that all requests are UTF Strings.
       * <p>
       * If the incoming request does not contain a test ID, or is not of a
       * recognised format then the socket will be closed and this object will
       * finish.
       * </p>
       */
      public void run( )
      {
  //        System.out.println( "ClientReturner#run("+number+"): entry");
          int bytesRead=0;
          char[] readBuffer= new char[READ_BUFFER_SIZE];
  
              while (continueToRun)
              {
                  try
                  {
                  bytesRead = serverResponseStream.read(readBuffer, 0, READ_BUFFER_SIZE);
  //                System.out.println( "Clientreturner got some bytes from the server "+bytesRead);
                  }
                  catch(IOException exception)
                  {
                      System.err.println( "IOException when reading in response from server
");
                      exception.printStackTrace(System.err);
                  }
                  if(bytesRead!=-1)
                  {
  //                    System.out.println( "ClientReturner#run("+number+"): Writing to client:
"+new String(readBuffer, 0, bytesRead));
                      try
                      {
                      streamToClient.write(readBuffer, 0, bytesRead);
                      streamToClient.flush();
                      }
                      catch(IOException exception)
                      {
                          System.err.println( "IOException when writing server response back
to client");
                          exception.printStackTrace(System.err);
                          
                      }
                      //System.out.println( "ClientReturner#run(): flushed");
                      TCPMonitor.getInstance( ).writeResponse(readBuffer, bytesRead);
  //                    System.out.println( "About to go around again");
                  }
                  else
                  {
  //                    System.out.println( "ClientFileReturner#run(): bytesRead==-1 "+continueToRun);
                      
                      //continueToRun=false;
                  }
              }
          }
  //        System.out.println( "ClientReturner#run(): exit");
  
  }
  
  
  
  
  1.1                  ws-axis/c/tests/utils/monitor/org/apache/test/StopRequestException.java
  
  Index: StopRequestException.java
  ===================================================================
  /*
   * Copyright 2003-2004 The Apache Software Foundation. 
   * (c) Copyright IBM Corp. 2005
   *  
   * All Rights Reserved Licensed under the Apache License,
   * Version 2.0 (the "License"); you may not use this file except in compliance
   * with the License. You may obtain a copy of the License at
   * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
   * or agreed to in writing, software distributed under the License is
   * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   * KIND, either express or implied. See the License for the specific language
   * governing permissions and limitations under the License.
   */
  
  package org.apache.test;
  
  /**
   * @author hawkeye
   * This class is an exception that is used to denote a stop request happening and informing
the hierarchy to stop processing. 
   */
  public class StopRequestException extends Exception
  {
      public StopRequestException(String exceptionMessage)
      {
          super(exceptionMessage);
      }
  
  }
  
  
  

Mime
View raw message