QJCC homepage

biz.chitec.quarterback.gjsa.server
Class ServerThreadBase

java.lang.Object
  extended bybiz.chitec.quarterback.gjsa.server.ServerThreadBase
All Implemented Interfaces:
LoggingReceiver, TransactionLoggingReceiver

public class ServerThreadBase
extends java.lang.Object
implements TransactionLoggingReceiver

Logical counterpart of a client which is connected to the server. A ServerThreadBase is assigned to exactly one client and stays alive the whole time the client communicates with the server. It holds the basic data about the client and channelizes the communication between client and server.

The ServerThreadBase does not handle actual queries. Those are passed to a ServerThreadSession which does the handling and gives further logical separation in query handling.

A ServerThreadBase is always created by a SocketLayer instance. GJSA supports two types of connections: connectionbound (which means that the socket is open for the whole livetime of the connection between client and server) or connectionless (which means that a network connection is opened each time a query-response-pair is exchanged). For connectionbound connections, SocketLayer creates directly a ServerThreadBase and links that one into the Thread currently executed. For connectionless connections, the ServerThreadBase is created and stored into a Map where it can be found easily for further requests. So, in the connectionless case, a ServerThreadBase is run for each query in a different Thread while in the connectionbound case, it always runs in the same thread.

Version:
$Id: cd49ec8461c8089a3049e5717bba46f0f3afc687 $
Author:
Dirk Hillbrecht 1997-2000, chitec/Dirk Hillbrecht 2000,2001,2002, cantamen/Dirk Hillbrecht 2003. Distributed under the terms of the GNU LGPL.
See Also:
ServerThreadHandler, ServerThreadInitiator, GJSAServer, SessionConnector

Nested Class Summary
private static class ServerThreadBase.BurstLogDataStorage
           
 
Field Summary
private  boolean authenticated
          Marker that counterside has authenticated in whatever way.
private  long authenticatedtimeout
          Idle timeouts
protected  Logger clie
          target for logging messages
protected  boolean clientaddressisreportable
          Flag whether the client is allowed to report a different client IP address.
protected  java.lang.String clienthostip
          The real client's IP address
protected  java.lang.String clienthostname
          The (DNS-)name of the real client host
protected  java.net.InetAddress clientInetAddr
          The real client's InetAddress object
protected  java.util.Map cmdlogdata
          Complete map of data for this thread base
private  java.lang.String connectionid
          Complete id for logging output
private  boolean connectionless
          Indicator whether this is a connectionless connection or not
protected static int connnr
          connection number.
private  ServerThreadSession currentsession
          The session answering the current query
protected  java.util.Map data
          Complete map of data for this thread base
 int encryptionrule
          Description of the Field
protected  boolean encryptionstatecorrect
          Description of the Field
protected static EncryptionRulesSymbols ers
          Description of the Field
private  ServerThreadSession initialsession
          The initial ServerThreadSession
private  boolean isclosed
          Flag that closing the ServerThreadBase has been finished.
private  boolean isclosing
          Flag whether this ServerThreadBase is about to be closed by a QUIT command
private  int lastencodingmode
          Encoding mode of the connection.
private  boolean lastencryptionmode
          Encryption mode of the connection.
private  long lastinteraction
          Time of last interaction from the client
private  boolean locallycontrolled
          Flag whether the thread base is controlled by local commands
private  boolean locallycontrolledsettable
          Flag whether the locallycontrolled flag may be set.
protected  Logger mess
          target for logging messages
 boolean mustencrypt
          Description of the Field
 boolean mustnotencrypt
          Description of the Field
protected  int myconnnr
          Own connection number.
 GJSAServer myserv
          pointer to the Server object that has launched this ServerThreadBase
private  ThreadInterface readerinterface
          Interface for reading from the SocketLayer.
protected  java.lang.String reportedclienthostip
          The reported client's IP address.
protected  java.lang.String reportedclienthostname
          The (DNS-)name of the client host which is reported as client by the real client.
protected  java.net.InetAddress reportedclientinetaddr
          The reported client's address as InetAddress object
protected  java.util.Map senddata
          Complete map of data for this thread base
private  int sequence
          Sequence counter for connectionless connections
private  int sessionidcounter
          Session counter to create session ids.
private  java.util.Map sessions
          Map to all sessions
private  long unauthenticatedtimeout
          Idle timeouts
private  ThreadInterface writerinterface
          Interface for writing to the SocketLayer.
 
Constructor Summary
ServerThreadBase(GJSAServer gx, int encodingmode, boolean encryptionmode, java.net.InetAddress rx, boolean clx, long uat, long ato)
          Constructor for all cases.
 
Method Summary
 boolean clientMatchesPattern(java.lang.String pattern)
          Description of the Method
 void close()
          Close the handler.
 void closeSession()
           
 ServerReply continueSyncBurst()
           
private  void doClose()
          Real closing method Works regardless of connectionless or connectionbound connection.
 void finishNewState(CommandExecutor commexec)
           
 void finishNewState(java.util.List commexecs)
           
 void finishNewState(java.util.List commexecs, java.util.List allcommexecs)
           
 void freeFloatingReply(int seq, ServerReply sr)
          writes a free floating reply.
 void freeFloatingReply(int seq, ServerReply sr, InformableSender isx)
          writes a free floating reply.
 boolean getBurstAll()
           
 boolean getBurstNext()
           
 int getBurstSize()
           
 java.lang.String getClientHostDescription()
          Returns a complete declarative description of the client's name and IP.
 java.lang.String getClientHostIP()
          Returns the IP address of the connected client.
 java.lang.String getClientHostName()
          Returns the symbolic name of the real connected client.
 java.net.InetAddress getClientInetAddr()
          Returns the InetAddress object for the currently connected client This method will also work for connectionless connect.
 java.lang.String getConnectionID()
          Returns the connection ID which contains at least the connection number.
 int getConnectionNr()
          Returns the connection number of this connection.
 java.util.Map getData()
          Return complete data set for this connection
 GJSAServer getGJSAServer()
          Gets the gJSAServer attribute of the ServerThreadBase object
 int getLastChildSessionID()
           
static int getMaxConnectionNr()
          Returns the maximum assigned connection number.
 java.lang.Object getProperty(java.lang.Object key)
           
 boolean getRemovementLogging()
          Gets the removementLogging attribute of the ServerThreadBase object
 java.lang.String getReportedClientHostDescription()
          Returns a complete declarative description of the reported client's name and IP.
 java.lang.String getReportedClientHostIP()
          Returns the IP address of the connected client.
 java.lang.String getReportedClientHostName()
          Returns the symbolic name of the real connected client.
 java.net.InetAddress getReportedClientInetAddr()
          Returns the InetAddress object for the currently connected client This method will also work for connectionless connect.
 int getSequence()
          Returns current sequence counter
 int getUniqueSessionID()
          Returns a unique session id for new sessions.
 void handleLogObject(Logger src, int nr, java.lang.Object o)
          Description of the Method
 void handleLogObject(Logger src, java.lang.Object o)
          interface method for LoggingReceiver.
 void incSequence()
          Increases the sequence counter.
 void incSequenceAndDisableLocallyControlled()
          Increases the sequence counter and disables the locally controlled-flag.
 void informConnectionListeners()
          Informs data listeners on changes if they have occured via putData() before.
 ServerReply initBurstableReply(BurstMaker bm)
           
protected  void initDataMap()
          Initializes the data map and sends through CLIE logger
private  void initEncryptionFlags(java.lang.Object o)
          Description of the Method
private  void initNameAndIP(java.net.InetAddress ix)
          Primary initialisation of client IP address.
private  void initSessions()
          initializes the session stack with initial executors
 boolean isClosing()
          returns if connection has received QUIT command and can therefore be removed.
 boolean isConnectionless()
          Returns whether this connection is connectionless
 boolean isEncryptionStateCorrect()
          Returns whether the encryption state is correct for opening a session or a new state in an existing session.
 boolean isLocallyControlled()
          Returns whether the ServerThreadBase is currently fed with server-local commands.
 boolean isTimedOut(long currenttime)
          Returns whether this connection is timed out and should be closed.
 void leaveState()
           
 void logMessage(int sessionid, java.lang.Object message)
          Logs a message of any session to the standard message logger.
 void loopSynchronous(SocketLayer sly, ServerEnvelope firstquery)
           
 boolean mayBeClosed()
          returns whether the thread base may be closed or not.
 void newState(int newstate, CommandExecutor commexec)
           
 void newState(int newstate, java.util.List commexecs)
           
 void newState(int newstate, java.util.List commexecs, java.util.List allcommexecs)
           
 int openSession()
           
 void putData(java.lang.String key, java.lang.Object value)
          Put one data element into the map, sets flag that listeners should be informed.
 java.lang.Object putProperty(java.lang.Object key, java.lang.Object value)
           
 void registerSession(ServerThreadSession sts)
          Register a session for calling
 void releaseSession(ServerThreadSession sts)
          Release a session of the register.
 java.lang.Object removeProperty(java.lang.Object key)
           
 ServerEnvelope reply(ServerEnvelope se)
          "Main" query handler.
 ServerEnvelope reply(ServerEnvelope se, boolean encrypted, int currencodingmode)
          Handle a ServerEnvelope, readjust the "encryption" setting and report the current connection encoding
 ServerReply replyOneQuery(ServerRequest sr)
          Convenience method to handle a single query
 void retractNewState()
           
 void setBurstAll(boolean bx)
           
 void setBurstNext(boolean bx)
           
 void setBurstSize(int s)
           
 void setClientAddress(java.lang.String ipaddress)
          Sets the client's address of the connection to a new value.
private  void setCurrentIdleStart()
           
 void setLocallyControlled(boolean b)
          Sets whether the ServerThreadBase is currently fed with server-local commands.
 void setTimeouts(long nto, long ato)
          Set the timeouts for the connection object
 void startClosing()
          Start closing the stuff.
 void startNewState(int newstate)
           
 java.lang.String toString()
          Description of the Method
 void turnIntoAuthenticated()
          Turns this connection into an authenticated one.
 void updateInteractionTimestamp()
          Sets timestamp of last interaction to current time
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

connnr

protected static int connnr
connection number. Incremented for every new connection


myconnnr

protected int myconnnr
Own connection number. Set during initialization


ers

protected static EncryptionRulesSymbols ers
Description of the Field


myserv

public GJSAServer myserv
pointer to the Server object that has launched this ServerThreadBase


clienthostname

protected java.lang.String clienthostname
The (DNS-)name of the real client host


clienthostip

protected java.lang.String clienthostip
The real client's IP address


clientInetAddr

protected java.net.InetAddress clientInetAddr
The real client's InetAddress object


clientaddressisreportable

protected boolean clientaddressisreportable
Flag whether the client is allowed to report a different client IP address.


reportedclienthostname

protected java.lang.String reportedclienthostname
The (DNS-)name of the client host which is reported as client by the real client.


reportedclienthostip

protected java.lang.String reportedclienthostip
The reported client's IP address.


reportedclientinetaddr

protected java.net.InetAddress reportedclientinetaddr
The reported client's address as InetAddress object


initialsession

private ServerThreadSession initialsession
The initial ServerThreadSession


mess

protected Logger mess
target for logging messages


clie

protected Logger clie
target for logging messages


encryptionrule

public int encryptionrule
Description of the Field


mustencrypt

public boolean mustencrypt
Description of the Field


mustnotencrypt

public boolean mustnotencrypt
Description of the Field


encryptionstatecorrect

protected boolean encryptionstatecorrect
Description of the Field


data

protected java.util.Map data
Complete map of data for this thread base


senddata

protected java.util.Map senddata
Complete map of data for this thread base


cmdlogdata

protected java.util.Map cmdlogdata
Complete map of data for this thread base


sessionidcounter

private int sessionidcounter
Session counter to create session ids.


isclosing

private boolean isclosing
Flag whether this ServerThreadBase is about to be closed by a QUIT command


isclosed

private boolean isclosed
Flag that closing the ServerThreadBase has been finished. Needed only for vulture-driven close attempts


writerinterface

private ThreadInterface writerinterface
Interface for writing to the SocketLayer. Needed for sending free floating messages. Set only in connectionbound connections.


readerinterface

private ThreadInterface readerinterface
Interface for reading from the SocketLayer. Needed for closing in case of removal attempt from the outside. Set only in connectionbound connections.


connectionless

private boolean connectionless
Indicator whether this is a connectionless connection or not


connectionid

private java.lang.String connectionid
Complete id for logging output


sessions

private java.util.Map sessions
Map to all sessions


currentsession

private ServerThreadSession currentsession
The session answering the current query


authenticated

private boolean authenticated
Marker that counterside has authenticated in whatever way.


unauthenticatedtimeout

private long unauthenticatedtimeout
Idle timeouts


authenticatedtimeout

private long authenticatedtimeout
Idle timeouts


lastinteraction

private long lastinteraction
Time of last interaction from the client


sequence

private int sequence
Sequence counter for connectionless connections


locallycontrolled

private boolean locallycontrolled
Flag whether the thread base is controlled by local commands


locallycontrolledsettable

private boolean locallycontrolledsettable
Flag whether the locallycontrolled flag may be set.


lastencodingmode

private int lastencodingmode
Encoding mode of the connection.


lastencryptionmode

private boolean lastencryptionmode
Encryption mode of the connection.

Constructor Detail

ServerThreadBase

public ServerThreadBase(GJSAServer gx,
                        int encodingmode,
                        boolean encryptionmode,
                        java.net.InetAddress rx,
                        boolean clx,
                        long uat,
                        long ato)
Constructor for all cases.

Method Detail

initNameAndIP

private void initNameAndIP(java.net.InetAddress ix)
Primary initialisation of client IP address. This initializes the "real" client address and sets the reportable address to this real address. Additionally, a flag is initialized which controls whether the client can later on change the reportable address (i.e. it is a web browser serving the "interesting" client.

Parameters:
ix - IP address of the client

clientMatchesPattern

public boolean clientMatchesPattern(java.lang.String pattern)
Description of the Method

Parameters:
pattern - Description of the Parameter
Returns:
Description of the Return Value

setLocallyControlled

public void setLocallyControlled(boolean b)
Sets whether the ServerThreadBase is currently fed with server-local commands. This method can only be called once in the lifetime of a thread base. Any subsequent call is useless. This leads to the case that the password check can be circumvented only once during the lifetime of a thread base object as the check always resets the flag to "false" - and it cannot be changed afterwards with this method.

Parameters:
b - Flag whether passwords should be checked or not.

isLocallyControlled

public boolean isLocallyControlled()
Returns whether the ServerThreadBase is currently fed with server-local commands.


getClientInetAddr

public java.net.InetAddress getClientInetAddr()
Returns the InetAddress object for the currently connected client This method will also work for connectionless connect.


getClientHostName

public java.lang.String getClientHostName()
Returns the symbolic name of the real connected client. May be null.


getClientHostIP

public java.lang.String getClientHostIP()
Returns the IP address of the connected client. May be null though this is rather unlikely.


getClientHostDescription

public java.lang.String getClientHostDescription()
Returns a complete declarative description of the client's name and IP. Always not null, may be empty in case of neither name nor IP being available.


getReportedClientInetAddr

public java.net.InetAddress getReportedClientInetAddr()
Returns the InetAddress object for the currently connected client This method will also work for connectionless connect.


getReportedClientHostName

public java.lang.String getReportedClientHostName()
Returns the symbolic name of the real connected client. May be null.


getReportedClientHostIP

public java.lang.String getReportedClientHostIP()
Returns the IP address of the connected client. May be null though this is rather unlikely.


getReportedClientHostDescription

public java.lang.String getReportedClientHostDescription()
Returns a complete declarative description of the reported client's name and IP. Always not null, may be empty in case of neither name nor IP being available.


initEncryptionFlags

private void initEncryptionFlags(java.lang.Object o)
Description of the Method

Parameters:
o - Description of the Parameter

initDataMap

protected void initDataMap()
Initializes the data map and sends through CLIE logger


initSessions

private void initSessions()
initializes the session stack with initial executors


getUniqueSessionID

public int getUniqueSessionID()
Returns a unique session id for new sessions.


getRemovementLogging

public boolean getRemovementLogging()
Gets the removementLogging attribute of the ServerThreadBase object

Returns:
The removementLogging value

getGJSAServer

public GJSAServer getGJSAServer()
Gets the gJSAServer attribute of the ServerThreadBase object

Returns:
The gJSAServer value

registerSession

public void registerSession(ServerThreadSession sts)
Register a session for calling


setClientAddress

public void setClientAddress(java.lang.String ipaddress)
Sets the client's address of the connection to a new value. This method can be used by connections from certain hosts (e.g. where a webbrowser is running serving access to the system) to change the source IP address for the connection to another value (e.g. the IP from where the client to the web server is coming). This will only be granted if the real source is in the server's CHANGEABLEIP list. Otherwise, an exception is thrown and nothing happens.

Parameters:
ipaddress - The new client address, either by IP or by name.

releaseSession

public void releaseSession(ServerThreadSession sts)
Release a session of the register. Called by the session to be released in the moment of its disposal (close() method)

Parameters:
sts - The session to be released

setTimeouts

public void setTimeouts(long nto,
                        long ato)
Set the timeouts for the connection object

Parameters:
nto - Timeout in the non-authenticated case
ato - Timeout in the authenticated case

turnIntoAuthenticated

public void turnIntoAuthenticated()
Turns this connection into an authenticated one. An authenticated connection can have other timeouts when it comes to removing it from the server in case of inactivity


isTimedOut

public boolean isTimedOut(long currenttime)
Returns whether this connection is timed out and should be closed. Timeout is reached if nothing has been sent over the socket for the timeout time. That one depends on whether the client authenticated itself (usually longer time) or not (shorter time).

Returns:
Flag indicating whether timeout has been reached.

updateInteractionTimestamp

public void updateInteractionTimestamp()
Sets timestamp of last interaction to current time


isConnectionless

public boolean isConnectionless()
Returns whether this connection is connectionless


getSequence

public int getSequence()
Returns current sequence counter


incSequence

public void incSequence()
Increases the sequence counter.


incSequenceAndDisableLocallyControlled

public void incSequenceAndDisableLocallyControlled()
Increases the sequence counter and disables the locally controlled-flag. Sequence counter increment is usually done before a connectionless query is handled. It is quite sensible to disable the locally controlled flag at the same time as those queries come from a remote client. This method performs both tasks as efficiently as possible.


putProperty

public java.lang.Object putProperty(java.lang.Object key,
                                    java.lang.Object value)

getProperty

public java.lang.Object getProperty(java.lang.Object key)

removeProperty

public java.lang.Object removeProperty(java.lang.Object key)

setBurstAll

public void setBurstAll(boolean bx)

getBurstAll

public boolean getBurstAll()

setBurstNext

public void setBurstNext(boolean bx)

getBurstNext

public boolean getBurstNext()

setBurstSize

public void setBurstSize(int s)

getBurstSize

public int getBurstSize()

continueSyncBurst

public ServerReply continueSyncBurst()

initBurstableReply

public ServerReply initBurstableReply(BurstMaker bm)

openSession

public int openSession()

getLastChildSessionID

public int getLastChildSessionID()

closeSession

public void closeSession()

newState

public void newState(int newstate,
                     java.util.List commexecs,
                     java.util.List allcommexecs)

newState

public void newState(int newstate,
                     java.util.List commexecs)

newState

public void newState(int newstate,
                     CommandExecutor commexec)

startNewState

public void startNewState(int newstate)

retractNewState

public void retractNewState()

finishNewState

public void finishNewState(java.util.List commexecs,
                           java.util.List allcommexecs)

finishNewState

public void finishNewState(java.util.List commexecs)

finishNewState

public void finishNewState(CommandExecutor commexec)

leaveState

public void leaveState()

isClosing

public boolean isClosing()
returns if connection has received QUIT command and can therefore be removed. This method is only needed for connectionless connections as the handler of these connections must know when it may remove the ServerThreadBase from its Map

Returns:
Description of the Return Value

startClosing

public void startClosing()
Start closing the stuff. This one should be called from within the command executors if closing the session should be archieved after the current commands have been executed and the answers have been sent.


mayBeClosed

public boolean mayBeClosed()
returns whether the thread base may be closed or not. This is determined by the existance of a "NOKILL" property on any session's stack

Returns:
Description of the Return Value

freeFloatingReply

public void freeFloatingReply(int seq,
                              ServerReply sr,
                              InformableSender isx)
                       throws java.io.IOException
writes a free floating reply. Free floating replies work only in bound connections. The sender is informed after the reply has been actually written into the socket.

Parameters:
seq - Description of the Parameter
sr - Description of the Parameter
isx - Description of the Parameter
Throws:
java.io.IOException - Description of the Exception

freeFloatingReply

public void freeFloatingReply(int seq,
                              ServerReply sr)
                       throws java.io.IOException
writes a free floating reply. Free floating replies work only in bound connections.

Parameters:
seq - Description of the Parameter
sr - Description of the Parameter
Throws:
java.io.IOException - Description of the Exception

logMessage

public void logMessage(int sessionid,
                       java.lang.Object message)
Logs a message of any session to the standard message logger.


handleLogObject

public void handleLogObject(Logger src,
                            java.lang.Object o)
interface method for LoggingReceiver.

Specified by:
handleLogObject in interface LoggingReceiver
Parameters:
src - Description of the Parameter
o - Description of the Parameter

handleLogObject

public void handleLogObject(Logger src,
                            int nr,
                            java.lang.Object o)
Description of the Method

Specified by:
handleLogObject in interface TransactionLoggingReceiver
Parameters:
src - Description of the Parameter
nr - Description of the Parameter
o - Description of the Parameter

replyOneQuery

public ServerReply replyOneQuery(ServerRequest sr)
Convenience method to handle a single query


reply

public ServerEnvelope reply(ServerEnvelope se)
"Main" query handler.

All requests in the ServerEnvelope are handled and the replies are collected. Actual query handling is done by the correct ServerThreadSession's reply() method. It is guaranteed that there are no more replies than there have been requests. The reply vector can be shorter, however, if a query raised a serious error or was to close the connection.

Parameters:
se - ServerEnvelope containing the requests
Returns:
ServerEnvelope containing the replies

reply

public ServerEnvelope reply(ServerEnvelope se,
                            boolean encrypted,
                            int currencodingmode)
Handle a ServerEnvelope, readjust the "encryption" setting and report the current connection encoding


close

public void close()
Close the handler. Called from the outside. In connectionless case, just calls doClose() and make the handler removeable this way. In connectionbound case, closes reader interface so that main handling loop will stop.


doClose

private void doClose()
Real closing method Works regardless of connectionless or connectionbound connection. Calls all sessions to close themselves For connectionless connections, called directly from close(). In the connectionbound case, called by loopSynchronously() after leaving the main loop.


toString

public java.lang.String toString()
Description of the Method

Returns:
Description of the Return Value

setCurrentIdleStart

private void setCurrentIdleStart()

putData

public void putData(java.lang.String key,
                    java.lang.Object value)
Put one data element into the map, sets flag that listeners should be informed.


informConnectionListeners

public void informConnectionListeners()
Informs data listeners on changes if they have occured via putData() before.


getData

public java.util.Map getData()
Return complete data set for this connection


isEncryptionStateCorrect

public boolean isEncryptionStateCorrect()
Returns whether the encryption state is correct for opening a session or a new state in an existing session.

Returns:
boolean correctness of encryption state.

getMaxConnectionNr

public static int getMaxConnectionNr()
Returns the maximum assigned connection number.


getConnectionNr

public int getConnectionNr()
Returns the connection number of this connection.


getConnectionID

public java.lang.String getConnectionID()
Returns the connection ID which contains at least the connection number.


loopSynchronous

public void loopSynchronous(SocketLayer sly,
                            ServerEnvelope firstquery)
                     throws java.io.IOException
Throws:
java.io.IOException

QJCC homepage