[jboss-cvs] JBossCache/src/org/jboss/cache ...

Manik Surtani manik at jboss.org
Wed Apr 4 10:46:45 EDT 2007


  User: msurtani
  Date: 07/04/04 10:46:45

  Added:       src/org/jboss/cache  JBossCacheView.java
  Log:
  Updated gui for tutorial
  
  Revision  Changes    Path
  1.1      date: 2007/04/04 14:46:45;  author: msurtani;  state: Exp;JBossCache/src/org/jboss/cache/JBossCacheView.java
  
  Index: JBossCacheView.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   * Created on March 25 2003
   */
  package org.jboss.cache;
  
  
  import bsh.Interpreter;
  import bsh.util.JConsole;
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.jgroups.Address;
  import org.jgroups.View;
  
  import javax.swing.*;
  import javax.swing.event.TableModelEvent;
  import javax.swing.event.TableModelListener;
  import javax.swing.event.TreeSelectionEvent;
  import javax.swing.event.TreeSelectionListener;
  import javax.swing.table.DefaultTableModel;
  import javax.swing.table.TableColumn;
  import javax.swing.tree.DefaultMutableTreeNode;
  import javax.swing.tree.DefaultTreeModel;
  import javax.swing.tree.TreeNode;
  import javax.swing.tree.TreePath;
  import javax.swing.tree.TreeSelectionModel;
  import javax.transaction.Transaction;
  import javax.transaction.TransactionManager;
  import java.awt.*;
  import java.awt.event.ActionEvent;
  import java.awt.event.MouseAdapter;
  import java.awt.event.MouseEvent;
  import java.awt.event.MouseListener;
  import java.awt.event.WindowEvent;
  import java.awt.event.WindowListener;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.LinkedList;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  
  
  /**
   * Graphical view of a JBoss Cache instance.  Think of it as a view in an MVC model.  An instance of this view
   * needs to be given a reference to the  model ({@link Cache}) and needs to registers as a {@link CacheListener}. Changes
   * to the cache structure are propagated from the model to the view (via the CacheListener interface), changes from the
   * GUI (e.g. by a user) are executed on the Cache model directly (which, if clustered, will broadcast the changes to all replicas).
   * <p/>
   * The view itself maintains references to the nodes, but doesn't cache any of the data associated with the nodes. When
   * data needs to be displayed, the underlying cache will be accessed directly.
   *
   * @author Manik Surtani
   * @version $Revision: 1.1 $
   */
  public class JBossCacheView
  {
     /**
      * A reference to the Swing GUI that displays contents to the user.
      */
     private JBossCacheGUI gui = null;
  
     /**
      * Whether or not to use the embedded BeanShell console.
      */
     boolean useConsole = false;
  
     /**
      * The model - the cache that contains data.  For this example, the cache is only allowed to contain String types as both keys and values.
      */
     private Cache<String, String> cache = null;
  
     private static Log log = LogFactory.getLog(JBossCacheView.class.getName());
  
     /**
      * Constructs an instance of the view
      *
      * @param cache the cache which represents the model.
      */
     public JBossCacheView(Cache<String, String> cache)
     {
        setCache(cache);
     }
  
     /**
      * Sets a reference to the cache
      *
      * @param cache cache instance to associate with this view
      */
     public void setCache(Cache<String, String> cache)
     {
        this.cache = cache;
        if (gui != null) gui.setCache(cache);
     }
  
     /**
      * Starts the view
      *
      * @throws Exception if there are errors starting the GUI
      */
     public void start() throws Exception
     {
        if (gui == null)
        {
           log.info("start(): creating the GUI");
           System.out.println("start(): creating the GUI");
           gui = new JBossCacheGUI(cache, useConsole);
        }
     }
  
     /**
      * Stops the view
      */
     public void stop()
     {
        if (gui != null)
        {
           log.info("stop(): disposing the GUI");
           gui.stopGui();
           gui = null;
        }
     }
  
     /**
      * Starts the view
      *
      * @param args valid arguments are: -console to enable using the embedded beanShell console, -config [path/to/config/file] to specify a config file.
      */
     public static void main(String args[])
     {
        Cache<String, String> cache;
        JBossCacheView view;
        String configurationFile = "META-INF/replSync-service.xml";
        boolean useConsole = false;
  
        for (int i = 0; i < args.length; i++)
        {
           if (args[i].equals("-console"))
           {
              useConsole = true;
              continue;
           }
           if (args[i].equals("-config"))
           {
              configurationFile = args[++i];
              continue;
           }
           help();
           return;
        }
  
        try
        {
           CacheFactory<String, String> factory = DefaultCacheFactory.getInstance();
           cache = factory.createCache(configurationFile, false);
           // hack to prevent a state transfer for now
           cache.getConfiguration().setFetchInMemoryState(false);
           cache.start();
           view = new JBossCacheView(cache);
           view.useConsole = useConsole;
           view.start();
        }
        catch (Exception ex)
        {
           log.error("Cannot start up!!", ex);
        }
     }
  
     private static void help()
     {
        System.out.println("JBossCacheView [-help] " +
                           "[-console] " +
                           "[-config <path to configuration file to use>] ");
  
        System.out.println();
        System.out.println("-console enables the embedded BeanShell console");
        System.out.println("-config allows you to provide a path to the configuration file to use.");
     }
  }
  
  class JBossCacheGUI extends JFrame implements WindowListener, CacheListener, TreeSelectionListener, TableModelListener
  {
     private static final long serialVersionUID = -1242167331988194987L;
  
     private Cache<String, String> cache;
     private DefaultTreeModel tree_model = null;
     private Log log = LogFactory.getLog(getClass());
     private JTree jtree = null;
     private DefaultTableModel table_model = new DefaultTableModel();
     private JTable table = new JTable(table_model);
     private MyNode root = new MyNode(Fqn.SEPARATOR);
     private Fqn<String> selected_node = null;
     private JPanel tablePanel = null;
     private JPopupMenu operationsPopup = null;
     private static final int KEY_COL_WIDTH = 20;
     private static final int VAL_COL_WIDTH = 300;
     private TransactionManager tx_mgr = null;
     private Transaction tx = null;
     private JPanel mainPanel;
     private List<Address> membership = new LinkedList<Address>();
     private Address coordinator = null;
     private boolean useConsole = false;
  
  
     public JBossCacheGUI(Cache<String, String> cache, boolean useConsole) throws Exception
     {
        addNotify();
        this.useConsole = useConsole;
        tree_model = new DefaultTreeModel(root);
        jtree = new JTree(tree_model);
        jtree.setDoubleBuffered(true);
        jtree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
  
        JScrollPane scroll_pane = new JScrollPane(jtree);
        mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(scroll_pane, BorderLayout.CENTER);
  
        addWindowListener(this);
  
        table_model.setColumnIdentifiers(new String[]{"Name", "Value"});
        table_model.addTableModelListener(this);
  
        setTableColumnWidths();
  
        tablePanel = new JPanel();
        tablePanel.setLayout(new BorderLayout());
        tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
        tablePanel.add(table, BorderLayout.CENTER);
  
        mainPanel.add(tablePanel, BorderLayout.SOUTH);
        JSplitPane contentPanel = null;
        if (useConsole)
        {
           String welcomeMessage = "Welcome to the BeanShell console.\n\n" +
                                   "This console gives you a direct shell interface to the GUI above and allows you to manipulate the cache directly. " +
                                   "Some of the variables initialised in this shell session are:\n\n" +
                                   "// an instance of org.jboss.cache\n" +
                                   "    Cache<String, String> cache;\n" +
                                   "// a reference to the root node\n" +
                                   "    Node<String, String> root;\n" +
                                   "// the transaction manager registered with the cache\n" +
                                   "    TransactionManager transactionManager;\n";
           JConsole bshConsole = new JConsole();
           Interpreter interpreter = new Interpreter(bshConsole);
           interpreter.getNameSpace().importPackage("org.jboss.cache");
           interpreter.getNameSpace().importPackage("org.jboss.cache.transaction");
           interpreter.set("cache", cache);
           interpreter.set("root", cache.getRoot());
           interpreter.set("transactionManager", tx_mgr);
           interpreter.println(welcomeMessage);
           interpreter.setShowResults(!interpreter.getShowResults());// show() in beanShell
           System.setOut(bshConsole.getOut());
           System.setErr(bshConsole.getErr());
           Thread t = new Thread(interpreter);
           t.start();
  
           contentPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanel, bshConsole);
           getContentPane().add(contentPanel);
        }
        else
        {
           getContentPane().add(mainPanel);
        }
  
        jtree.addTreeSelectionListener(this);// REVISIT
  
        MouseListener ml = new MouseAdapter()
        {
           public void mouseClicked(MouseEvent e)
           {
              int selRow = jtree.getRowForLocation(e.getX(), e.getY());
              TreePath selPath = jtree.getPathForLocation(e.getX(), e.getY());
              if (selRow != -1)
              {
                 selected_node = makeFqn(selPath.getPath());
                 jtree.setSelectionPath(selPath);
  
                 if (e.getModifiers() == java.awt.event.InputEvent.BUTTON3_MASK)
                 {
                    operationsPopup.show(e.getComponent(), e.getX(), e.getY());
                 }
              }
           }
        };
  
        jtree.addMouseListener(ml);
  
        createMenus();
        setLocation(50, 50);
        setSize(getInsets().left + getInsets().right + 800, getInsets().top
                                                            + getInsets().bottom + 800);
  
        // make sure we set the cache BEFORE initialising this!!
        setCache(cache);
        init();
        setVisible(true);
  
        if (useConsole)
        {
           //has to be called after setVisible() otherwise no effect
           contentPanel.setDividerLocation(0.65);
        }
     }
  
     public void setCache(final Cache<String, String> cache)
     {
        this.cache = cache;
        if (this.cache != null)
        {
           Runtime.getRuntime().addShutdownHook(
                 new Thread()
                 {
                    public void run()
                    {
                       cache.stop();
                    }
                 });
  
           this.cache.addCacheListener(this);
           setTitle("JBoss Cache GUI: Local Address=" + getLocalAddress());
           tx_mgr = this.cache.getConfiguration().getRuntimeConfig().getTransactionManager();
           populateTree();
        }
        else
        {
           setTitle("Cache undefined");
           if (tree_model != null)
           {
              root = new MyNode(Fqn.SEPARATOR);
              tree_model.setRoot(root);
              tree_model.reload();
  
           }
           if (table_model != null)
           {
              clearTable();
           }
        }
     }
  
     public void windowClosed(WindowEvent event)
     {
     }
  
     public void windowDeiconified(WindowEvent event)
     {
     }
  
     public void windowIconified(WindowEvent event)
     {
     }
  
     public void windowActivated(WindowEvent event)
     {
     }
  
     public void windowDeactivated(WindowEvent event)
     {
     }
  
     public void windowOpened(WindowEvent event)
     {
     }
  
     public void windowClosing(WindowEvent event)
     {
        stopGui();
     }
  
  
     public void tableChanged(TableModelEvent evt)
     {
        int row, col;
        String key, val;
  
        if (evt.getType() == TableModelEvent.UPDATE)
        {
           row = evt.getFirstRow();
           col = evt.getColumn();
           if (col == 0)
           {// set()
              key = (String) table_model.getValueAt(row, col);
              val = (String) table_model.getValueAt(row, col + 1);
              if (key != null && val != null)
              {
                 try
                 {
                    cache.put(selected_node, key, val);
                 }
                 catch (Exception e)
                 {
                    e.printStackTrace();
                 }
  
              }
           }
           else
           {
              key = (String) table_model.getValueAt(row, col - 1);
              val = (String) table.getValueAt(row, col);
              if (key != null && val != null)
              {
                 put(selected_node, key, val);
              }
           }
        }
     }
  
  
     public void valueChanged(TreeSelectionEvent evt)
     {
        TreePath path = evt.getPath();
        String fqnString = Fqn.SEPARATOR;
        Fqn<String> fqn;
        String component_name;
        Map<String, String> data;
  
        for (int i = 0; i < path.getPathCount(); i++)
        {
           component_name = ((MyNode) path.getPathComponent(i)).name;
           if (component_name.equals(Fqn.SEPARATOR))
           {
              continue;
           }
           if (fqnString.equals(Fqn.SEPARATOR))
           {
              fqnString += component_name;
           }
           else
           {
              fqnString = fqnString + Fqn.SEPARATOR + component_name;
           }
        }
        fqn = Fqn.fromString(fqnString);
        data = getData(fqn);
        if (data != null)
        {
           mainPanel.add(tablePanel, BorderLayout.SOUTH);
           populateTable(data);
           validate();
        }
        else
        {
           clearTable();
           mainPanel.remove(tablePanel);
           validate();
        }
     }
  
     /* ------------------ CacheListener interface ------------ */
  
     public void nodeCreated(Fqn fqn, boolean pre, boolean isLocal)
     {
        if (!pre)
        {
           MyNode n, p;
  
           n = root.add(fqn);
           if (n != null)
           {
              p = (MyNode) n.getParent();
              tree_model.reload(p);
              jtree.scrollPathToVisible(new TreePath(n.getPath()));
           }
        }
  
     }
  
     public void nodeModified(Fqn fqn, boolean pre, boolean isLocal, ModificationType modType, Map data)
     {
        if (!pre)
        {
           populateTable(data);
        }
     }
  
     public void nodeRemoved(Fqn fqn, boolean pre, boolean isLocal, Map data)
     {
        if (!pre)
        {
           MyNode n;
           TreeNode par;
  
           n = root.findNode(fqn);
           if (n != null)
           {
              n.removeAllChildren();
              par = n.getParent();
              n.removeFromParent();
              tree_model.reload(par);
           }
        }
  
     }
  
     public void nodeVisited(Fqn fqn, boolean pre)
     {
     }
  
     public void nodeEvicted(Fqn fqn, boolean pre, boolean isLocal)
     {
        nodeRemoved(fqn, pre, isLocal, null);
     }
  
     public void nodeLoaded(Fqn fqn, boolean pre, Map data)
     {
        nodeCreated(fqn, pre, true);
     }
  
     public void nodeMoved(Fqn from, Fqn to, boolean pre, boolean isLocal)
     {
     }
  
     public void nodeActivated(Fqn fqn, boolean pre)
     {
     }
  
     public void nodePassivated(Fqn fqn, boolean pre)
     {
     }
  
     public void cacheStarted(CacheSPI cache)
     {
     }
  
     public void cacheStopped(CacheSPI cache)
     {
     }
  
     public void viewChange(final View new_view)
     {
        Thread t = new Thread()
        {
           public void run()
           {
              List<Address> mbrship;
              if (new_view != null && (mbrship = new_view.getMembers()) != null)
              {
                 membership.clear();
                 membership.addAll(mbrship);
                 coordinator = mbrship.get(0);
              }
           }
        };
        t.setDaemon(true);
        t.start();
     }
  
     /* ---------------- End of CacheListener interface -------- */
  
     /*----------------- Runnable implementation to make View change calles in AWT Thread ---*/
  
     public void run()
     {
  
     }
  
     /* ----------------------------- Private Methods ---------------------------------- */
  
     /**
      * Fetches all data from underlying cache model and display it graphically
      */
     private void init()
     {
        List<Address> mbrship;
  
        mbrship = getMembers();
        if (mbrship != null && mbrship.size() > 0)
        {
           membership.clear();
           membership.addAll(mbrship);
           coordinator = mbrship.get(0);
        }
     }
  
  
     /**
      * Fetches all data from underlying cache model and display it graphically
      */
     private void populateTree()
     {
        addGuiNode(Fqn.ROOT);
     }
  
  
     /**
      * Recursively adds GUI nodes starting from fqn
      */
     private void addGuiNode(Fqn<String> fqn)
     {
        Set<String> children;
  
        if (fqn == null) return;
  
        // 1 . Add myself
        root.add(fqn);
  
        // 2. Then add my children
        children = getChildrenNames(fqn);
        if (children != null)
        {
           for (String child_name : children)
           {
              addGuiNode(new Fqn<String>(fqn, child_name));
           }
        }
     }
  
  
     private Fqn<String> makeFqn(Object[] path)
     {
        List<String> elements = convertMyNodeArrayToStringArray(path);
        if (path.length == 0) return Fqn.ROOT;
        return new Fqn<String>(elements);
     }
  
     private List<String> convertMyNodeArrayToStringArray(Object[] path)
     {
        List<String> list = new LinkedList<String>();
        for (Object o : path)
        {
           MyNode n = (MyNode) o;
           if (!n.name.equals(Fqn.SEPARATOR)) list.add(n.name);
        }
        return list;
     }
  
     private void clearTable()
     {
        int num_rows = table.getRowCount();
  
        if (num_rows > 0)
        {
           for (int i = 0; i < num_rows; i++)
           {
              table_model.removeRow(0);
           }
           table_model.fireTableRowsDeleted(0, num_rows - 1);
           repaint();
        }
     }
  
  
     private void populateTable(Map<String, String> data)
     {
        String key;
        String val;
        int num_rows;
  
        if (data == null) return;
        num_rows = data.size();
        clearTable();
  
        if (num_rows > 0)
        {
           for (Map.Entry<String, String> entry : data.entrySet())
           {
              key = entry.getKey();
              val = entry.getValue();
              table_model.addRow(new Object[]{key, val});
           }
           table_model.fireTableRowsInserted(0, num_rows - 1);
           validate();
        }
     }
  
     private void setTableColumnWidths()
     {
        table.sizeColumnsToFit(JTable.AUTO_RESIZE_NEXT_COLUMN);
        TableColumn column;
        column = table.getColumnModel().getColumn(0);
        column.setMinWidth(KEY_COL_WIDTH);
        column.setPreferredWidth(KEY_COL_WIDTH);
        column = table.getColumnModel().getColumn(1);
        column.setPreferredWidth(VAL_COL_WIDTH);
     }
  
     private void createMenus()
     {
        JMenuBar menubar = new JMenuBar();
        JMenu operationsMenu = new JMenu("Operations");
        AddNodeAction addNode = new AddNodeAction();
        addNode.putValue(AbstractAction.NAME, "Add to this node");
        LoadAction load_action = new LoadAction();
        load_action.putValue(AbstractAction.NAME, "Load from the CacheLoader");
        RemoveNodeAction removeNode = new RemoveNodeAction();
        removeNode.putValue(AbstractAction.NAME, "Remove this node");
        EvictAction evict_action = new EvictAction();
        evict_action.putValue(AbstractAction.NAME, "Evict from the Cache");
        AddModifyDataForNodeAction addModAction = new AddModifyDataForNodeAction();
        addModAction.putValue(AbstractAction.NAME, "Add/Modify data");
        PrintLockInfoAction print_locks = new PrintLockInfoAction();
        print_locks.putValue(AbstractAction.NAME, "Print lock information (stdout)");
        ExitAction exitAction = new ExitAction();
        exitAction.putValue(AbstractAction.NAME, "Exit");
        StartTransaction start_tx = new StartTransaction();
        start_tx.putValue(AbstractAction.NAME, "Start TX");
        CommitTransaction commit_tx = new CommitTransaction();
        commit_tx.putValue(AbstractAction.NAME, "Commit TX");
        RollbackTransaction rollback_tx = new RollbackTransaction();
        rollback_tx.putValue(AbstractAction.NAME, "Rollback TX");
        operationsMenu.add(addNode);
        operationsMenu.add(load_action);
        operationsMenu.add(removeNode);
        operationsMenu.add(evict_action);
        operationsMenu.add(addModAction);
        operationsMenu.add(print_locks);
        operationsMenu.add(start_tx);
        operationsMenu.add(commit_tx);
        operationsMenu.add(rollback_tx);
        operationsMenu.add(exitAction);
        menubar.add(operationsMenu);
        setJMenuBar(menubar);
  
        operationsPopup = new JPopupMenu();
        operationsPopup.add(addNode);
        operationsPopup.add(load_action);
        operationsPopup.add(evict_action);
        operationsPopup.add(removeNode);
        operationsPopup.add(addModAction);
     }
  
     private Object getLocalAddress()
     {
        try
        {
           return cache.getLocalAddress();
        }
        catch (Throwable t)
        {
           log.error("JBossCacheGUI.getLocalAddress(): ", t);
           return null;
        }
     }
  
     private Map<String, String> getData(Fqn<String> fqn)
     {
        if (fqn == null) return null;
        Node<String, String> child = cache.getRoot().getChild(fqn);
        if (child == null) return null;
        return child.getData();
     }
  
  
     private void load(Fqn<String> fqn)
     {
        try
        {
           // this will cause the cache to load the relevant node from a cache loader.
           cache.getRoot().getChild(fqn);
        }
        catch (Throwable t)
        {
           log.error("JBossCacheGUI.load(): " + t);
        }
     }
  
     private void evict(Fqn<String> fqn)
     {
        try
        {
           cache.evict(fqn, true);
        }
        catch (Throwable t)
        {
           log.error("JBossCacheGUI.evict(): " + t);
        }
     }
  
     private void put(Fqn<String> fqn, Map<String, String> m)
     {
        try
        {
           cache.put(fqn, m);
        }
        catch (Throwable t)
        {
           log.error("JBossCacheGUI.put(): " + t);
        }
     }
  
     private void put(Fqn<String> fqn, String key, String value)
     {
        try
        {
           cache.put(fqn, key, value);
        }
        catch (Throwable t)
        {
           log.error("JBossCacheGUI.put(): " + t);
        }
     }
  
     private Set getChildrenNames(Fqn<String> fqn)
     {
        try
        {
           return cache.getRoot().getChild(fqn).getChildrenNames();
        }
        catch (Throwable t)
        {
           log.error("JBossCacheGUI.getChildrenNames(): " + t);
           return null;
        }
     }
  
     private List<Address> getMembers()
     {
        try
        {
           return new ArrayList<Address>(cache.getMembers());
        }
        catch (Throwable t)
        {
           log.error("TreeCacheGui.getMembers(): ", t);
           return null;
        }
     }
  
     /* -------------------------- End of Private Methods ------------------------------ */
  
     /*----------------------- Actions ---------------------------*/
  
     class ExitAction extends AbstractAction
     {
        private static final long serialVersionUID = -5364163916172148038L;
  
        public void actionPerformed(ActionEvent e)
        {
           stopGui();
        }
     }
  
  
     void stopGui()
     {
        if (cache != null)
        {
           try
           {
              cache.stop();
              cache.destroy();
              cache = null;
           }
           catch (Throwable t)
           {
              t.printStackTrace();
           }
        }
        dispose();
        System.exit(0);
     }
  
     class AddNodeAction extends AbstractAction
     {
        private static final long serialVersionUID = 7084928639244438800L;
  
        public void actionPerformed(ActionEvent e)
        {
           JTextField fqnTextField = new JTextField();
           if (selected_node != null)
           {
              System.out.println("Seletcednode to string = " + selected_node.toString());
              fqnTextField.setText(selected_node.toString());
           }
           else
           {
              fqnTextField.setText(Fqn.SEPARATOR);
           }
           Object[] information = {"Enter fully qualified name",
                                   fqnTextField};
           final String btnString1 = "OK";
           final String btnString2 = "Cancel";
           Object[] options = {btnString1, btnString2};
           int userChoice = JOptionPane.showOptionDialog(null,
                                                         information,
                                                         "Add DataNode",
                                                         JOptionPane.YES_NO_OPTION,
                                                         JOptionPane.PLAIN_MESSAGE,
                                                         null,
                                                         options,
                                                         options[0]);
           if (userChoice == 0)
           {
              String userInput = fqnTextField.getText();
              put(Fqn.fromString(userInput), null);
           }
        }
     }
  
     class LoadAction extends AbstractAction
     {
        private static final long serialVersionUID = -6998760732995584428L;
  
        public void actionPerformed(ActionEvent e)
        {
           JTextField fqnTextField = new JTextField();
           if (selected_node != null)
           {
              System.out.println("Seletcednode to string = " + selected_node.toString());
              fqnTextField.setText(selected_node.toString());
           }
           else
           {
              fqnTextField.setText(Fqn.SEPARATOR);
           }
  
           Object[] information = {"Enter fully qualified name",
                                   fqnTextField};
           final String btnString1 = "OK";
           final String btnString2 = "Cancel";
           Object[] options = {btnString1, btnString2};
           int userChoice = JOptionPane.showOptionDialog(null,
                                                         information,
                                                         "Load DataNode",
                                                         JOptionPane.YES_NO_OPTION,
                                                         JOptionPane.PLAIN_MESSAGE,
                                                         null,
                                                         options,
                                                         options[0]);
           if (userChoice == 0)
           {
              String userInput = fqnTextField.getText();
              load(Fqn.fromString(userInput));
           }
        }
     }
  
     class EvictAction extends AbstractAction
     {
        private static final long serialVersionUID = 6007500908549034215L;
  
        public void actionPerformed(ActionEvent e)
        {
           JTextField fqnTextField = new JTextField();
           if (selected_node != null)
           {
              System.out.println("Seletcednode to string = " + selected_node.toString());
              fqnTextField.setText(selected_node.toString());
           }
           else
           {
              fqnTextField.setText(Fqn.SEPARATOR);
           }
           Object[] information = {"Enter fully qualified name",
                                   fqnTextField};
           final String btnString1 = "OK";
           final String btnString2 = "Cancel";
           Object[] options = {btnString1, btnString2};
           int userChoice = JOptionPane.showOptionDialog(null,
                                                         information,
                                                         "Evict DataNode",
                                                         JOptionPane.YES_NO_OPTION,
                                                         JOptionPane.PLAIN_MESSAGE,
                                                         null,
                                                         options,
                                                         options[0]);
           if (userChoice == 0)
           {
              String userInput = fqnTextField.getText();
              evict(Fqn.fromString(userInput));
           }
        }
     }
  
  
     class StartTransaction extends AbstractAction
     {
        private static final long serialVersionUID = 7059131008813144857L;
  
        public void actionPerformed(ActionEvent e)
        {
           if (tx_mgr == null)
           {
              log.error("no TransactionManager specified");
              return;
           }
           if (tx != null)
           {
              log.error("transaction is already running: " + tx);
              return;
           }
           try
           {
              tx_mgr.begin();
              tx = tx_mgr.getTransaction();
           }
           catch (Throwable t)
           {
              t.printStackTrace();
           }
        }
     }
  
     class CommitTransaction extends AbstractAction
     {
        private static final long serialVersionUID = 5426108920883879873L;
  
        public void actionPerformed(ActionEvent e)
        {
           if (tx == null)
           {
              log.error("transaction is not running");
              return;
           }
           try
           {
              tx.commit();
           }
           catch (Throwable t)
           {
              t.printStackTrace();
           }
           finally
           {
              tx = null;
           }
        }
     }
  
     class RollbackTransaction extends AbstractAction
     {
        private static final long serialVersionUID = -4836748411400541430L;
  
        public void actionPerformed(ActionEvent e)
        {
           if (tx == null)
           {
              log.error("transaction is not running");
              return;
           }
           try
           {
              tx.rollback();
           }
           catch (Throwable t)
           {
              t.printStackTrace();
           }
           finally
           {
              tx = null;
           }
        }
     }
  
     class PrintLockInfoAction extends AbstractAction
     {
        private static final long serialVersionUID = -2171307516592250436L;
  
        public void actionPerformed(ActionEvent e)
        {
           System.out.println("\n*** lock information ****\n" + ((CacheImpl) cache).printLockInfo());
        }
     }
  
     class RemoveNodeAction extends AbstractAction
     {
        private static final long serialVersionUID = 3746013603940497991L;
  
        public void actionPerformed(ActionEvent e)
        {
           try
           {
              cache.removeNode(selected_node);
           }
           catch (Throwable t)
           {
              log.error("RemoveNodeAction.actionPerformed(): " + t);
           }
        }
     }
  
     class AddModifyDataForNodeAction extends AbstractAction
     {
        private static final long serialVersionUID = -7656592171312920825L;
  
        public void actionPerformed(ActionEvent e)
        {
           Map<String, String> data = getData(selected_node);
           if (data != null && data.size() > 0)
           {
           }
           else
           {
              clearTable();
              data = new HashMap<String, String>();
              data.put("Add Key", "Add Value");
  
           }
           populateTable(data);
           getContentPane().add(tablePanel, BorderLayout.SOUTH);
           validate();
  
        }
     }
  
  
     class MyNode extends DefaultMutableTreeNode
     {
        private static final long serialVersionUID = 4882445905140460053L;
        String name = "<unnamed>";
  
  
        MyNode(String name)
        {
           this.name = name;
        }
  
  
        /**
         * Adds a new node to the view. Intermediary nodes will be created if they don't yet exist.
         * Returns the first node that was created or null if node already existed
         */
        public MyNode add(Fqn<String> fqn)
        {
           MyNode curr, n, ret = null;
  
           if (fqn == null) return null;
           curr = this;
  
           for (String child_name : fqn.peekElements())
           {
              n = curr.findChild(child_name);
              if (n == null)
              {
                 n = new MyNode(child_name);
                 if (ret == null) ret = n;
                 curr.add(n);
              }
              curr = n;
           }
           return ret;
        }
  
  
        /**
         * Removes a node from the view. Child nodes will be removed as well
         */
        public void remove()
        {
           removeFromParent();
        }
  
  
        private MyNode findNode(Fqn<String> fqn)
        {
           MyNode curr, n;
  
           if (fqn == null) return null;
           curr = this;
  
           for (String child_name : fqn.peekElements())
           {
              n = curr.findChild(child_name);
              if (n == null)
              {
                 return null;
              }
              curr = n;
           }
           return curr;
        }
  
  
        private MyNode findChild(String relative_name)
        {
           MyNode child;
  
           if (relative_name == null || getChildCount() == 0)
           {
              return null;
           }
           for (int i = 0; i < getChildCount(); i++)
           {
              child = (MyNode) getChildAt(i);
              if (child.name == null)
              {
                 continue;
              }
  
              if (child.name.equals(relative_name))
              {
                 return child;
              }
           }
           return null;
        }
  
        public String toString()
        {
           return name;
        }
  
     }
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  



More information about the jboss-cvs-commits mailing list