packageme.timothy.consolegui;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.text.NumberFormat;
importjava.text.DecimalFormat;
importjavax.swing.SwingUtilities;
/**
* This class includes a command registry system
* and several default commands. The static methods
* from ConsoleGUI can be used.
*
* Note that the console will look for a 'default' in the
* commands HashMap if an unknown command is typed. By default,
* this will call 'help'. Help will be updated on called updateHelp(),
* which will take all of the names and descriptions and make a fast
* println.
*
* @author Timothy Moore
*/publicclassServerConsoleextendsConsoleGUI {
privateHashMap<String[], CommandListener> commands;
privatestaticServerConsoleuncastedGUI;
privateStringcurrentHelp;
privateServerConsole() {
super();
commands = newHashMap<String[], CommandListener>();
}
/**
* Creates an empty console to show default commands
*/publicstaticvoidmain(String[] args) {
toGUI();
ConsoleGUI.setSaveText(true);
TAScannerscanner = ConsoleGUI.getScanner();
TAPrintStreamout = ConsoleGUI.getStream();
}
/**
* Registers the command and updates the help document. A few special commands
* that are registered by default, however they can be overriden:
* <ul>
* <li>help - Lists
* <li>memory - Will list current memory, used memory and available memory
* <li>default - Called whenever an unexpected/unregistered command is used.
* </ul>
*
* @param cmName the name of the command
* @param description the description of the command
* @param listener the listener to call if that command is made
*/publicstaticvoidregisterCommand(StringcmName, Stringdescription,
CommandListenerlistener) {
String[] command = newString[] { cmName, description };
getGUI().commands.put(command, listener);
}
/**
* Overrides the help command with the current
* commands and their descriptions.
*/publicstaticStringupdateHelp() {
Iteratorit = getGUI().commands.keySet().iterator();
StringBuilderres = newStringBuilder("");
while(it.hasNext()) {
String[] str = (String[]) it.next();
if(!str[0].equals("default")) {
res.append(str[0]).append(" - ").append(str[1]).append("\n");
}
}
getGUI().currentHelp = res.toString();
returngetGUI().currentHelp;
}
/**
* Acts similiarly to the ConsoleGUI's method, except includes
* registrying commands.
*/publicstaticvoidtoGUI() {
try
{
if(!SwingUtilities.isEventDispatchThread())
{
SwingUtilities.invokeAndWait(newRunnable() {
@Overridepublicvoidrun()
{
gui = newServerConsole();
gui.setTitle("Server Console");
uncastedGUI = (ServerConsole) gui;
ConsoleGUI.gui = uncastedGUI;
gui.stream = gui.createPrintStream();
uncastedGUI.registerSpecial();
uncastedGUI.updateHelp();
gui.setVisible(true);
}
});
}else
{
gui = newServerConsole();
uncastedGUI = (ServerConsole) gui;
ConsoleGUI.gui = uncastedGUI;
gui.stream = gui.createPrintStream();
uncastedGUI.registerSpecial();
uncastedGUI.updateHelp();
gui.setVisible(true);
}
// Now prepare the command loop
Runnableloop = newRunnable() {
@Overridepublicvoidrun() {
while(true) {
Stringstr = getScanner().readLine();
String[] spl = str.split(" ");
String[] params = java.util.Arrays.copyOfRange(spl, 1, spl.length);
// This could be optimized, however it doesn't matter because they will
// not be doing very many commands, so this really won't make a difference
// unless there are a lot of commands.
for(String[] cmd : getGUI().commands.keySet()) {
if(cmd[0].equalsIgnoreCase(str)) {
getGUI().commands.get(cmd).onCommand(str, params);
break;
}
}
}
}
};
newThread(loop).start();
}catch(Exceptionexc)
{
handleException("Failed to convert to gui", exc, saveRun);
}
}
publicstaticServerConsolegetGUI() {
returnuncastedGUI;
}
/**
* Registers special commands, such as help, default and memory
*/protectedvoidregisterSpecial() {
CommandListenerlistener = newCommandListener() {
@OverridepublicvoidonCommand(Stringnm, String[] param) {
TAPrintStreamstrm = getStream();
if(nm.equalsIgnoreCase("help") || nm.equalsIgnoreCase("default")) {
strm.print(getGUI().currentHelp);
}elseif(nm.equalsIgnoreCase("memory")) {
longmaxMemoryN = Runtime.getRuntime().maxMemory();
longtotalMemN = Runtime.getRuntime().totalMemory();
longfreeMemN = Runtime.getRuntime().freeMemory();
longusedMemoryN = totalMemN - freeMemN;
NumberFormatf = NumberFormat.getInstance();
StringmaxMemory = f.format(maxMemoryN) + " (" + getReasonable(maxMemoryN)+ ")";
StringtotalMem = f.format(totalMemN) + " (" + getReasonable(totalMemN) + ")";
StringfreeMem = f.format(freeMemN) + " (" + getReasonable(freeMemN) + ")";
StringusedMemory = f.format(usedMemoryN) + " (" + getReasonable(usedMemoryN) + ")";
StringBuildermem = newStringBuilder("Allocated Memory / Max Memory: ");
mem.append(maxMemoryN == Long.MAX_VALUE ? totalMem : maxMemory).append("\nTotal Memory: ");
mem.append(totalMem).append("\nFree Memory: ");
mem.append(freeMem).append("\nUsed Memory: ").append(usedMemory);
strm.println(mem.toString());
}
}
};
registerCommand("memory", "Prints memory usage and information", listener);
registerCommand("help", "Prints this list of commands", listener);
registerCommand("default", "Prints this list of commands", listener);
}
privatestaticfinallongKILO_BYTE = 1024;
privatestaticfinallongMEGA_BYTE = KILO_BYTE * 1024;
privatestaticfinallongGIGA_BYTE = MEGA_BYTE * 1024;
/**
* Converts bytes to something more reasonable, eg 5000 bytes to 4.something
* kilobytes.
* 2,051,280 bytes is much harder to understand than 1.96 megabytes
*
* @param l the number of bytes
*/publicstaticStringgetReasonable(longl) {
DecimalFormatformater = newDecimalFormat("####.##");
if(l > GIGA_BYTE) {
doubled = l / (double) GIGA_BYTE;
returnformater.format(d) + " gigabytes";
}elseif(l > MEGA_BYTE) {
doubled = l / (double) MEGA_BYTE;
returnformater.format(d) + " megabytes";
}else {
doubled = l / (double) KILO_BYTE;
returnformater.format(d) + " kilobytes";
}
}
}
Special syntax:
To highlight a line (yellow background), prefix it with '@@'
To indicate that a line should be removed (red background), prefix it with '-'
To indicate that a line should be added (green background), prefix it with '+'
To post multiple snippets, seperate them by '~~~~'