/*
* Created on 08.11.2005 by jawe
* $Id$
*/
package net.jawe.scriptbot;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.jawe.scriptbot.factory.Factory;
/**
* Startup class for the Scriptbot.<br />
* Maintains a list of bots started throgh this class, that is available to
* every bot instance under the
* {@link net.jawe.scriptbot.Bot#getFromCache(String) cache}
* key {@value #BOTS_CACHE_KEY}.
*
* @author jawe
*/
public abstract class Main {
private static final Log LOG = LogFactory.getLog(Main.class);
private static final Map<String, Bot> bots = new HashMap<String, Bot>();
public static final String BOTS_CACHE_KEY = "_bots";
/**
* Starts the bot.
* @param args
*/
public static void main(String[] args) {
try {
if (args.length == 0) {
addBot();
} else {
for (String arg : args) {
if (arg.equals("-h") || arg.equals("--help")) {
printHelp();
break;
} else if (arg.equals("-V") || arg.equals("--version")) {
Bot bot = (Bot) Factory.getInstance().getBean("bot");
System.out.println(bot.getVersion());
break;
} else {
addBot(arg);
}
}
}
startBots();
} catch (Throwable t) {
LOG.fatal("Unexpected error", t);
System.exit(1);
}
}
/**
* Print usage information for the bot's command line invocation.
*/
public static void printUsage() {
System.out.println("Usage: java " + Main.class.getName()
+ " [-h] [-V] [ <init-script> [ <init-script> ...] ]");
}
public static void printHelp() {
printUsage();
System.out.println(" <init-script> (Optional) Path of the initial");
System.out.println(" configuration script. Every script");
System.out.println(" given starts a new bot.");
System.out.println(" Options:");
System.out.println(" -h|--help Print this help text and exit");
System.out.println(" -V|--version Print the program version and exit");
}
/**
* Starts the added bots.
*/
private static void startBots() {
for (final Map.Entry<String, Bot> e : bots.entrySet()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Starting bot " + e.getKey());
}
if (bots.size() > 1) {
Thread t = new Thread(e.getValue(), "Startup thread for bot "
+ e.getKey());
t.setDaemon(false); // give every startup thread a chance
t.start();
} else {
e.getValue().run();
}
}
if (LOG.isDebugEnabled()) {
int n = bots.size();
LOG.debug(n + " bot" + (n != 1 ? "s" : "") + " started");
}
}
/**
* Adds a bot to the list.
*/
private static void addBot() {
addBot(null);
}
/**
* Add a bot to the list.
* @param initScript the initScript to use.
*/
private static void addBot(String initScript) {
Bot bot = (Bot) Factory.getInstance().getBean("bot");
if (initScript != null) {
bot.getConfig().setInitScriptName(initScript);
}
bot.putInCache(BOTS_CACHE_KEY, bots);
bots.put(bot.getConfig().getInitScriptName(), bot);
}
}