Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (109)
games submitted by our members
Games in WIP (536)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
  JavaGaming.org - Pastebin



Author: Tjstretchalot (posted 2012-10-02 15:48:28, viewed 126 times)

1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   116   117   118   119   120   121   122   123   124   125   126   127   128   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   184   185   186   187   188   189   190   191   192   193   194   195   196   197   198   199   200   201   202   203   204   205   206   207   208   209   210   211   212  
package me.timothy.consolegui;

import java.util.HashMap;
import java.util.Iterator;
import java.text.NumberFormat;
import java.text.DecimalFormat;

import javax.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
 */
public class ServerConsole extends ConsoleGUI {
  private HashMap<String[], CommandListener> commands;
  private static ServerConsole uncastedGUI;
  
  private String currentHelp;
  
  private ServerConsole() {
    super();
    commands = new HashMap<String[], CommandListener>();
  }
  
  /**
   * Creates an empty console to show default commands
   */
  public static void main(String[] args) {
    toGUI();
    ConsoleGUI.setSaveText(true);
    TAScanner scanner = ConsoleGUI.getScanner();
    TAPrintStream out = 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
   */
  public static void registerCommand(String cmName, String description, 
                                     CommandListener listener) {
    String[] command = new String[] { cmName, description };
    
    getGUI().commands.put(command, listener);
  }
  
  /**
   * Overrides the help command with the current
   * commands and their descriptions.
   */
  public static String updateHelp() {
    Iterator it = getGUI().commands.keySet().iterator();
    
    StringBuilder res = new StringBuilder("");
    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();
    return getGUI().currentHelp;
  }
  
  /**
   * Acts similiarly to the ConsoleGUI's method, except includes
   * registrying commands.
   */
  public static void toGUI() { 
    try
    {
      if(!SwingUtilities.isEventDispatchThread())
      {
        SwingUtilities.invokeAndWait(new Runnable() {
          @Override
          public void run()
          {
            gui = new ServerConsole();
            gui.setTitle("Server Console");
            uncastedGUI = (ServerConsole) gui;
            ConsoleGUI.gui = uncastedGUI;
            gui.stream = gui.createPrintStream();
            
            uncastedGUI.registerSpecial();
            uncastedGUI.updateHelp();
            gui.setVisible(true);
          }
        });
      }else
      {
        gui = new ServerConsole();
        uncastedGUI = (ServerConsole) gui;
        ConsoleGUI.gui = uncastedGUI;
        gui.stream = gui.createPrintStream();
        
        uncastedGUI.registerSpecial();
        uncastedGUI.updateHelp();
        gui.setVisible(true);
      }
      
      // Now prepare the command loop
      Runnable loop = new Runnable() {
        @Override
        public void run() {
          while(true) {
            String str = 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;
              }
            }
          }
        }
      };
      new Thread(loop).start();
    }catch(Exception exc)
    {
      handleException("Failed to convert to gui", exc, saveRun);
    }
  }
  
  public static ServerConsole getGUI() {
    return uncastedGUI;
  }
  
  /**
   * Registers special commands, such as help, default and memory
   */
  protected void registerSpecial() {
    CommandListener listener = new CommandListener() {
      @Override
      public void onCommand(String nm, String[] param) {
        TAPrintStream strm = getStream();
        if(nm.equalsIgnoreCase("help") || nm.equalsIgnoreCase("default")) {
          strm.print(getGUI().currentHelp);
        }else if(nm.equalsIgnoreCase("memory")) {
          long maxMemoryN = Runtime.getRuntime().maxMemory();
          long totalMemN = Runtime.getRuntime().totalMemory();
          long freeMemN = Runtime.getRuntime().freeMemory();
          long usedMemoryN = totalMemN - freeMemN;
          
          NumberFormat f = NumberFormat.getInstance();
          String maxMemory = f.format(maxMemoryN) + " (" + getReasonable(maxMemoryN)+ ")";
          String totalMem = f.format(totalMemN) + " (" + getReasonable(totalMemN) + ")";
          String freeMem = f.format(freeMemN) + " (" + getReasonable(freeMemN) + ")";
          String usedMemory = f.format(usedMemoryN) + " (" + getReasonable(usedMemoryN) + ")";
          
          StringBuilder mem = new StringBuilder("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);
    
  }
  
  private static final long KILO_BYTE = 1024;
  private static final long MEGA_BYTE = KILO_BYTE * 1024;
  private static final long GIGA_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
   */
  public static String getReasonable(long l) {
    DecimalFormat formater = new DecimalFormat("####.##");
    if(l > GIGA_BYTE) { 
      double d = l / (double) GIGA_BYTE;
      return formater.format(d) + " gigabytes";
    }else if(l > MEGA_BYTE) {
      double d = l / (double) MEGA_BYTE;
      return formater.format(d) + " megabytes";
    }else {
      double d = l / (double) KILO_BYTE;
      return formater.format(d) + " kilobytes";
    }
  }
}





Dump your java code here :



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 '~~~~'
  EOF
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CogWheelz (18 views)
2014-07-30 21:08:39

Riven (25 views)
2014-07-29 18:09:19

Riven (15 views)
2014-07-29 18:08:52

Dwinin (12 views)
2014-07-29 10:59:34

E.R. Fleming (33 views)
2014-07-29 03:07:13

E.R. Fleming (12 views)
2014-07-29 03:06:25

pw (43 views)
2014-07-24 01:59:36

Riven (43 views)
2014-07-23 21:16:32

Riven (30 views)
2014-07-23 21:07:15

Riven (31 views)
2014-07-23 20:56:16
List of Learning Resources
by SilverTiger
2014-07-31 18:29:50

List of Learning Resources
by SilverTiger
2014-07-31 18:26:06

List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!