net.sf.freecol.server
Class FreeColServer

java.lang.Object
  extended by net.sf.freecol.server.FreeColServer

public final class FreeColServer
extends java.lang.Object

The main control class for the FreeCol server. This class both starts and keeps references to all of the server objects and the game model objects.

If you would like to start a new server you just create a new object of this class.


Nested Class Summary
static class FreeColServer.GameState
          Constant for storing the state of the game.
 
Field Summary
private  Unit activeUnit
          An active unit specified in a saved game.
private  AIMain aiMain
           
static java.lang.String defaultSpec
          The specification to use when loading old format games where a spec may not be readily available.
private  ServerGame game
           
private  FreeColServer.GameState gameState
          Stores the current state of the game.
private static java.lang.String HEX_DIGITS
          Hex constant digits for get/restoreRandomState.
private static java.lang.String HIGH_SCORE_FILE
           
static java.util.Comparator<HighScore> highScoreComparator
           
private  java.util.List<HighScore> highScores
          The high scores on this server.
private  InGameController inGameController
           
private  InGameInputHandler inGameInputHandler
           
private  boolean integrity
          Did the integrity check succeed
private static java.util.logging.Logger logger
           
private  MapGenerator mapGenerator
           
private static int META_SERVER_UPDATE_INTERVAL
           
static int MINIMUM_SAVEGAME_VERSION
          The oldest save game format that can still be loaded.
private  java.lang.String name
          The name of this server.
private static int NUMBER_OF_HIGH_SCORES
           
private  java.lang.String owner
           
private  int port
           
private  PreGameController preGameController
           
private  PreGameInputHandler preGameInputHandler
           
private  boolean publicServer
           
private  java.util.Random random
          The private provider for random numbers.
static int SAVEGAME_VERSION
          The save game format used for saving games.
private  Server server
           
private  boolean singleplayer
           
private  UserConnectionHandler userConnectionHandler
           
 
Constructor Summary
FreeColServer(FreeColSavegameFile savegame, int port, java.lang.String name)
          Starts a new server in a specified mode and with a specified port and loads the game from the given file.
FreeColServer(FreeColSavegameFile savegame, int port, java.lang.String name, Specification specification)
          Starts a new server in a specified mode and with a specified port and loads the game from the given file.
FreeColServer(Specification specification, boolean publicServer, boolean singleplayer, int port, java.lang.String name)
          Starts a new server in a specified mode and with a specified port.
FreeColServer(Specification specification, boolean publicServer, boolean singleplayer, int port, java.lang.String name, NationOptions.Advantages advantages)
           
 
Method Summary
 ServerPlayer addAIPlayer(Nation nation)
          Adds a new AIPlayer to the Game.
private  void addBooleanOption(java.lang.String id, java.lang.String gr, boolean defaultValue)
           
private  void addIntegerOption(java.lang.String id, java.lang.String gr, int defaultValue)
           
private  void addStringOption(java.lang.String id, java.lang.String gr, java.lang.String defaultValue)
           
static XMLStream createXMLStreamReader(FreeColSavegameFile fis)
          Creates a XMLStream for reading the given file.
private  void fixGameOptions()
           
 Unit getActiveUnit()
          Gets the active unit specified in a saved game, if any.
 IndianSettlement getAdjacentIndianSettlementSafely(java.lang.String settlementId, Unit unit)
          Get an adjacent Indian settlement by ID, validating as much as possible, including checking whether the nation involved has been contacted.
 Settlement getAdjacentSettlementSafely(java.lang.String settlementId, Unit unit)
          Get a settlement by ID, validating the ID as much as possible.
 AIMain getAIMain()
          Gets the main AI-object.
 AIPlayer getAIPlayer(Player player)
          Gets the AI player corresponding to a given player.
 Controller getController()
          Gets the Controller.
 ServerGame getGame()
          Gets the Game that is being played.
 FreeColServer.GameState getGameState()
          Gets the current state of the game.
 java.util.List<HighScore> getHighScores()
          Get the HighScores value.
 InGameController getInGameController()
          Gets the controller being used while the game is running.
 InGameInputHandler getInGameInputHandler()
          Gets the InGameInputHandler.
 boolean getIntegrity()
          Gets the integrity check result.
 MapGenerator getMapGenerator()
          Gets the MapGenerator this FreeColServer is using when creating random maps.
 java.lang.String getName()
          Returns the name of this server.
 int getNumberOfLivingHumanPlayers()
          Gets the number of human players in this game that is still playing.
 java.lang.String getOwner()
          Gets the owner of the Game.
 ServerPlayer getPlayer(Connection connection)
          Gets a Player specified by a connection.
 PreGameInputHandler getPreGameInputHandler()
          Gets the PreGameInputHandler.
static java.lang.String getRandomState(java.util.Random random)
          Get the internal state of a random number generator as a string.
private static int getSavegameVersion(FreeColSavegameFile fis)
          Gets the save game version from a saved game.
 Server getServer()
          Gets the network server responsible of handling the connections.
 java.util.Random getServerRandom()
          Gets the server random number generator.
 int getSlotsAvailable()
          Gets the number of player that may connect.
 Specification getSpecification()
          Gets the specification from the game run by this server.
 Unit getUnitSafely(java.lang.String unitId, ServerPlayer serverPlayer)
          Get a unit by ID, validating the ID as much as possible.
 UserConnectionHandler getUserConnectionHandler()
          Gets the UserConnectionHandler.
 boolean isSingleplayer()
          Checks if the user is playing in singleplayer mode.
 Game loadGame(FreeColSavegameFile fis)
          Loads a game.
 Game loadGame(FreeColSavegameFile fis, Specification specification)
          Loads a game.
 void loadHighScores()
          Loads high scores.
 boolean newHighScore(Player player)
          Adds a new high score for player and returns true if possible.
static ServerGame readGame(FreeColSavegameFile fis, Specification specification, FreeColServer server)
          Reads just the game part from a save game.
static void removeAutosaves(java.lang.String prefix)
          Removes automatically created save games.
 void removeFromMetaServer()
          Removes this server from the metaserver's list.
static java.util.Random restoreRandomState(java.lang.String state)
          Restore a previously saved state.
 void revealMapForAllPlayers()
          Makes the entire map visible for all players.
 void saveGame(java.io.File file, java.lang.String username, OptionGroup options)
          Saves a game.
 void saveGame(java.io.File file, java.lang.String username, OptionGroup options, java.awt.image.BufferedImage image)
          Saves a game.
 void saveHighScores()
          Saves high scores.
 void setActiveUnit(Unit unit)
          Gets the active unit specified in a saved game, if any.
 void setAIMain(AIMain aiMain)
          Sets the main AI-object.
 void setGame(ServerGame game)
          Sets the Game that is being played.
 void setGameState(FreeColServer.GameState state)
          Sets the current state of the game.
 void setMapGenerator(MapGenerator mapGenerator)
          Sets the MapGenerator this FreeColServer is using when creating random maps.
 void setName(java.lang.String name)
          Sets the name of this server.
 void setOwner(java.lang.String owner)
          Sets the owner of the game.
 void setPublicServer(boolean publicServer)
          Sets the public server.
 void setServerRandom(java.util.Random random)
          Sets the server random number generator.
 void setSingleplayer(boolean singleplayer)
          Sets the mode of the game: singleplayer/multiplayer.
 void shutdown()
           
 void startMetaServerUpdateThread()
          Starts the metaserver update thread if publicServer == true.
 void updateMetaServer()
          Sends information about this server to the meta-server.
 void updateMetaServer(boolean firstTime)
          Sends information about this server to the meta-server.
private static void v11FixServerObjects(java.util.List<java.lang.String> serverStrings, FreeColSavegameFile fis)
          At savegame version 11 (new in 0.10.0) several classes were added to serverObjects.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

logger

private static final java.util.logging.Logger logger

META_SERVER_UPDATE_INTERVAL

private static final int META_SERVER_UPDATE_INTERVAL
See Also:
Constant Field Values

NUMBER_OF_HIGH_SCORES

private static final int NUMBER_OF_HIGH_SCORES
See Also:
Constant Field Values

HIGH_SCORE_FILE

private static final java.lang.String HIGH_SCORE_FILE
See Also:
Constant Field Values

HEX_DIGITS

private static final java.lang.String HEX_DIGITS
Hex constant digits for get/restoreRandomState.

See Also:
Constant Field Values

SAVEGAME_VERSION

public static final int SAVEGAME_VERSION
The save game format used for saving games. Version 7-10 were used in 0.9.x. Version 11 made a lot of changes and was introduced for the 0.10.0 series. Version 12 was introduced with HighSeas post-0.10.1. Please add to this comment if you increase the version.

See Also:
Constant Field Values

MINIMUM_SAVEGAME_VERSION

public static final int MINIMUM_SAVEGAME_VERSION
The oldest save game format that can still be loaded. The promise is that FreeCol 0.n.* can load 0.(n-1).* games. TODO: revisit the numbering scheme and save compatibility promise when 1.0 is released.

See Also:
Constant Field Values

defaultSpec

public static final java.lang.String defaultSpec
The specification to use when loading old format games where a spec may not be readily available.

See Also:
Constant Field Values

gameState

private FreeColServer.GameState gameState
Stores the current state of the game.


server

private Server server

userConnectionHandler

private final UserConnectionHandler userConnectionHandler

preGameController

private final PreGameController preGameController

preGameInputHandler

private final PreGameInputHandler preGameInputHandler

inGameInputHandler

private final InGameInputHandler inGameInputHandler

inGameController

private final InGameController inGameController

game

private ServerGame game

aiMain

private AIMain aiMain

mapGenerator

private MapGenerator mapGenerator

singleplayer

private boolean singleplayer

owner

private java.lang.String owner

publicServer

private boolean publicServer

port

private final int port

name

private java.lang.String name
The name of this server.


random

private java.util.Random random
The private provider for random numbers.


integrity

private boolean integrity
Did the integrity check succeed


activeUnit

private Unit activeUnit
An active unit specified in a saved game.


highScores

private java.util.List<HighScore> highScores
The high scores on this server.


highScoreComparator

public static final java.util.Comparator<HighScore> highScoreComparator
Constructor Detail

FreeColServer

public FreeColServer(Specification specification,
                     boolean publicServer,
                     boolean singleplayer,
                     int port,
                     java.lang.String name)
              throws java.io.IOException,
                     NoRouteToServerException
Starts a new server in a specified mode and with a specified port.

Parameters:
publicServer - This value should be set to true in order to appear on the meta server's listing.
singleplayer - Sets the game as singleplayer (if true) or multiplayer (if false).
port - The TCP port to use for the public socket. That is the port the clients will connect to.
name - The name of the server, or null if the default name should be used.
Throws:
java.io.IOException - if the public socket cannot be created (the exception will be logged by this class).
NoRouteToServerException

FreeColServer

public FreeColServer(Specification specification,
                     boolean publicServer,
                     boolean singleplayer,
                     int port,
                     java.lang.String name,
                     NationOptions.Advantages advantages)
              throws java.io.IOException,
                     NoRouteToServerException
Throws:
java.io.IOException
NoRouteToServerException

FreeColServer

public FreeColServer(FreeColSavegameFile savegame,
                     int port,
                     java.lang.String name)
              throws java.io.IOException,
                     FreeColException,
                     NoRouteToServerException
Starts a new server in a specified mode and with a specified port and loads the game from the given file.

Parameters:
savegame - The file where the game data is located.
port - The TCP port to use for the public socket. That is the port the clients will connect to.
name - The name of the server, or null if the default name should be used.
Throws:
java.io.IOException - if the public socket cannot be created (the exception will be logged by this class).
FreeColException - if the savegame could not be loaded.
NoRouteToServerException - if an error occurs

FreeColServer

public FreeColServer(FreeColSavegameFile savegame,
                     int port,
                     java.lang.String name,
                     Specification specification)
              throws java.io.IOException,
                     FreeColException,
                     NoRouteToServerException
Starts a new server in a specified mode and with a specified port and loads the game from the given file.

Parameters:
savegame - The file where the game data is located.
port - The TCP port to use for the public socket. That is the port the clients will connect to.
name - The name of the server, or null if the default name should be used.
specification - a Specification value
Throws:
java.io.IOException - if the public socket cannot be created (the exception will be logged by this class).
FreeColException - if the savegame could not be loaded.
NoRouteToServerException - if an error occurs
Method Detail

setSingleplayer

public void setSingleplayer(boolean singleplayer)
Sets the mode of the game: singleplayer/multiplayer.

Parameters:
singleplayer - Sets the game as singleplayer (if true) or multiplayer (if false).

isSingleplayer

public boolean isSingleplayer()
Checks if the user is playing in singleplayer mode.

Returns:
true if the user is playing in singleplayer mode, false otherwise.

getSpecification

public Specification getSpecification()
Gets the specification from the game run by this server.

Returns:
The specification from the game.

getUserConnectionHandler

public UserConnectionHandler getUserConnectionHandler()
Gets the UserConnectionHandler.

Returns:
The UserConnectionHandler that is beeing used when new client connect.

getController

public Controller getController()
Gets the Controller.

Returns:
The Controller.

getPreGameInputHandler

public PreGameInputHandler getPreGameInputHandler()
Gets the PreGameInputHandler.

Returns:
The PreGameInputHandler.

getInGameInputHandler

public InGameInputHandler getInGameInputHandler()
Gets the InGameInputHandler.

Returns:
The InGameInputHandler.

getInGameController

public InGameController getInGameController()
Gets the controller being used while the game is running.

Returns:
The controller from making a new turn etc.

getGame

public ServerGame getGame()
Gets the Game that is being played.

Returns:
The Game which is the main class of the game-model being used in this game.

setGame

public void setGame(ServerGame game)
Sets the Game that is being played.

Parameters:
game - The new Game.

setAIMain

public void setAIMain(AIMain aiMain)
Sets the main AI-object.

Parameters:
aiMain - The main AI-object which is responsible for controlling, updating and saving the AI objects.

getAIMain

public AIMain getAIMain()
Gets the main AI-object.

Returns:
The main AI-object which is responsible for controlling, updating and saving the AI objects.

getGameState

public FreeColServer.GameState getGameState()
Gets the current state of the game.

Returns:
One of: FreeColServer.GameState.STARTING_GAME, FreeColServer.GameState.IN_GAME and FreeColServer.GameState.ENDING_GAME.

setGameState

public void setGameState(FreeColServer.GameState state)
Sets the current state of the game.

Parameters:
state - The new state to be set. One of: FreeColServer.GameState.STARTING_GAME, FreeColServer.GameState.IN_GAME and FreeColServer.GameState.ENDING_GAME.

getServer

public Server getServer()
Gets the network server responsible of handling the connections.

Returns:
The network server.

getIntegrity

public boolean getIntegrity()
Gets the integrity check result.

Returns:
The integrity check result.

getServerRandom

public java.util.Random getServerRandom()
Gets the server random number generator.

Returns:
The server random number generator.

setServerRandom

public void setServerRandom(java.util.Random random)
Sets the server random number generator.

Parameters:
random - The new random number generator.

getMapGenerator

public MapGenerator getMapGenerator()
Gets the MapGenerator this FreeColServer is using when creating random maps.

Returns:
The MapGenerator.

setMapGenerator

public void setMapGenerator(MapGenerator mapGenerator)
Sets the MapGenerator this FreeColServer is using when creating random maps.

Parameters:
mapGenerator - The MapGenerator.

updateMetaServer

public void updateMetaServer()
                      throws NoRouteToServerException
Sends information about this server to the meta-server. The information is only sent if public == true.

Throws:
NoRouteToServerException

getName

public java.lang.String getName()
Returns the name of this server.

Returns:
The name.

setName

public void setName(java.lang.String name)
Sets the name of this server.

Parameters:
name - The name.

getOwner

public java.lang.String getOwner()
Gets the owner of the Game.

Returns:
The owner of the game.

setOwner

public void setOwner(java.lang.String owner)
Sets the owner of the game.

Parameters:
owner - The new owner of the game.

getActiveUnit

public Unit getActiveUnit()
Gets the active unit specified in a saved game, if any.

Returns:
The active unit.

setActiveUnit

public void setActiveUnit(Unit unit)
Gets the active unit specified in a saved game, if any.

Parameters:
unit - The active unit to save.

setPublicServer

public void setPublicServer(boolean publicServer)
Sets the public server.

Parameters:
publicServer - The new public server flag.

startMetaServerUpdateThread

public void startMetaServerUpdateThread()
Starts the metaserver update thread if publicServer == true. This update is really a "Hi! I am still here!"-message, since an additional update should be sent when a new player is added to/removed from this server etc.


updateMetaServer

public void updateMetaServer(boolean firstTime)
                      throws NoRouteToServerException
Sends information about this server to the meta-server. The information is only sent if public == true.

Parameters:
firstTime - Should be set to true> when calling this method for the first time.
Throws:
NoRouteToServerException - if the meta-server cannot connect to this server.

removeFromMetaServer

public void removeFromMetaServer()
Removes this server from the metaserver's list. The information is only sent if public == true.


getSlotsAvailable

public int getSlotsAvailable()
Gets the number of player that may connect.

Returns:
The number of available slots for human players. This number also includes european players currently controlled by the AI.

getNumberOfLivingHumanPlayers

public int getNumberOfLivingHumanPlayers()
Gets the number of human players in this game that is still playing.

Returns:
The number.

saveGame

public void saveGame(java.io.File file,
                     java.lang.String username,
                     OptionGroup options)
              throws java.io.IOException
Saves a game.

Parameters:
file - The file where the data will be written.
username - The username of the player saving the game.
Throws:
java.io.IOException - If a problem was encountered while trying to open, write or close the file.

saveGame

public void saveGame(java.io.File file,
                     java.lang.String username,
                     OptionGroup options,
                     java.awt.image.BufferedImage image)
              throws java.io.IOException
Saves a game.

Parameters:
file - The file where the data will be written.
username - The username of the player saving the game.
image - an Image value
Throws:
java.io.IOException - If a problem was encountered while trying to open, write or close the file.

createXMLStreamReader

public static XMLStream createXMLStreamReader(FreeColSavegameFile fis)
                                       throws java.io.IOException
Creates a XMLStream for reading the given file. Compression is automatically detected.

Parameters:
fis - The file to be read.
Returns:
The XMLStreamr.
Throws:
java.io.IOException - if thrown while loading the game or if a XMLStreamException have been thrown by the parser.

loadGame

public Game loadGame(FreeColSavegameFile fis)
              throws java.io.IOException,
                     FreeColException
Loads a game.

Parameters:
fis - The file where the game data is located.
Returns:
The username of the player saving the game.
Throws:
java.io.IOException - If a problem was encountered while trying to open, read or close the file.
java.io.IOException - if thrown while loading the game or if a XMLStreamException have been thrown by the parser.
FreeColException - if the savegame contains incompatible data.

readGame

public static ServerGame readGame(FreeColSavegameFile fis,
                                  Specification specification,
                                  FreeColServer server)
                           throws java.io.IOException,
                                  FreeColException
Reads just the game part from a save game. This routine exists apart from loadGame so that the map generator can load the predefined maps.

Parameters:
fis - The stream to read from.
specification - The Specification to use in the game.
server - Use this (optional) server to load into.
Returns:
The game found in the stream.
Throws:
FreeColException - if the format is incompatible.
java.io.IOException - if there is a problem reading the stream.

loadGame

public Game loadGame(FreeColSavegameFile fis,
                     Specification specification)
              throws FreeColException,
                     java.io.IOException
Loads a game.

Parameters:
fis - The file where the game data is located.
specification - a Specification value
Returns:
The new game.
Throws:
FreeColException - if the savegame contains incompatible data.
java.io.IOException - if there is problem reading a stream.

getSavegameVersion

private static int getSavegameVersion(FreeColSavegameFile fis)
                               throws FreeColException
Gets the save game version from a saved game.

Parameters:
fis - The saved game.
Returns:
The saved game version.
Throws:
FreeColException - if the version is incompatible.

fixGameOptions

private void fixGameOptions()

addBooleanOption

private void addBooleanOption(java.lang.String id,
                              java.lang.String gr,
                              boolean defaultValue)

addIntegerOption

private void addIntegerOption(java.lang.String id,
                              java.lang.String gr,
                              int defaultValue)

addStringOption

private void addStringOption(java.lang.String id,
                             java.lang.String gr,
                             java.lang.String defaultValue)

v11FixServerObjects

private static void v11FixServerObjects(java.util.List<java.lang.String> serverStrings,
                                        FreeColSavegameFile fis)
At savegame version 11 (new in 0.10.0) several classes were added to serverObjects. Evil hack here to scan the game for objects in pre-v11 games that should now be in serverObjects, and put them in.

Parameters:
serverStrings - A list of server object {type, id} pairs to add to.
fis - The savegame to scan.

removeAutosaves

public static void removeAutosaves(java.lang.String prefix)
Removes automatically created save games. Call this function to delete the automatically created save games from a previous game.


revealMapForAllPlayers

public void revealMapForAllPlayers()
Makes the entire map visible for all players. Used only when debugging (will be removed).


getPlayer

public ServerPlayer getPlayer(Connection connection)
Gets a Player specified by a connection.

Parameters:
connection - The connection to use while searching for a ServerPlayer.
Returns:
The player.

getUnitSafely

public Unit getUnitSafely(java.lang.String unitId,
                          ServerPlayer serverPlayer)
                   throws java.lang.IllegalStateException
Get a unit by ID, validating the ID as much as possible. Designed for message unpacking where the ID should not be trusted.

Parameters:
unitId - The ID of the unit to be found.
serverPlayer - The ServerPlayer to whom the unit must belong.
Returns:
The unit corresponding to the unitId argument.
Throws:
java.lang.IllegalStateException - on failure to validate the unitId in any way. In the worst case this may be indicative of a malign client.

getAdjacentSettlementSafely

public Settlement getAdjacentSettlementSafely(java.lang.String settlementId,
                                              Unit unit)
                                       throws java.lang.IllegalStateException
Get a settlement by ID, validating the ID as much as possible. Designed for message unpacking where the ID should not be trusted.

Parameters:
settlementId - The ID of the Settlement to be found.
unit - A Unit which must be adjacent to the Settlement.
Returns:
The settlement corresponding to the settlementId argument.
Throws:
java.lang.IllegalStateException - on failure to validate the settlementId in any way. In the worst case this may be indicative of a malign client.

getAdjacentIndianSettlementSafely

public IndianSettlement getAdjacentIndianSettlementSafely(java.lang.String settlementId,
                                                          Unit unit)
                                                   throws java.lang.IllegalStateException
Get an adjacent Indian settlement by ID, validating as much as possible, including checking whether the nation involved has been contacted. Designed for message unpacking where the ID should not be trusted.

Parameters:
settlementId - The ID of the Settlement to be found.
unit - A Unit which must be adjacent to the Settlement.
Returns:
The settlement corresponding to the settlementId argument.
Throws:
java.lang.IllegalStateException - on failure to validate the settlementId in any way. In the worst case this may be indicative of a malign client.

addAIPlayer

public ServerPlayer addAIPlayer(Nation nation)
Adds a new AIPlayer to the Game.

Parameters:
nation - a Nation value
Returns:
a ServerPlayer value

getAIPlayer

public AIPlayer getAIPlayer(Player player)
Gets the AI player corresponding to a given player.

Parameters:
player - The Player to look up.
Returns:
The corresponding AI player, or null if not found.

getHighScores

public java.util.List<HighScore> getHighScores()
Get the HighScores value.

Returns:
a List value

newHighScore

public boolean newHighScore(Player player)
Adds a new high score for player and returns true if possible.

Parameters:
player - a Player value
Returns:
a boolean value

saveHighScores

public void saveHighScores()
                    throws java.io.IOException
Saves high scores.

Throws:
java.io.IOException - If a problem was encountered while trying to open, write or close the file.

loadHighScores

public void loadHighScores()
                    throws java.io.IOException,
                           FreeColException
Loads high scores.

Throws:
java.io.IOException - If a problem was encountered while trying to open, read or close the file.
java.io.IOException - if thrown while loading the game or if a XMLStreamException have been thrown by the parser.
FreeColException - if the savegame contains incompatible data.

shutdown

public void shutdown()

getRandomState

public static java.lang.String getRandomState(java.util.Random random)
Get the internal state of a random number generator as a string. It would have been more convenient to simply return the current seed, but unfortunately it is private.

Parameters:
random - The Random to use.
Returns:
A String encapsulating the object state.

restoreRandomState

public static java.util.Random restoreRandomState(java.lang.String state)
                                           throws java.io.IOException
Restore a previously saved state.

Parameters:
state - The saved state (@see #getRandomState()).
Returns:
The restored Random.
Throws:
java.io.IOException - if unable to restore state.