com.ccg.net.tcp
Class SimpleExpect

java.lang.Object
  extended by com.ccg.net.tcp.SimpleExpect
All Implemented Interfaces:
Runnable

public class SimpleExpect
extends Object
implements Runnable

A very simple implementation of a "send/expect" checking object.

This object allows one to do a simple check on a server. It allows one to specify the following:

Take a look at the following example program which uses this class:

import com.ccg.net.tcp.*;
import com.ccg.util.*;

import java.io.*;
import java.net.*;

public class Foo {

  static public void main(String args[]) {
    try {
      if (2 > args.length) {
        System.err.println("usage: java Foo HOST PORT "+
                           " [EXPECT [SEND] [CAPLEN]]");
        System.exit(1);
      }

                                // setup our simple expect object
      SimpleExpect se = new SimpleExpect();
      se.setInetAddress(InetAddress.getByName(args[0]));
      se.setPort(Integer.parseInt(args[1]));
      if (args.length > 2) se.setExpectBytes(args[2].getBytes());
      if (args.length > 3) se.setSendBytes(args[3].getBytes());
      if (args.length > 4) se.setCaptureMax(Integer.parseInt(args[4]));

      se.run();                 // try to verify

      PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));

                                // dump results about verification
      pw.println("                     isOK():"+
                 se.isOK());
      pw.println("           getInetAddress():"+
                 se.getInetAddress());

      pw.println("                  getPort():"+
                 se.getPort());

      pw.println("            getWaitMillis():"+
                 se.getWaitMillis());

      pw.println("             getRunMillis():"+
                 se.getRunMillis());

      pw.println("    getTotalBytesReceived():"+
                 se.getTotalBytesReceived());

      pw.println("getPrecedingBytesReceived():"+
                 se.getPrecedingBytesReceived());

      Exception e = se.getLastException();
      if (e != null) {
        pw.println("         getLastException():"+e.getMessage());
      }

                                // if we captured data, do a hex dump
                                // of what we got
      byte[] capBuf = se.getCaptured();
      if (capBuf != null) {
        HexDump hd = new HexDump();
        pw.println();
        pw.println("Captured Data:");
        hd.formatBytes(pw,capBuf,0,capBuf.length);
        hd.flush(pw);
      }
                                // otherwise, just flush buffer
      else pw.flush();


    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
 

The above program demonstrates how one might typically use this class. You should be able to cut/paste the above to a file (name it "Foo.java"), compiler and run the example shown.

Here are some examples of how you could use the above program:

#
# See if the "my.yahoo.com" web site is accepting connections
#
java Foo my.yahoo.com 80

#
# See if the host "rice" is running a OpenSSH server on port 22
#

java Foo rice 22 OpenSSH

#
# Try connecting port to port 1494 on mole - send "Fred" wait for "ICA"
#

java Foo mole 1494 ICA Fred

 

Since:
1.0
Version:
$Revision: 1.4 $
Author:
$Author: pkb $

Constructor Summary
SimpleExpect()
          Default object constructor.
 
Method Summary
 Socket createSocket()
          Create a Socket used for communications.
 byte[] getCaptured()
          Fetch the contents of the "capture buffer".
 int getCaptureMax()
          Get the size of capture buffer which holds data read after run().
 byte[] getExpectBytes()
          Get the bytes we expect to receive from the host.
 InetAddress getInetAddress()
          Get the IP address to connect to
 Exception getLastException()
          Get the Exception encountered during the last run.
 InetAddress getLocalInetAddress()
          Get the local InetAddress to bind to.
 int getLocalPort()
          Get the local port to bind to.
 int getPort()
          Get the TCP port to connect to
 int getPrecedingBytesReceived()
          Get the number of bytes which preceded the "matched" expect sequence.
 int getRunMillis()
          Get the number of milliseconds we actually waited.
 byte[] getSendBytes()
          Get the initial array of bytes that are to be written to the socket when opened.
 int getTotalBytesReceived()
          Get the total number of bytes we received during the run.
 int getWaitMillis()
          Get the number of milliseconds to wait for verification.
 boolean isOK()
          Is did the last run successfully verify the connection set?
 void run()
          Try to establish and verify the connection.
 void setCaptureMax(int maxLen)
          Set the capture buffer which holds data read after run().
 void setExpectBytes(byte[] val)
          Set the bytes we expect to receive from the host.
 void setInetAddress(InetAddress val)
          Set the IP address to connect to.
 void setLocalInetAddress(InetAddress val)
          Set the local InetAddress to bind to.
 void setLocalPort(int val)
          Set the local port to bind to.
 void setPort(int val)
          Set the TCP port to connect to.
 void setSendBytes(byte[] val)
          Set the initial array of bytes that are to be written to the socket when opened.
 void setWaitMillis(int val)
          Set the number of milliseconds to wait for verification.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SimpleExpect

public SimpleExpect()
Default object constructor.

After creating a SimpleExpect object in this fashion, at a minimum you will need to specify a remote host and remote port before you can invoke the run() method to check the remote machine.

Since:
1.0
Method Detail

run

public void run()
Try to establish and verify the connection.

Use this method to:

After this method completes, you can use the isOK() method to determine if we successfully verified the server to be functional. The methods getRunMillis(), getTotalBytesReceived(), getPrecedingBytesReceived, and getLastException() can provide more detailed information about what occurred during the verification process.

Specified by:
run in interface Runnable
Since:
1.0
See Also:
isOK(), getLastException()

getCaptureMax

public int getCaptureMax()
Get the size of capture buffer which holds data read after run().

This method returns the maximum capacity of the "capture buffer". This is not the same as the number of bytes contained in the "capture buffer".

Returns:
Size of the capture buffer. A value of 0 indicates that the capture buffer is not in affect.
See Also:
getCaptured()

setCaptureMax

public void setCaptureMax(int maxLen)
Set the capture buffer which holds data read after run().

Use this method to enable/disable the "capture buffer" for the object. If you pass a value larger than 0, then that many bytes will be allocated to "capture" the data received from the server as we looke for the expect sequence of bytes. You can disable the capture buffer by specifying a value of 0.

Since the capture buffer will also contain the matched sequence of bytes, there isn't much point to enable it unless you specify a size larger than your expect sequence.

If the server returns more bytes than the limit you specify, then capture buffer will wrap to hold the last bytes (most recent) received from the server.

For example, lets assume you specify 250 bytes as the maximum size for the capture buffer and set a expect sequence which is 50 bytes long. If the expect sequence is matched by the run() method after receiving 2050 bytes from the server, then the capture buffer will only have the last 250 bytes available (and 50 of those will be the matched expect sequence)..

Parameters:
maxLen - The maximum number of bytes you'd like to have the run() method capture for you.
See Also:
getCaptured()

getCaptured

public byte[] getCaptured()
Fetch the contents of the "capture buffer".

This method allows you to fetch the contents of the "capture buffer". This buffer contains the data received the last time the run() method was invoked. If more data was received than the "capture buffer" could hold (when getTotalBytesReceived() > getCaptureMax()), only the most recent bytes (up to getCaptureMax()) will be returned.

Returns:
Byte array to of data captured by the run() method. Will return null if no capture buffer was set. The byte array returned is newly allocated and filled (you can modify it to your hearts content without affecting the internal "capture buffer" of this object).
See Also:
setCaptureMax(int), getCaptureMax()

createSocket

public Socket createSocket()
                    throws IOException
Create a Socket used for communications.

This method will create a new Socket which can be used to communicate with the current end-point assigned to the object.

Returns:
Current Socket value assigned.
Throws:
IOException
See Also:
setInetAddress(java.net.InetAddress), setPort(int)

setInetAddress

public void setInetAddress(InetAddress val)
Set the IP address to connect to.

Parameters:
val - New InetAddress value to assign.
See Also:
getInetAddress()

getInetAddress

public InetAddress getInetAddress()
Get the IP address to connect to

Returns:
Current InetAddress value assigned.
See Also:
setInetAddress(java.net.InetAddress)

setPort

public void setPort(int val)
Set the TCP port to connect to.

Parameters:
val - New value to assign.
See Also:
getPort()

getPort

public int getPort()
Get the TCP port to connect to

Returns:
Current value assigned.
See Also:
setPort(int)

setLocalInetAddress

public void setLocalInetAddress(InetAddress val)
Set the local InetAddress to bind to.

Typically one doesn't need to specify this value as the default will be sufficient.

Parameters:
val - New InetAddress value to assign.
See Also:
getLocalInetAddress()

getLocalInetAddress

public InetAddress getLocalInetAddress()
Get the local InetAddress to bind to.

Returns:
Current InetAddress value assigned.
See Also:
setLocalInetAddress(java.net.InetAddress)

setLocalPort

public void setLocalPort(int val)
Set the local port to bind to.

If your server needs to see you coming from a specific port on YOUR machine, then you can use this method to specify what port you need to bind to at your local host. Typically one doesn't need to specify this.

Parameters:
val - New int value to assign.
See Also:
getLocalPort()

getLocalPort

public int getLocalPort()
Get the local port to bind to.

Returns:
Current int value assigned (will be -1 if we don't need to bind to a specific local port).
See Also:
setLocalPort(int)

setExpectBytes

public void setExpectBytes(byte[] val)
Set the bytes we expect to receive from the host.

If you specify a non-null value here, we will verify that the bytes we receive from the host contain the bytes you specify. If you pass a null value, we will not check any response from the host (we will only check that we can connect to the host).

Parameters:
val - New byte[] value to assign.
See Also:
getExpectBytes()

getExpectBytes

public byte[] getExpectBytes()
Get the bytes we expect to receive from the host.

Returns:
Current byte[] value assigned.
See Also:
setExpectBytes(byte[])

setSendBytes

public void setSendBytes(byte[] val)
Set the initial array of bytes that are to be written to the socket when opened.

If you want to send an array of bytes to the socket connection after you open the connection, use this method to pass the bytes you want to send. You can specify null (which is what the object defaults to at time of construction) to indicate that you don't need to send any bytes after the initial connection.

Parameters:
val - New byte[] value to assign.
See Also:
getSendBytes()

getSendBytes

public byte[] getSendBytes()
Get the initial array of bytes that are to be written to the socket when opened.

Returns:
Current byte[] value assigned.
See Also:
setSendBytes(byte[])

isOK

public boolean isOK()
Is did the last run successfully verify the connection set?

Use this method after invoking run to see if we were able to verify that the other end of the connection was behaving as expected.

Returns:
Current boolean value assigned.
See Also:
run()

getLastException

public Exception getLastException()
Get the Exception encountered during the last run.

Use this method after the run method completes if you want to see if any exceptions were encountered during the run. It will return 'null' if no unexpected exceptions were encountered.

Returns:
Current Exception value assigned.
See Also:
run()

getTotalBytesReceived

public int getTotalBytesReceived()
Get the total number of bytes we received during the run.

As the run method reads data from the server looking for a matching expect sequence, it keeps track of the total number of bytes received from the server. You can use this method to check the progress of the bytes received.

NOTE: The run method closes the connection once the expected sequence has been matched.

Returns:
Current int value assigned.
See Also:
getPrecedingBytesReceived()

getPrecedingBytesReceived

public int getPrecedingBytesReceived()
Get the number of bytes which preceded the "matched" expect sequence.

After the run method completes, you can use this method to determine how many bytes were received PRIOR to the matching the "expected bytes". The value returned will be 0 or higher if a match was made. It will be -1 if the "expected bytes" were not received.

Returns:
Number of bytes which preceded the "expected bytes" byte sequence (-1 if the "expected byte sequence was not received).
See Also:
getTotalBytesReceived()

setWaitMillis

public void setWaitMillis(int val)
Set the number of milliseconds to wait for verification.

Parameters:
val - New int value to assign.
See Also:
getWaitMillis()

getWaitMillis

public int getWaitMillis()
Get the number of milliseconds to wait for verification.

Returns:
Current int value assigned.
See Also:
setWaitMillis(int)

getRunMillis

public int getRunMillis()
Get the number of milliseconds we actually waited.

This method returns the total number of milliseconds which we actually waited for the run method to attempt/complete its verification process.

Returns:
Current int value assigned.
See Also:
setWaitMillis(int)


Copyright 1998-1998-2006 null. All Rights Reserved.