Manager.java
jmud-0.11/src/Manager.java · 22.3 KB
From the archive jmud-0_11.tgz
Download the archive « Back to the archive contents
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.NoSuchElementException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.File;
import util.list.List;
import util.list.Queue;
import util.state.StateKeeper;
import util.state.StateUser;
import util.file.InvalidFileFormatException;
import string.StrUtil;
import misc.Separators;
import util.log.Log;
import util.log.LogRecipient;
import util.nice.NiceVector;
import util.nice.Searcher;
import util.nice.NiceKey;
import util.nice.NiceEnumeration;
class Manager implements LogRecipient {
private NiceVector clientMap = new NiceVector();
private List incomingClients = new List();
private List playingClients = new List();
private List fighters = new List();
private Interpreter theInterpreter = null;
private World theWorld = null;
private Config theConfig = null;
private SerialGenerator theSerialGen = null;
private ServerSocket serverSocket = null;
private Help theHelp = null;
private StateKeeper keeper = null;
private EffectTimer effecter = new EffectTimer();
private int portNumber;
private boolean listening;
private int shutdownTime = 0;
private String motd = "";
private InterpreterSuspender suspender = new InterpreterSuspender();
//private int numOfCli = 0;
//private Lock clientLock = new Lock();
Manager(String configName, int port) {
Log.log("Carregando arquivo de configuração: " + configName);
try {
theConfig = new Config(configName);
}
catch (FileNotFoundException e) {
Log.abort("Arquivo de configuração não encontrado: " + configName);
}
catch (IOException e) {
Log.abort("Falha de E/S ao ler arquivo de configuração: " + configName);
}
catch (InvalidFileFormatException e) {
Log.abort("Formato inválido do arquivo de configuração: " + configName);
}
String help = theConfig.getHelpFileName();
Log.log("Carregando arquivo de ajuda: " + help);
try {
theHelp = new Help(help);
}
catch(FileNotFoundException e) {
Log.err("Arquivo de ajuda não encontrado: " + help);
}
catch(IOException e) {
Log.err("Erro de E/S ao abrir arquivo de ajuda: " + help);
}
catch(InvalidFileFormatException e) {
Log.err("Arquivo de ajuda com formato inválido: " + help);
}
String state = theConfig.getStateFileName();
Log.log("Carregando arquivo de estado: " + state);
try {
keeper = new StateKeeper(state);
}
catch(IOException e) {
Log.abort("Erro de E/S ao abrir arquivo de estado: " + state);
}
catch(InvalidFileFormatException e) {
Log.abort("Arquivo de estado com formato inválido: " + state);
}
String motdfile = theConfig.getMotdFileName();
Log.log("Carregando mensagem do dia: " + motdfile);
try {
BufferedReader reader = new BufferedReader(new FileReader(motdfile));
while (reader.ready())
motd += reader.readLine() + Separators.NL;
reader.close();
}
catch(IOException e) {
Log.err("Erro de E/S ao carregar mensagem do dia: " + motdfile);
}
loadClientMap();
theInterpreter = new Interpreter(this, keeper);
theSerialGen = new SerialGenerator(keeper);
portNumber = port;
}
void loadClientMap() {
Log.log("Carregando mapa de clientes");
File f = new File(theConfig.getUserFilesDir());
if (!f.isDirectory())
Log.abort("Falha ao abrir diretório de usuários: " + theConfig.getUserFilesDir());
String users[] = f.list();
Player pl = null;
for (int i = 0; i < users.length; ++i) {
try {
pl = new Player(null, users[i], theConfig);
addClientMapEntry(pl.getName(), Integer.parseInt(users[i]));
}
catch(IOException e) {
Log.err("Falha de E/S ao ler arquivo de usuário: " + users[i]);
}
catch(InvalidFileFormatException e) {
Log.err("Arquivo de usuário com formato inválido: " + users[i]);
}
}
}
NiceEnumeration getClientMapEnum() {
return clientMap.elements();
}
void addClientMapEntry(String name, int id) {
clientMap.insert(new StrIntPair(name, id));
}
String listClientMap() {
String list = "";
for (NiceEnumeration enum = getClientMapEnum(); enum.hasMoreElements(); ) {
StrIntPair pair = (StrIntPair) enum.nextElement();
list += Separators.NL + StrUtil.rightPad(pair.getStr(), Client.MAX_NAME_LENGTH) + " " + StrUtil.formatNumber(pair.getInt(), 5);
}
return list;
}
////////////////////////
// Métodos synchronized:
/* desconectado
| (income)
recém-chegado
/ (play) \ (retreat)
jogando desconectado
| (quit)
desconectado
*/
// Entra na lista de recém-chegados
synchronized /* incomingClients, playingClients */
void income(Client aClient) {
incomingClients.insert(aClient);
}
// Desiste de se conectar (sai da lista de recém-chegados)
synchronized /* incomingClients */
void retreat(Client aClient) {
incomingClients.remove(aClient);
}
/////////////////////////
// client lock management
/*
private boolean getClientLock() {
return clientLock.get();
}
private void releaseClientLock() {
clientLock.release();
}
*/
//
/////////////////////////
/*
// executado por uma nova thread de cliente
private void incClients() {
// sim, isso é necessário, pois o
// interpreter é suspenso quando o JMud é iniciado
theInterpreter.resume();
while (!getClientLock()) {
if (Debug.full)
Log.log("Client: esperando trava");
theInterpreter.resume();
Thread.yield();
try { Thread.sleep(2000); } catch(InterruptedException e) { }
Thread.yield();
}
if (Debug.full)
Log.log("Client: trava obtida");
++numOfCli;
releaseClientLock();
if (Debug.full)
Log.log("Client: trava liberada");
}
// executado pela thread do interpreter
private void decClients() {
while (!getClientLock()) {
if (Debug.full)
Log.log("Interpreter: esperando trava");
theInterpreter.yield();
}
if (Debug.full)
Log.log("Interpreter: trava obtida");
--numOfCli;
if (numOfCli == 0) {
Log.log("Interpretador indo dormir");
theInterpreter.suspend();
Log.log("Interpretador despertado");
}
releaseClientLock();
if (Debug.full)
Log.log("Interpreter: trava liberada");
}
*/
// O Interpreter usa este método para avisar o Manager de que
// um personagem saiu efetivamente do mundo
//
// Executado na thread do Interpreter
void quitDone() {
suspender.oneLessClient();
}
// O Client usa este método (via metodo play) para inserir
// seu personagem no mundo.
//
// Executado na thread do Client
synchronized /* playingClients, incomingClients */
private void arrive(Client aClient) {
incomingClients.remove(aClient);
playingClients.insert(aClient);
suspender.oneMoreClient();
}
// Usado _apenas_ pelo Interpreter para se congelar
// aguardando por conexoes apos a carga do sistema.
void suspendWhileEmpty() {
suspender.blockWhileEmpty();
}
// Remove um personagem do lista de jogadores
synchronized /* playingClients */
private void leave(Client aClient) {
playingClients.remove(aClient);
}
//////////////////////////////////
// Muda para a lista de conectados
// * e' chamado pela thread do cliente (Client) para
// inserir o respectivo personagem no mundo
// 1. chaveia o personagem para a lista efetiva de jogadores
// 2. agenda BeginTask, que faz o restante do processamento
// na thread do Interpreter
void play(Client aClient) {
arrive(aClient);
scheduleTask(new BeginTask(aClient, -1));
}
void play(Client aClient, int roomId) {
arrive(aClient);
scheduleTask(new BeginTask(aClient, roomId));
}
// Muda para a lista de conectados
//////////////////////////////////
///////////////////////
// Complemento do 'play
// * executado pela thread do cliente
// Sai da lista de conectados
void quit(Client aClient) {
leave(aClient);
scheduleTask(new QuitTask(aClient));
}
// Complemento do 'play
///////////////////////
//
//////////////////////////
String getWorldTime() {
return theInterpreter.getYear() + "/" +
StrUtil.formatNumber(theInterpreter.getMonth(), 2, '0') + "/" +
StrUtil.formatNumber(theInterpreter.getDay(), 2, '0') + " " +
StrUtil.formatNumber(theInterpreter.getHour(), 2, '0') + ":" +
StrUtil.formatNumber(theInterpreter.getMinute(), 2, '0');
}
String findHelpTopic(String topic)
throws NoSuchElementException {
if (theHelp == null) {
Log.log("Aviso: Manager.findElement() ignorando Ajuda vazia");
throw new NoSuchElementException();
}
return theHelp.findHelpByKey(topic);
}
void scheduleTask(Task tsk) {
theInterpreter.scheduleTask(tsk);
}
// apenas para nao passar ponteiro de interpreter
// para o comando "force"
void scheduleRequest(Request req) {
theInterpreter.scheduleRequest(req);
}
// consuta ao Serial Generator para o fornecimento
// de um novo ID de cliente
int newClientId() {
return theSerialGen.next();
}
synchronized /* incomingClients, playingClients */
void disconnectClients() {
Log.log("Desconectando clientes");
for (Enumeration ce = incomingClients.elements(); ce.hasMoreElements(); ) {
Client c = (Client) ce.nextElement();
c.flush();
c.rawSend(Separators.NL + "Sistema desativado." + Separators.NL);
c.disconnect();
}
for (Enumeration ce = playingClients.elements(); ce.hasMoreElements(); ) {
Client c = (Client) ce.nextElement();
c.saveChar();
c.flush();
c.rawSend(Separators.NL + "Sistema desativado." + Separators.NL);
c.disconnect();
}
}
void saveState() {
if (Debug.full)
Log.log("Gravando estado");
try {
keeper.shutdown();
}
catch(Throwable e) {
Log.err("Falha ao gravar estado");
}
}
/*
Este método é invocado pelo Interpreter,
para pedir ao Manager que encerre o programa.
É executado na Thread do Interpreter!
*/
void shutdown() {
disconnectClients();
saveState();
theWorld.saveBoards();
Log.log("Desativado");
System.exit(0);
}
synchronized /* playingClients */
Client findClientByName(String name)
throws NoSuchElementException {
for (Enumeration ce = playingClients.elements(); ce.hasMoreElements(); ) {
Client c = (Client) ce.nextElement();
if (c.hasName(name))
return c;
}
throw new NoSuchElementException();
}
synchronized /* playingClients */
private void logToClients(String msg, int minRank) {
for (Enumeration ce = playingClients.elements(); ce.hasMoreElements(); ) {
Client cli = (Client) ce.nextElement();
Char ch = cli.getChar();
if (ch.getRank() >= minRank && ((Player) ch).isReceivingLog())
ch.send(msg);
}
}
synchronized /* playingClients */
void sendToClients(String msg, int minRank) {
for (Enumeration ce = playingClients.elements(); ce.hasMoreElements(); ) {
Client cli = (Client) ce.nextElement();
Char ch = cli.getChar();
if (ch.getRank() >= minRank)
ch.send(msg);
}
}
synchronized /* playingClients */
void fillInterpreter() {
for (Enumeration ce = playingClients.elements(); ce.hasMoreElements(); ) {
Client cli = (Client) ce.nextElement();
Request req = cli.oneRequest();
if (req != null)
theInterpreter.scheduleRequest(req);
}
}
synchronized /* playingClients */
void flushToClients() {
for (Enumeration ce = playingClients.elements(); ce.hasMoreElements(); ) {
Client cli = (Client) ce.nextElement();
cli.flush();
}
}
int getShutdownTime() {
return shutdownTime;
}
void scheduleShutdown(int time) {
shutdownTime = time;
}
void cancelShutdown() {
shutdownTime = 0;
}
private void checkShutdown() {
if (shutdownTime > 0)
if (--shutdownTime == 0) {
Log.log("Executando desativação agendada");
shutdown();
}
else
sendToClients("Desativação agendada ocorrerá em " + shutdownTime + " hora(s).", Char.R_DISABLED);
}
///////////////////
// LogRecipient:
public void forward(String msg, int priority) {
logToClients("[" + msg + "]", priority);
}
//
///////////////////
///////////////////
// Usados por Char:
void enterFight(Char ch) {
fighters.insert(ch);
}
void leaveFight(Char ch) {
fighters.remove(ch);
}
//
///////////////////
private void pulseBattles() {
for (Enumeration fig = fighters.elements(); fig.hasMoreElements(); ) {
Char curr = (Char) fig.nextElement();
curr.attack();
}
}
//////////////////////////////////////////////////////////////////
// Chamados pelo interpreter quando os respectivos ticks ocorrem:
void yearAction() {
}
void monthAction() {
}
void dayAction() {
}
void hourAction() {
effecter.updateEffects();
checkShutdown();
theWorld.checkResets();
int hour = theInterpreter.getHour();
switch (hour) {
case 6:
theWorld.sendToOpenPlace("Amanheceu.");
break;
case 18:
theWorld.sendToOpenPlace("Anoiteceu.");
break;
}
theWorld.creatureAction();
}
void minuteAction() {
pulseBattles();
}
void tickAction() {
flushToClients();
}
//
//////////////////////////////////////////////////////////////////
void insertEffect(Effect eff) {
effecter.insert(eff, false);
}
void removeEffect(Effect eff) {
effecter.remove(eff, true);
}
String getMotd() {
return motd;
}
void go() {
Log.log("Executando na porta: " + portNumber);
try {
serverSocket = new ServerSocket(portNumber);
}
catch (IOException e) {
Log.abort("Falha ao ouvir porta: " + portNumber);
}
Log.log("Carregando mundo");
theWorld = new World(this, theConfig);
Command.setWorld(theWorld);
Task.setWorld(theWorld);
Char.setWorld(theWorld);
Item.setWorld(theWorld);
Room.setWorld(theWorld);
Magic.setWorld(theWorld);
CreatureProto.setWorld(theWorld);
theWorld.resetZones();
Log.log("Lançando interpretador");
theInterpreter.start();
Log.log("Esperando por conexões");
listening = true;
while (listening) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
Log.err("Falha ao aceitar conexão na porta: " + portNumber);
continue;
}
Client newClient = null;
try {
newClient = new Client(theConfig, clientSocket);
}
catch(IOException e) {
Log.err("Falha ao criar novo cliente");
continue;
}
income(newClient);
newClient.start();
}
try {
serverSocket.close();
}
catch (IOException e) {
Log.err("Falha ao fechar socket servidor");
}
Log.log("Abandonada espera por conexões");
}
}
class SerialGenerator implements StateUser {
private final String stateUserId = "SerialGenerator";
private final String serialKey = "ContadorSerial";
private int current;
SerialGenerator(StateKeeper keeper) {
keeper.register(this);
String info = keeper.lookupInfo(this, serialKey);
current = (info == null) ? 0 : Integer.parseInt(info);
}
synchronized int next() {
return current++;
}
//////////////
// StateUser:
public String getStateUserId() {
return stateUserId;
}
public void updateStateKeeper(StateKeeper keeper) {
keeper.updateInfo(this, serialKey, String.valueOf(current));
}
//
/////////////
}
class EventQueue extends Queue {
synchronized public void insert(Object event) {
super.insert(event);
}
synchronized public Object remove() {
return super.remove();
}
}
class Interpreter extends Thread implements StateUser {
private Manager theManager = null;
private boolean interpreting = true;
private EventQueue theRequests = new EventQueue();
private EventQueue theTasks = new EventQueue();
static private final int PULSES_PER_SEC = 4;
static private final int SLEEP_TIME = 1000 / PULSES_PER_SEC;
private int pulses = 0;
private int minute = 0;
private int hour = 0;
private int day = 1;
private int month = 1;
private int year = 0;
static final String stateUserId = "Interpreter";
static final String infoKey = "TempoDoMundo";
Interpreter(Manager aManager, StateKeeper keeper) {
theManager = aManager;
keeper.register(this);
String info = keeper.lookupInfo(this, infoKey);
if (info != null) {
StringTokenizer tok = new StringTokenizer(info);
year = Integer.parseInt(tok.nextToken());
month = Integer.parseInt(tok.nextToken());
day = Integer.parseInt(tok.nextToken());
hour = Integer.parseInt(tok.nextToken());
minute = Integer.parseInt(tok.nextToken());
}
}
void scheduleTask(Task aTask) {
theTasks.insert(aTask); // EventQueue e' synchronized
}
void scheduleRequest(Request aRequest) {
theRequests.insert(aRequest); // EventQueue e' synchronized
}
private void nextYear() {
++year;
theManager.yearAction();
}
private void nextMonth() {
++month;
if (month > 12) {
month = 1;
nextYear();
}
theManager.monthAction();
}
private void nextDay() {
++day;
if (day > 30) {
day = 1;
nextMonth();
}
theManager.dayAction();
}
private void nextHour() {
++hour;
if (hour > 23) {
hour = 0;
nextDay();
}
theManager.hourAction();
}
private void nextMinute() {
++minute;
if (minute > 59) {
minute = 0;
nextHour();
}
theManager.minuteAction();
}
private void nextTick() {
++pulses;
if (pulses >= PULSES_PER_SEC) {
pulses = 0;
nextMinute();
}
theManager.tickAction();
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
int getHour() {
return hour;
}
int getMinute() {
return minute;
}
public void run () {
theManager.suspendWhileEmpty();
while (interpreting) {
try {
sleep(SLEEP_TIME);
}
catch(InterruptedException e) {
}
// perform Tasks:
while (!theTasks.isEmpty())
((Task) theTasks.remove()).execute();
// perform Requests:
theManager.fillInterpreter(); // obtem 1 request de cada cliente
// executa todos os requests
while (!theRequests.isEmpty()) {
Request req = (Request) theRequests.remove();
String line = req.getCommandLine();
Char ch = req.getChar();
if (Debug.cmd)
Log.debug("Interpreter: " + ch.getName() + " {" + line + "}");
Command cmd = null;
StringTokenizer toker = new StringTokenizer(line);
String word = toker.nextToken();
cmd = CommandTable.findCommandByName(ch, word);
if (cmd == null) {
ch.send("Comando inválido.");
continue;
}
if (ch instanceof Player && !cmd.allowPlayer()) {
ch.send("Jogadores não podem usar esse comando.");
continue;
}
if (ch instanceof Creature && !cmd.allowCreature()) {
ch.send("Criaturas não podem usar esse comando.");
continue;
}
int minPos = cmd.getMinPos();
int chPos = ch.getPosition();
if (chPos >= minPos)
cmd.execute(ch, toker, word, line);
else
switch(chPos) {
case Char.P_DISABLED:
ch.send("Sua execução de comandos está desabilitada.");
break;
case Char.P_DEAD:
ch.send("Sinto muito, mas você está morto.");
break;
case Char.P_UNCONSCIOUS:
ch.send("Você está inconsciente.");
break;
case Char.P_INCAPACITATED:
ch.send("Você tenta, mas seu corpo não responde.");
break;
case Char.P_ASLEEP:
ch.send("Que tal acordar primeiro ?");
break;
case Char.P_RESTING:
ch.send("Não, você está relaxado demais pra isso.");
break;
case Char.P_SITTING:
ch.send("Não é possível fazer isso sentado.");
break;
case Char.P_STANDING:
ch.send("Seria preciso mais adrenalina.");
break;
case Char.P_AWARE:
ch.send("Você só pode fazer isso em batalha.");
break;
case Char.P_FIGHTING:
Log.warn(ch.getName() + " (posição: " + chPos + ") não pôde executar comando '" + cmd.getName() + "' (posição mínima: " + minPos + ")");
break;
default:
Log.warn(ch.getName() + " com posição inválida (" + chPos + ") invocando comando `" + cmd.getName() + "' (posição mínima: " + minPos + ")");
}
}
// executa ações dependentes de tempo
nextTick();
}
Log.log("Interpretador terminado");
}
private String stateInfo() {
return String.valueOf(year) + " " + String.valueOf(month) + " " + String.valueOf(day) + " " + String.valueOf(hour) + " " + String.valueOf(minute);
}
///////////////////////////////
// Implementação de StateUser:
public String getStateUserId() {
return stateUserId;
}
public void updateStateKeeper(StateKeeper keeper) {
keeper.updateInfo(this, infoKey, stateInfo());
}
//
///////////////////////////////
}
class InterpreterSuspender {
private int numberOfClients = 0;
synchronized void blockWhileEmpty() {
try {
Log.info("Interpretador indo dormir");
wait();
Log.info("Interpretador acordando");
}
catch (InterruptedException e) {
}
}
synchronized void oneMoreClient() {
++numberOfClients;
Log.debug("Número de clientes: " + numberOfClients);
notify();
}
synchronized void oneLessClient() {
--numberOfClients;
Log.debug("Número de clientes: " + numberOfClients);
if (numberOfClients == 0)
blockWhileEmpty();
}
}