org.starhope.appius.net
Class ServerThread

java.lang.Object
  extended by java.lang.Thread
      extended by org.starhope.appius.net.NetIOThread
          extended by org.starhope.appius.net.ServerThread
All Implemented Interfaces:
Comparable<Thread>, Runnable, Thread.UncaughtExceptionHandler, NetIOHandlerPeer, ServerProcessor, AcceptsMetronomeTicks, HasName, CanProcessCommands
Direct Known Subclasses:
BatchProcessor, StreamProcessor, UserLoadTest

public class ServerThread
extends NetIOThread
implements ServerProcessor

This is the server thread for Appius Claudius Caecus. One server thread is instantiated for each connected user.

Author:
brpocock@star-hope.org

Nested Class Summary
 
Nested classes/interfaces inherited from class java.lang.Thread
Thread.State, Thread.UncaughtExceptionHandler
 
Field Summary
private  Set<Thread> adopted
          threads adopted by this one
protected  boolean busyState
          While we are processing a transaction for the user (during command processing), this flag is brought high to block idle timeouts due to overlong transactions
protected  Queue<AppiusDatagram> futureDatagrams
          The queue of all datagrams pending for this user.
protected  long idleWarned
          At what time was the user warned about being idle for too long?
protected  boolean keepRunning
          This variable controls the main loop of the server thread.
private  String language_dialect
          The user's language and dialect string for internationalization and localization
protected  long lastInputTime
          The time at which we last received input from the remote user.
protected  boolean loggedIn
          If the user has been logged in, this flag will be true
protected  int maxInputSize
          The maximum number of characters (or is it bytes? I'm unclear on my own implementation there!) that can be accepted from the client in a single packet
protected  User myUser
          The user account that is logged in on this thread
protected  int preloginCountdown
          The number of prelogin commands that can be accepted before the user is dropped for failing to log in
protected  String randomKey
          random key used for SHA1 sum in login
protected  float streamProtocolLanguage
          The language variant that the session is speaking.
protected  long tLastNudge
          Time at which users were last nudged to check their online status
protected  Zone zone
          The Zone in which this thread is connecting
 
Fields inherited from class org.starhope.appius.net.NetIOThread
debug, dialect, in, isDone, language, letsPlayWithFlash, out, parallelMode, socket, state
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
protected ServerThread(int maxSize)
          constructor used sôlely for WebSocketProcessor to be happy.
  ServerThread(Socket newSocket)
          Create a new thread connected to a given client, in a certain zone.
  ServerThread(String string)
          Just for uncaught exception handler faux-thread
 
Method Summary
 void adopt(Thread t)
          Adopt a thread into this one, starting it executing.
protected  void areYouThere()
          Send a packet to the user to see if they're still there
 void close()
          Schedule the socket to be closed and terminated ASAP
 void commandJSON(String cmd, org.json.JSONObject jso, Class<?> klass)
          Process a command from a JSON source
 void disconnectDuplicate()
          Disconnect *this* user, with a notification that they have logged in from someplace else.
protected  void doNudge(long t)
          Nudge the user to see if they're dead yet
protected  String doProcessing(String theInput)
           
 void doRealClose()
          Close the socket, terminate the connection
 void end()
          Indicate that this thread should cease to breathe.
 void enterZone(String zoneName)
          Enter into a Zone (set the local zone indicator)
 void enterZone(Zone whichZone)
          Enter into a Zone (set the local zone indicator)
 boolean equals(Object other)
          This is an overriding method.
 void failLogin()
          This method is called when login fails.
protected  void finalize()
           
protected  void genRandomKey(double mode)
           Generate a new random key:
 String getApple(String pass)
          Get the “apple” (CHAP authentication string SHA1 digest encoded in hex) for the login system
 String getIpAddress()
          Deprecated. Smart Fox Server Pro misspelling of getIPAddress()
 String getIPAddress()
           
 String getLanguage()
           
 String getRandomKey()
           
 String getRandomKey(double mode)
          Generate a new random key in the specified mode, and then return it.
 double getSFSVersion()
          Deprecated. use getStreamProtocolLanguage()
 double getStreamProtocolLanguage()
          get the language code used for the stream protocol
protected  Socket getStreamsReady()
          WRITEME: Document this method brpocock@star-hope.org
 GeneralUser getUser()
           
 Zone getZone()
          Get the zone in which this client is acting
protected  String grabInput()
          Get input from the client stream
 int hashCode()
          This is an overriding method.
 boolean isLoggedIn()
           
protected  void kickDuplicates(User user, String nick)
          Kick offline any duplicates of the given user as s/he logs in
protected  void kickDuplicates(User user, String nick, String password)
          Deprecated. use kickDuplicates(User, String)
protected  boolean logIn_checkPassword(User user, String password, Zone z)
          Check whether the supplied password (encrypted in SHA-1) is correct.
protected  boolean logIn_checkUserAllowed(AbstractUser user)
          Check whether the user is permitted to log in.
protected  boolean logIn_loadTest_autoCreateFakeUser(String nick)
          Automatically create a fake user in the database for load-testing purposes only.
 boolean logIn(Zone z, String bigNick, String password)
          Process a login request from the user
 void logout()
          Log out of the game
 void migrate(String hostName, int portNumber, String zoneName)
          Order this user to migrate to another Appius Claudius Caecus server.
protected  void postLogIn(Zone z, String password, AbstractUser user)
          Handle post-login events
private  void primeConnection()
          WRITEME: Document this method brpocock@star-hope.org
protected  String processInput_Infinity(String theInput)
          Process input received using the JSON-based Infinity mode
protected  String processInput_SmartFoxServer(String theInput)
           
protected  String processJSONInput(String theInput)
          Process a JSON string from the client
protected  String processJSONPreLogin(String theInput)
          Process a prelogin JSON command
protected  String processPreLogin(String theInput)
          Process a prelogin input sequence
protected  String processXMLInput(String theInput)
           
 void run()
          Run the server thread connected to a client
private  boolean send$EdenLogin(org.json.JSONObject result)
          WRITEME: Document this method brpocock@star-hope.org
 void sendAdminDisconnect(String message, String title, String label, String disconnectCause)
          Send a disconnection message, and drop the user on the next client cycle.
 void sendAdminMessage(String message, boolean remote)
          Send an administrative message to the user.
 void sendAdminMessage(String message, String title, String hatLabel, boolean remote)
          Send an administrative message.
 void sendBadPassword(Zone failZone, User user, String password)
           Send the user a notification that their password was incorrect.
protected  void sendDeferredDatagrams()
          Deprecated. for sendFutureDatagrams()
 void sendErrorReply(String source, String error, org.json.JSONObject result, User u, int room)
           send an error packet to the other party.
protected  boolean sendFutureDatagrams()
          Send any future datagrams that are pending for this user
 void sendGameActionMessage(AbstractUser sender, org.json.JSONObject data)
          Send a game action event message to the client
protected  void sendLoginPacket(String zoneName, String nick, String password)
          Send the bucketfuls of information that we force-feed the client at login...
protected  void sendLogKO()
          Send a login failure message to the client, using the default (generic) message.
protected  void sendLogKO(String messageText)
          Send a “KO” message to the client, informing them that they are not permitted to log in.
protected  boolean sendNextFutureDatagram()
          Send a single datagram off the queue.
 void sendNoSuchUser(String nick, String zoneName, String password)
          Tell the user to bugger off, because they don't exist.
 void sendPrivateMessage(AbstractUser from, String message)
          Send a private (“whisper”) message to the user
 void sendPublicMessage(AbstractUser from, String message)
          Send a public message
 void sendRawMessage(String reply, boolean remote)
          Deprecated. 
protected  void sendRawMessageLater(String reply)
          Send a message to the user in future
 void sendResponse(org.json.JSONObject result)
          Send a response as a future (deferred remote) datagram without a room specified
 void sendResponse(org.json.JSONObject result, int room, AbstractUser u)
          Deprecated. use sendResponse(JSONObject, int, boolean)
 void sendResponse(org.json.JSONObject result, int room, boolean remote)
          Send a response to the other party in JSON form.
 void sendResponse(org.json.JSONObject result, Integer room)
          Send a response as a future (deferred remote) datagram
 void sendResponse(org.json.JSONObject result, Integer room, AbstractUser u)
          Deprecated. perhaps use sendResponse(JSONObject,int,boolean) directly with the room ID and the “remote” boolean flag probably as “true”
 void sendResponseRemote(org.json.JSONObject result, Integer room, AbstractUser u)
          Deprecated. use sendResponse(JSONObject, Integer)
 void sendRoomEnteredByUser(Room room, AbstractUser user)
          Send notification that an user has joined a room
 void sendRoomList()
          Send the user a room list for their current zone
 void sendRoomList(AbstractZone forZone, boolean remote)
          Send the user a room list for an arbitrary zone
 void sendRoomPartedBy(Room room, AbstractUser user)
          Send a notification that an user has departed from a room
 void sendRoomUserCount(Room room)
          Send the user count for the given room
 void sendRoomVar(int roomNum, String varName, String varValue)
           
 void sendSuccessReply(String source, org.json.JSONObject resultIn, AbstractUser u, int room)
          Send a JSON success packet back to the client
 void sendUserJoin(Room room)
          Send the event to the user indicated that this user has joined a room successfully.
 void sendUserPart(AbstractUser user, Room room)
          Deprecated. use sendRoomPartedBy(Room, AbstractUser)
 void sendUserVariable(AbstractUser user, String varName, String varValue)
          Send an update to an user variable
 void setBusyState(boolean b)
           
 void setLanguage(String new_language_dialect)
           
 void setLastInputTime(long thatTime)
           
 void setLoggedIn(boolean amILoggedInNow)
           
 void setParallelMode(boolean newParallelMode)
           
 void setSFSVersion(float smartFoxServerCommProtocolVersion)
           
private  void setSocketOptionsFromConfig(Socket sock)
          WRITEME: Document this method brpocock@star-hope.org
protected  void setup()
          Set up this thread to execute
protected  String sha1hexify(String seed)
           
protected  String tattlePrefix()
          WRITEME: Document this method brpocock@star-hope.org
protected  boolean tick_checkIdleKick(long tIdle)
          Check whether the user has been idle for too long, and kick them offline if so
protected  boolean tick_checkIdleWarnTime(long tIdle)
          Check how long the user has been idle, and send a warning if the time idle has exceeded a limit
 void tick(long t, long dT)
          Propagate a metronome tick
protected  void toInfinityAndBeyond()
          engage Infinity-mode protocol
 String toString()
          This returns a plethora of debugging-useful information about this particular server thread.
 void uncaughtException(Thread t, Throwable e)
          This is an overriding method.
protected  String userDebug(String string)
          Create a message string informing the user that an error has occurred, and instructing them to contact Customer Service.
 
Methods inherited from class org.starhope.appius.net.NetIOThread
checkInputStream, compareTo, dropSocket_socketCore, dropSocketConnection, equals, getLanguage_dialect, getRemoteAddress, getSocket, getVerboseBugReplies, isDebug, isParallelMode, processInput, sendError_RAW, sendRawMessageNow, setDebug, setLanguage, setVerboseBugReplies, superVerbose, tattle, tattle
 
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, yield
 
Methods inherited from class java.lang.Object
clone, getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.starhope.appius.net.ServerProcessor
start
 
Methods inherited from interface org.starhope.appius.util.HasName
getName
 
Methods inherited from interface org.starhope.util.types.CanProcessCommands
getName
 

Field Detail

adopted

private final Set<Thread> adopted
threads adopted by this one


busyState

protected boolean busyState
While we are processing a transaction for the user (during command processing), this flag is brought high to block idle timeouts due to overlong transactions


futureDatagrams

protected final Queue<AppiusDatagram> futureDatagrams
The queue of all datagrams pending for this user. The user should receive these as soon as possible.


idleWarned

protected long idleWarned
At what time was the user warned about being idle for too long?


keepRunning

protected boolean keepRunning
This variable controls the main loop of the server thread. When it transitions to “false,” the thread will die.


language_dialect

private String language_dialect
The user's language and dialect string for internationalization and localization


lastInputTime

protected long lastInputTime
The time at which we last received input from the remote user.


loggedIn

protected boolean loggedIn
If the user has been logged in, this flag will be true


maxInputSize

protected final int maxInputSize
The maximum number of characters (or is it bytes? I'm unclear on my own implementation there!) that can be accepted from the client in a single packet


myUser

protected User myUser
The user account that is logged in on this thread


preloginCountdown

protected int preloginCountdown
The number of prelogin commands that can be accepted before the user is dropped for failing to log in


randomKey

protected transient String randomKey
random key used for SHA1 sum in login


streamProtocolLanguage

protected float streamProtocolLanguage
The language variant that the session is speaking.


tLastNudge

protected long tLastNudge
Time at which users were last nudged to check their online status


zone

protected Zone zone
The Zone in which this thread is connecting

Constructor Detail

ServerThread

protected ServerThread(int maxSize)
constructor used sôlely for WebSocketProcessor to be happy.

Parameters:
maxSize - the maximum input buffer size

ServerThread

public ServerThread(Socket newSocket)
Create a new thread connected to a given client, in a certain zone.

Parameters:
newSocket - The socket connected to the client

ServerThread

public ServerThread(String string)
Just for uncaught exception handler faux-thread

Parameters:
string - thread name
Method Detail

adopt

public void adopt(Thread t)
Adopt a thread into this one, starting it executing. This thread will be made a part of the thread group with the server thread as its parent (XXX), and should be terminated when the user logs off. (This does not work… I don't think it does, anyways.)

Parameters:
t - a thread to be adopted

areYouThere

protected void areYouThere()
                    throws UserDeadException
Send a packet to the user to see if they're still there

Throws:
UserDeadException - if the user is disconnected

close

public void close()
Schedule the socket to be closed and terminated ASAP


commandJSON

public void commandJSON(String cmd,
                        org.json.JSONObject jso,
                        Class<?> klass)
Process a command from a JSON source

Parameters:
cmd - The command to be processed
jso - The JSON data object to be passed into the relevant command
klass - The dispatcher class responsible for handling this command

disconnectDuplicate

public void disconnectDuplicate()
Disconnect *this* user, with a notification that they have logged in from someplace else.


doNudge

protected void doNudge(long t)
                throws UserDeadException
Nudge the user to see if they're dead yet

Parameters:
t - the current time
Throws:
UserDeadException - if they are, in fact, dead

doProcessing

protected String doProcessing(String theInput)
Overrides:
doProcessing in class NetIOThread
Parameters:
theInput - to be processed
Returns:
the results

doRealClose

public void doRealClose()
Close the socket, terminate the connection


end

public void end()
Indicate that this thread should cease to breathe. This sets the keepRunning flag to “false” to terminate the main loop, and throws an arbitrary interrupt to smash whatever might be going on already.


enterZone

public void enterZone(String zoneName)
Enter into a Zone (set the local zone indicator)

Parameters:
zoneName - the name of the Zone

enterZone

public void enterZone(Zone whichZone)
Enter into a Zone (set the local zone indicator)

Parameters:
whichZone - The zone being entered

equals

public boolean equals(Object other)
Description copied from class: NetIOThread
This is an overriding method.

Overrides:
equals in class NetIOThread
See Also:
NetIOThread.equals(java.lang.Object)

failLogin

public void failLogin()
This method is called when login fails. At present, it just closes the connection.


finalize

protected void finalize()
                 throws Throwable
Overrides:
finalize in class Object
Throws:
Throwable
See Also:
Object.finalize()

genRandomKey

protected void genRandomKey(double mode)

Generate a new random key:

If mode is 0, avoid characters that won't work with Smart Fox Server clients;

If mode is Double.POSITIVE_INFINITY, don't worry about it

Parameters:
mode - the random key generation mode

getApple

public String getApple(String pass)
Get the “apple” (CHAP authentication string SHA1 digest encoded in hex) for the login system

Parameters:
pass - The plaintext password to be used
Returns:
the “apple” string

getIpAddress

@Deprecated
public String getIpAddress()
Deprecated. Smart Fox Server Pro misspelling of getIPAddress()

Returns:
The string form of the client's IP address (may be IPv4 or IPv6)

getIPAddress

public String getIPAddress()
Returns:
The string form of the client's IP address (may be IPv4 or IPv6)

getLanguage

public String getLanguage()
Returns:
the language and dialect to be used for Internationalisations and localisation
See Also:
LocalisedThread.getLanguage()

getRandomKey

public String getRandomKey()
Returns:
the random key sequence generated for this client thread

getRandomKey

public String getRandomKey(double mode)
Generate a new random key in the specified mode, and then return it. This destroys any existing apple that might have existed

Parameters:
mode - the random mode for genRandomKey(double)
Returns:
the newly-generated random key

getSFSVersion

@Deprecated
public double getSFSVersion()
Deprecated. use getStreamProtocolLanguage()

Returns:
the sfVersion

getStreamProtocolLanguage

public double getStreamProtocolLanguage()
get the language code used for the stream protocol

Returns:
the language code used for the stream protocol

getStreamsReady

protected Socket getStreamsReady()
                          throws UserDeadException,
                                 IOException
WRITEME: Document this method brpocock@star-hope.org

Returns:
WRITEME
Throws:
UserDeadException - WRITEME
IOException - WRITEME

getUser

public GeneralUser getUser()
Returns:
the user connected to this server thread

getZone

public Zone getZone()
Get the zone in which this client is acting

Returns:
the zone in which this client is acting

grabInput

protected String grabInput()
                    throws UserDeadException
Get input from the client stream

Returns:
the input from the client
Throws:
UserDeadException - if the user disconnects

hashCode

public int hashCode()
This is an overriding method.

Overrides:
hashCode in class NetIOThread
See Also:
Object.hashCode()

isLoggedIn

public boolean isLoggedIn()
Returns:
true, if a user has logged in on this thread

kickDuplicates

protected void kickDuplicates(User user,
                              String nick)
Kick offline any duplicates of the given user as s/he logs in

Parameters:
user - The user logging in (whose duplicates should be disconnected)
nick - The user's nickname (login name)

kickDuplicates

@Deprecated
protected void kickDuplicates(User user,
                                         String nick,
                                         String password)
Deprecated. use kickDuplicates(User, String)

Kick offline any duplicates of the given user as s/he logs in

Parameters:
user - The user logging in (whose duplicates should be disconnected)
nick - The user's nickname (login name)
password - The user's password (ignored)

logIn

public boolean logIn(Zone z,
                     String bigNick,
                     String password)
Process a login request from the user

Parameters:
z - The zone into which the user is trying to log in
bigNick - The user's requested nickname (attempted user name)
password - This is a bit of a misnomer. We actually are checking for the secret key (CHAP cookie) for the current channel, to which has been appended the user's actual password, as presented as a hex-coded SHA1 digest. (In brief: pseudocode of sha1( cookie + password ).toHex )
Returns:
true, if the user can log in; false, if they were refused

logIn_checkPassword

protected boolean logIn_checkPassword(User user,
                                      String password,
                                      Zone z)
Check whether the supplied password (encrypted in SHA-1) is correct. If it's incorrect, send a norification to that effect.

Parameters:
user - the user attempting to log in
password - the seeded SHA-1 hash of the password
z - the zone into which the user is attempting to log in
Returns:
true, if the password was correct, else false.

logIn_checkUserAllowed

protected boolean logIn_checkUserAllowed(AbstractUser user)
Check whether the user is permitted to log in. Reasons to not be permitted include being kicked, banned, canceled, or not having permission to connect to a beta test server

Parameters:
user - the user in question
Returns:
true, if the user is allowed to log in

logIn_loadTest_autoCreateFakeUser

protected boolean logIn_loadTest_autoCreateFakeUser(String nick)
Automatically create a fake user in the database for load-testing purposes only.

Parameters:
nick - the new user's nickname
Returns:
true, if the user was created

logout

public void logout()
Log out of the game


migrate

public void migrate(String hostName,
                    int portNumber,
                    String zoneName)
Order this user to migrate to another Appius Claudius Caecus server.

Parameters:
hostName - The alternate server's public host name or IP address string
portNumber - The listening port on the alternate server
zoneName - The zone name to which the user should connect

postLogIn

protected void postLogIn(Zone z,
                         String password,
                         AbstractUser user)
Handle post-login events

Parameters:
z - zone
password - user's (encrypted) password sequence
user - user

primeConnection

private void primeConnection()
                      throws UserDeadException
WRITEME: Document this method brpocock@star-hope.org

Throws:
UserDeadException - WRITEME

processInput_Infinity

protected String processInput_Infinity(String theInput)
Description copied from class: NetIOThread
Process input received using the JSON-based Infinity mode

Specified by:
processInput_Infinity in class NetIOThread
Parameters:
theInput - an input string from the client
Returns:
a string to output to the client
See Also:
handler for Infinity protocol

processInput_SmartFoxServer

protected String processInput_SmartFoxServer(String theInput)
Parameters:
theInput - the input string from the client
Returns:
an output string to the client
See Also:
handler for Smart Fox Server compatibility protocol

processJSONInput

protected String processJSONInput(String theInput)
Process a JSON string from the client

Parameters:
theInput - The JSON string containing the command and data
Returns:
A sequence to return to the client

processJSONPreLogin

protected String processJSONPreLogin(String theInput)
Process a prelogin JSON command

Parameters:
theInput - The input string, which must contain a properly-formatted JSON command sequence
Returns:
a result string to be returned to the client

processPreLogin

protected String processPreLogin(String theInput)
                          throws UserDeadException
Process a prelogin input sequence

Parameters:
theInput - the prelogin input sequence
Returns:
the output string to return to the client
Throws:
UserDeadException - if the user disconnects

processXMLInput

protected String processXMLInput(String theInput)
Parameters:
theInput - The input stream, expected to be in Smart Fox Server Pro XML format
Returns:
A result string to be returned to the user

run

public void run()
Run the server thread connected to a client

Specified by:
run in interface Runnable
Overrides:
run in class Thread
See Also:
Thread.run()

send$EdenLogin

private boolean send$EdenLogin(org.json.JSONObject result)
                        throws org.json.JSONException
WRITEME: Document this method brpocock@star-hope.org

Parameters:
result - WRITEME
Returns:
WRITEME
Throws:
org.json.JSONException - WRITEME

sendAdminDisconnect

public void sendAdminDisconnect(String message,
                                String title,
                                String label,
                                String disconnectCause)
Send a disconnection message, and drop the user on the next client cycle. This is an asynchronous drop, but it clears all other pending output, ensuring that the client will receive this message next in queue and then disconnect.

Parameters:
message - User-visible message explaining the disconnection
title - Title to display in message box
label - Label to display in corner of message box
disconnectCause - Cause code to return to client application giving general cause for disconnection; e.g. "kick" or "ban" usually

sendAdminMessage

public void sendAdminMessage(String message,
                             boolean remote)
                      throws UserDeadException
Send an administrative message to the user.

Parameters:
message - administrative message to send
remote - if true, this is being written to another user
Throws:
UserDeadException - if the user has been disconnected
See Also:
sendAdminMessage(String, String, String, boolean)

sendAdminMessage

public void sendAdminMessage(String message,
                             String title,
                             String hatLabel,
                             boolean remote)
                      throws UserDeadException
Send an administrative message. Attempts to use the JSON protocol for all clients now. If the data can't be successfully encoded into

Parameters:
message - The actual message text
title - The title, which displays in the same font above the message, but does not scroll
hatLabel - A short label which identifies the general source of the message, for dialog box decoration
remote - Whether to send this message remotely (true = deferred delivery) or immediately (false)
Throws:
UserDeadException - if the user isn't there to receive the message

sendBadPassword

public void sendBadPassword(Zone failZone,
                            User user,
                            String password)

Send the user a notification that their password was incorrect.

Note that the user will actually just get a logKO, we don't give them any further information — this routine sends some more logging information, though.

Parameters:
failZone - The failed zone
user - The user attempting to log in
password - The attempted password

sendDeferredDatagrams

@Deprecated
protected void sendDeferredDatagrams()
                              throws UserDeadException
Deprecated. for sendFutureDatagrams()

Send all deferred (future) datagrams pending in the queue

Throws:
UserDeadException - if the user has disconnected

sendErrorReply

public void sendErrorReply(String source,
                           String error,
                           org.json.JSONObject result,
                           User u,
                           int room)
                    throws org.json.JSONException,
                           UserDeadException

send an error packet to the other party.

Parameters:
source - The method returning the error message
error - The error message
result - The payload, if any. May be altered.
u - The user to whom to send the success reply
room - The room in which the user is standing
Throws:
org.json.JSONException - if the packet can't be created
UserDeadException - if the user is not there

sendFutureDatagrams

protected boolean sendFutureDatagrams()
Send any future datagrams that are pending for this user

Returns:
true, if the user has been disconnected

sendGameActionMessage

public void sendGameActionMessage(AbstractUser sender,
                                  org.json.JSONObject data)
                           throws org.json.JSONException,
                                  UserDeadException
Send a game action event message to the client

Parameters:
sender - The user sending the game action
data - Arbitrary data associated with the game action
Throws:
org.json.JSONException - if the data can't be represented as JSON
UserDeadException - if the user has been disconnected

sendLoginPacket

protected void sendLoginPacket(String zoneName,
                               String nick,
                               String password)
Send the bucketfuls of information that we force-feed the client at login...

Parameters:
zoneName - The name of the zone into which the user has logged in
nick - The user's nickname
password - The user's password (SHA1 encoded with the local random key)

sendLogKO

protected void sendLogKO()
Send a login failure message to the client, using the default (generic) message.


sendLogKO

protected void sendLogKO(String messageText)
Send a “KO” message to the client, informing them that they are not permitted to log in.

Parameters:
messageText - The user-visible message given to the user

sendNextFutureDatagram

protected boolean sendNextFutureDatagram()
Send a single datagram off the queue.

Returns:
true, if we should disconnect now

sendNoSuchUser

public void sendNoSuchUser(String nick,
                           String zoneName,
                           String password)
Tell the user to bugger off, because they don't exist. Produces a login.fail (logKO) packet and makes some nice log entries.

Parameters:
nick - the user nickname (login name) attempted
zoneName - the zone into which they attempted to log in
password - the password attempted

sendPrivateMessage

public void sendPrivateMessage(AbstractUser from,
                               String message)
                        throws UserDeadException
Send a private (“whisper”) message to the user

Parameters:
from - The user sending the message
message - The message being whispered
Throws:
UserDeadException - if the user has been disconnected

sendPublicMessage

public void sendPublicMessage(AbstractUser from,
                              String message)
                       throws UserDeadException
Send a public message

Parameters:
from - sender of the message (speaker)
message - The public message
Throws:
UserDeadException - if the user has been disconnected

sendRawMessage

@Deprecated
public void sendRawMessage(String reply,
                                      boolean remote)
                    throws UserDeadException
Deprecated. 

probably clearer to call sendRawMessageLater(String) or NetIOThread.sendRawMessageNow(String)

Parameters:
reply - The string to be transmitted to this thread's user
remote - True, if being written to another user (if being written as a deferred future datagram)
Throws:
UserDeadException - if the user has been disconnected

sendRawMessageLater

protected void sendRawMessageLater(String reply)
                            throws UserDeadException
Description copied from class: NetIOThread
Send a message to the user in future

Specified by:
sendRawMessageLater in class NetIOThread
Parameters:
reply - The message to be sent in future
Throws:
UserDeadException - if the user is already gone
See Also:
NetIOThread.sendRawMessageLater(java.lang.String)

sendResponse

public void sendResponse(org.json.JSONObject result)
                  throws UserDeadException
Send a response as a future (deferred remote) datagram without a room specified

Specified by:
sendResponse in interface CanProcessCommands
Specified by:
sendResponse in class NetIOThread
Parameters:
result - a JSON-encoded response
Throws:
UserDeadException - if the user disconnects
See Also:
sendResponse(JSONObject, int, boolean), CanProcessCommands.sendResponse(org.json.JSONObject)

sendResponse

@Deprecated
public void sendResponse(org.json.JSONObject result,
                                    int room,
                                    AbstractUser u)
                  throws UserDeadException
Deprecated. use sendResponse(JSONObject, int, boolean)

send a response

Parameters:
result - result set
room - room of event
u - user to notify
Throws:
UserDeadException - if the user is detected to have been disconnected

sendResponse

public void sendResponse(org.json.JSONObject result,
                         int room,
                         boolean remote)
                  throws UserDeadException
Send a response to the other party in JSON form. In Smart Fox Server Pro compatibility mode, this goes through as a JSON Extension Response packet. In Cubist JSON form, the JSON object is returned “intact,” with the room number (if supplied as a positive number) added into it as the “r” key.

Parameters:
result - the JSON object to be returned to the other party
room - The room number from which the response is being sent.
remote - Whether to send the message as a remote (deferred future datagram) message
Throws:
UserDeadException - if the user has been disconnected

sendResponse

public void sendResponse(org.json.JSONObject result,
                         Integer room)
                  throws UserDeadException
Send a response as a future (deferred remote) datagram

Parameters:
result - the JSON result object to be sent (“extension response”)
room - The room in which the event occurred.
Throws:
UserDeadException - if the user has disconnected
See Also:
sendResponse(JSONObject, int, boolean)

sendResponse

@Deprecated
public void sendResponse(org.json.JSONObject result,
                                    Integer room,
                                    AbstractUser u)
                  throws UserDeadException
Deprecated. perhaps use sendResponse(JSONObject,int,boolean) directly with the room ID and the “remote” boolean flag probably as “true”

Parameters:
result - the JSON result object to be sent (“extension response”)
room - The room in which the event occurred.
u - The user to whom the message is being sent
Throws:
UserDeadException - if the user has disconnected

sendResponseRemote

@Deprecated
public void sendResponseRemote(org.json.JSONObject result,
                                          Integer room,
                                          AbstractUser u)
                        throws UserDeadException
Deprecated. use sendResponse(JSONObject, Integer)

Send a response as a future datagram, presumably to a remote user's thread

Parameters:
result - the JSON object to send to the client
room - the room number in which the event occurred
u - ignored…
Throws:
UserDeadException - if the user has already disconnected

sendRoomEnteredByUser

public void sendRoomEnteredByUser(Room room,
                                  AbstractUser user)
                           throws UserDeadException
Send notification that an user has joined a room

Parameters:
room - the room that has been joined by an user
user - the user joining the room
Throws:
UserDeadException - if the user has been disconnected

sendRoomList

public void sendRoomList()
                  throws UserDeadException
Send the user a room list for their current zone

Throws:
UserDeadException - if the user has been disconnected

sendRoomList

public void sendRoomList(AbstractZone forZone,
                         boolean remote)
                  throws UserDeadException
Send the user a room list for an arbitrary zone

Parameters:
forZone - The zone for which the user will receive a room list
remote - If true, writing to a remote user
Throws:
UserDeadException - if the user has been disconnected

sendRoomPartedBy

public void sendRoomPartedBy(Room room,
                             AbstractUser user)
                      throws UserDeadException
Send a notification that an user has departed from a room

Parameters:
room - The room from which someone has departed
user - The user who has departed from the room
Throws:
UserDeadException - if the user has been disconnected

sendRoomUserCount

public void sendRoomUserCount(Room room)
                       throws UserDeadException
Send the user count for the given room

Parameters:
room - The room whose user count is being updated
Throws:
UserDeadException - if the user has been disconnected

sendRoomVar

public void sendRoomVar(int roomNum,
                        String varName,
                        String varValue)
                 throws UserDeadException
Parameters:
roomNum - The room number for which the variable is being set
varName - The name of the room variable
varValue - The new value of the variable
Throws:
UserDeadException - if the user has been disconnected

sendSuccessReply

public void sendSuccessReply(String source,
                             org.json.JSONObject resultIn,
                             AbstractUser u,
                             int room)
                      throws org.json.JSONException
Send a JSON success packet back to the client

Parameters:
source - the method returning success
resultIn - additional information to be returned to the client
u - the user responsible for the successful reply (ignored)
room - the room in which the user is standing (ignored)
Throws:
org.json.JSONException - if the success reply can't be encoded in JSON form

sendUserJoin

public void sendUserJoin(Room room)
                  throws UserDeadException
Send the event to the user indicated that this user has joined a room successfully. This also engages Parallel mode, since the login process in both Smart Fox Server clients and Persephone II is known to have bad race conditions and not deal well with parallel mode.

Parameters:
room - the room joined
Throws:
UserDeadException - if the user has disconnected

sendUserPart

@Deprecated
public void sendUserPart(AbstractUser user,
                                    Room room)
                  throws UserDeadException
Deprecated. use sendRoomPartedBy(Room, AbstractUser)

Send notification that a user has departed from the room

Parameters:
user - The user departing from the room
room - The room from which the user has departed
Throws:
UserDeadException - if the user has been disconnected

sendUserVariable

public void sendUserVariable(AbstractUser user,
                             String varName,
                             String varValue)
                      throws UserDeadException
Send an update to an user variable

Parameters:
user - The user whose variable has been updated
varName - The name of the user variable
varValue - The new value of the user variable
Throws:
UserDeadException - if the user has been disconnected

setBusyState

public void setBusyState(boolean b)
Specified by:
setBusyState in interface CanProcessCommands
Parameters:
b - true, if the thread is in a busy state and should not be interrupted for idle timeout

setLanguage

public void setLanguage(String new_language_dialect)
Parameters:
new_language_dialect - the language and dialect to be used for internationalisation and localisation

setLastInputTime

public void setLastInputTime(long thatTime)
Specified by:
setLastInputTime in interface CanProcessCommands
Parameters:
thatTime - the time of last input from the client

setLoggedIn

public void setLoggedIn(boolean amILoggedInNow)
Parameters:
amILoggedInNow - True, if the thread represents a logged-in user

setParallelMode

public void setParallelMode(boolean newParallelMode)
Parameters:
newParallelMode - the parallelMode to set

setSFSVersion

public void setSFSVersion(float smartFoxServerCommProtocolVersion)
Parameters:
smartFoxServerCommProtocolVersion - The protocol version to be used. This version of the server supports Smart Fox Server Pro version 1.58, or Cubist JSON form using the value Double.POSITIVE_INFINITY

setSocketOptionsFromConfig

private void setSocketOptionsFromConfig(Socket sock)
                                 throws SocketException
WRITEME: Document this method brpocock@star-hope.org

Parameters:
sock - WRITEME
Throws:
SocketException - WRITEME

setup

protected void setup()
              throws IOException,
                     UserDeadException
Set up this thread to execute

Throws:
IOException - if the I/O streams can't be initialised
UserDeadException - if the user disconnects before setup is complete

sha1hexify

protected String sha1hexify(String seed)
Parameters:
seed - a string to be hashed
Returns:
the seed's SHA1 hash in hex

tattlePrefix

protected String tattlePrefix()
Description copied from class: NetIOThread
WRITEME: Document this method brpocock@star-hope.org

Specified by:
tattlePrefix in class NetIOThread
Returns:
WRITEME
See Also:
NetIOThread.tattlePrefix()

tick

public void tick(long t,
                 long dT)
          throws UserDeadException
Propagate a metronome tick

Specified by:
tick in interface AcceptsMetronomeTicks
Parameters:
t - The value of System.currentTimeMillis at the start of this tick
dT - The delta-T since the prior tick
Throws:
UserDeadException - if the user has been disconnected

tick_checkIdleKick

protected boolean tick_checkIdleKick(long tIdle)
                              throws UserDeadException
Check whether the user has been idle for too long, and kick them offline if so

Parameters:
tIdle - Time that the user has been idle (milliseconds)
Returns:
true, if the user was kicked off
Throws:
UserDeadException - if the user is disconnected

tick_checkIdleWarnTime

protected boolean tick_checkIdleWarnTime(long tIdle)
                                  throws UserDeadException
Check how long the user has been idle, and send a warning if the time idle has exceeded a limit

Parameters:
tIdle - The time that this connection or user has been idle
Returns:
true, if the user was warned; false, if not
Throws:
UserDeadException - if the user went away

toInfinityAndBeyond

protected void toInfinityAndBeyond()
engage Infinity-mode protocol

Overrides:
toInfinityAndBeyond in class NetIOThread

toString

public String toString()
This returns a plethora of debugging-useful information about this particular server thread.

Overrides:
toString in class Thread
See Also:
Thread.toString()

uncaughtException

public void uncaughtException(Thread t,
                              Throwable e)
This is an overriding method.

Specified by:
uncaughtException in interface Thread.UncaughtExceptionHandler
See Also:
Thread.UncaughtExceptionHandler.uncaughtException(java.lang.Thread, java.lang.Throwable)

userDebug

protected String userDebug(String string)
Create a message string informing the user that an error has occurred, and instructing them to contact Customer Service.

Parameters:
string - The debugging code to append to the message
Returns:
A string to return to the user