com.ccg.net
Class LineReceiver

java.lang.Object
  extended by java.lang.Thread
      extended by com.ccg.net.LineReceiver
All Implemented Interfaces:
Runnable

public abstract class LineReceiver
extends Thread

Base class for implementing ASCII text clients.

This class is particularily handy if you have a server process which periodically broadcasts ASCII information. The easiest way to see how to use this class is to look at a example program. This example requires two parts. Part one is a simple TCP server that periodically broadcast information at port 6666 on the 'localhost'. You can create such a server by compiling the TimeServer.java example program. After compiling it, you can start the server with the following command line:

 java TimeServer
 

You can verify that the server is working by using the following telnet command:

 telnet localhost 6666
 

Now,

import com.ccg.net.*;

public class MyReceiver extends LineReceiver {

  public void lineReceived(String text) {
                                // OK, this is a trivial
                                // implementation - we just dump what
                                // we get to the standard system
                                // output
    System.out.println(text);
  }

  public static void main(String[] args) {
                                // construct my client object
    MyReceiver r = new MyReceiver();

                                // set where its source of information
    String src = "tcp://localhost:6666";
    if (args.length == 1) src = args[0];
    r.setSource(src);

    r.start();                  // and start it up
  }
}
 

Save the above example program to a file called "MyReceiver.java", then compile and run the program. You should notice the following:

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

Nested Class Summary
 
Nested classes/interfaces inherited from class java.lang.Thread
Thread.State, Thread.UncaughtExceptionHandler
 
Field Summary
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
LineReceiver()
          Does the minimal initialization for the object.
 
Method Summary
 int getCharsReceived()
          Get the number of ASCII characters received from the source.
 int getConnectDelayMillis()
          Get the number of milliseconds to delay between connection attempts.
 int getFailedConnects()
          Get the number of times a connection attempt failed.
 int getLinesReceived()
          Get the number of ASCII text lines received from the source.
 boolean getRunTimeSpan(TimeSpan ts)
          Get the thread run time.
 String getSource()
          Get the source of the network status to read information from.
 int getSuccessfulConnects()
          Get the number of times a successful connection has been made.
 boolean isConnected()
          Is the connection to the source UP?
protected  void layoutField(StringBuffer sb, String inFront, String label, Object val)
          A helper method to format output fields.
abstract  void lineReceived(String text)
          What to do with each line received from the server.
protected  void logError(String message, Throwable e)
          Log that a error condition has occurred.
 void print(PrintWriter pw, String withEach)
          A detailed "dump" of information about the state of the object.
 void run()
          Attempts to connect and receive lines of text from the source.
 void setConnectDelayMillis(int val)
          Set the number of milliseconds to delay between connection attempts.
protected  void setConnected(boolean val)
          This method is invoked whenever the state of the connection changes.
 void setSource(String val)
          Set the source of the network status to read information from.
 void shutdown()
          Try to gracefully stop the background thread.
 void zero()
          Zero's out the internal counts/status information of the object.
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

LineReceiver

public LineReceiver()
Does the minimal initialization for the object.

This constructor does the minimal initialization of the object. After construction you will want to do the following (at a minimum):

Since:
1.0
See Also:
setSource(java.lang.String)
Method Detail

lineReceived

public abstract void lineReceived(String text)
What to do with each line received from the server.

This is the method which ALL derived classes MUST implement. This method will be invoked each time a new line of text is received from the source/server. What you do with the text received depends upon your implementation.

Parameters:
text - A single line of ASCII text received from the server. Should never be null, but may be 0 bytes in length
Since:
1.0

getRunTimeSpan

public boolean getRunTimeSpan(TimeSpan ts)
Get the thread run time.

This method is used to determine how long the background thread has been running.

Parameters:
ts - Where to store the time span information
Returns:
true if we have ever started running and can return time span of current/last run, false if never started.
Since:
1.0
See Also:
TimeSpan

run

public void run()
Attempts to connect and receive lines of text from the source.

This method runs in the background (after you "start" the thread). It will attempt to connect to the server and reconnect when necessary (if you change the source or a connection is lost). When a connection is established, lines of ASCII text will be retrieved from the server and then processed by the lineReceived(java.lang.String) method which derived classes MUST implement.

Specified by:
run in interface Runnable
Overrides:
run in class Thread
Since:
1.0
See Also:
lineReceived(java.lang.String)

setConnected

protected void setConnected(boolean val)
This method is invoked whenever the state of the connection changes.

As the run() method executes, it may need to open and/or close its connection to the source (as errors occur). This method will be invoked each time this happens.

If a derived class wants to detect when these events occur, it may override this method (in the future, the capability to register event listeners with this class may be added).

Parameters:
val - true if connection has just been made, false if a connection has just been lost.
See Also:
isConnected()

isConnected

public final boolean isConnected()
Is the connection to the source UP?

Returns:
true if we are currently connected to the source.
See Also:
setConnected(boolean)

setConnectDelayMillis

public void setConnectDelayMillis(int val)
Set the number of milliseconds to delay between connection attempts.

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

getConnectDelayMillis

public int getConnectDelayMillis()
Get the number of milliseconds to delay between connection attempts.

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

zero

public void zero()
Zero's out the internal counts/status information of the object.

This method can be used to clear all of the internal counts and status information which the object has been tracking. It should be overridden by derived classes to extend the behaviour (to also "zero" out their respective information).

Since:
1.0
See Also:
run()

getLinesReceived

public int getLinesReceived()
Get the number of ASCII text lines received from the source.

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

getCharsReceived

public int getCharsReceived()
Get the number of ASCII characters received from the source.

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

getSuccessfulConnects

public int getSuccessfulConnects()
Get the number of times a successful connection has been made.

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

getFailedConnects

public int getFailedConnects()
Get the number of times a connection attempt failed.

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

setSource

public void setSource(String val)
Set the source of the network status to read information from.

This method is used to specify a new source for the server. Typically it is in the form of "tcp://[HOST:]PORT/OPTIONS", but any string which can be converted to a InputStream by Utility.getInputStream(java.lang.String) is permitted.

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

getSource

public String getSource()
Get the source of the network status to read information from.

Returns:
Current String value assigned.
See Also:
setSource(java.lang.String)

logError

protected void logError(String message,
                        Throwable e)
Log that a error condition has occurred.

When things go wrong in the background thread, this method is used to log the problems which occur.

Parameters:
message - Some text describing what error occurred
e - The exception that is associated with the error
Since:
1.0

shutdown

public void shutdown()
Try to gracefully stop the background thread.

This method is intended to gracefully shutdown the background thread which is running and connecting to the server (or reading information from the server).

Since:
1.0

print

public void print(PrintWriter pw,
                  String withEach)
A detailed "dump" of information about the state of the object.

This method provides diagnostic output (in a very verbose form) for the current state of the object.

Parameters:
pw - Where to print the information to
withEach - This can be used to prefix each line with some space (if you want the output indented). You can pass null if you don't need any indentation.
Since:
1.0

layoutField

protected void layoutField(StringBuffer sb,
                           String inFront,
                           String label,
                           Object val)
A helper method to format output fields.

This is a helper method which can be used by the print method when formatting a single row of output.

Parameters:
sb - A string buffer to use to build the next line of output in.
inFront - This can be used to prefix each line with some space (if you want the output indented). You can pass null if you don't need any indentation.
label - A label to precede the value (must not be null)
o - The value that goes with the label (may be null)
Since:
1.0
See Also:
print(java.io.PrintWriter, java.lang.String)


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