KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > cache > TreeCacheView2


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  * Created on March 25 2003
7  */

8 package org.jboss.cache;
9
10
11 import bsh.Interpreter;
12 import bsh.util.JConsole;
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15 import org.jboss.cache.factories.XmlConfigurationParser;
16 import org.jgroups.View;
17
18 import javax.swing.*;
19 import javax.swing.event.TableModelEvent JavaDoc;
20 import javax.swing.event.TableModelListener JavaDoc;
21 import javax.swing.event.TreeSelectionEvent JavaDoc;
22 import javax.swing.event.TreeSelectionListener JavaDoc;
23 import javax.swing.table.DefaultTableModel JavaDoc;
24 import javax.swing.table.TableColumn JavaDoc;
25 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
26 import javax.swing.tree.DefaultTreeModel JavaDoc;
27 import javax.swing.tree.TreeNode JavaDoc;
28 import javax.swing.tree.TreePath JavaDoc;
29 import javax.swing.tree.TreeSelectionModel JavaDoc;
30 import javax.transaction.Transaction JavaDoc;
31 import javax.transaction.TransactionManager JavaDoc;
32 import java.awt.*;
33 import java.awt.event.ActionEvent JavaDoc;
34 import java.awt.event.MouseAdapter JavaDoc;
35 import java.awt.event.MouseEvent JavaDoc;
36 import java.awt.event.MouseListener JavaDoc;
37 import java.awt.event.WindowEvent JavaDoc;
38 import java.awt.event.WindowListener JavaDoc;
39 import java.io.File JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.Map JavaDoc;
43 import java.util.Set JavaDoc;
44 import java.util.StringTokenizer JavaDoc;
45 import java.util.Vector JavaDoc;
46
47
48 /**
49  * Graphical view of a ReplicatedTree (using the MVC paradigm). An instance of this class needs to be given a
50  * reference to the underlying model (ReplicatedTree) and needs to registers as a ReplicatedTreeListener. Changes
51  * to the cache structure are propagated from the model to the view (via ReplicatedTreeListener), changes from the
52  * GUI (e.g. by a user) are executed on the cache model (which will broadcast the changes to all replicas).<p>
53  * The view itself caches only the nodes, but doesn't cache any of the data (HashMap) associated with it. When
54  * data needs to be displayed, the underlying cache will be accessed directly.
55  *
56  * @version $Revision: 1.20 $
57  */

58 public class TreeCacheView2
59 {
60    static TreeCacheGui2 gui_ = null;
61    static boolean useConsole = false;
62    CacheImpl cache_ = null;
63    static Log log_ = LogFactory.getLog(TreeCacheView2.class.getName());
64
65    public TreeCacheView2(CacheImpl cache) throws Exception JavaDoc
66    {
67       this.cache_ = cache;
68    }
69
70    public static void setCache(CacheImpl cache)
71    {
72       gui_.setCache(cache);
73    }
74
75    public void start() throws Exception JavaDoc
76    {
77       if (gui_ == null)
78       {
79          log_.info("start(): creating the GUI");
80          System.out.println("start(): creating the GUI");
81          gui_ = new TreeCacheGui2(cache_);
82       }
83    }
84
85    public void stop()
86    {
87       if (gui_ != null)
88       {
89          log_.info("stop(): disposing the GUI");
90          gui_.stopGui();
91          gui_ = null;
92       }
93    }
94
95    void populateTree(String JavaDoc dir) throws Exception JavaDoc
96    {
97       File JavaDoc file = new File JavaDoc(dir);
98
99       if (!file.exists()) return;
100
101       put(dir, null);
102
103       if (file.isDirectory())
104       {
105          String JavaDoc[] children = file.list();
106          if (children != null && children.length > 0)
107          {
108             for (int i = 0; i < children.length; i++)
109                populateTree(dir + "/" + children[i]);
110          }
111       }
112    }
113
114    void put(String JavaDoc fqn, Map JavaDoc m)
115    {
116       try
117       {
118          cache_.put(fqn, m);
119       }
120       catch (Throwable JavaDoc t)
121       {
122          log_.error("TreeCacheView2.put(): " + t);
123       }
124    }
125
126    public static void main(String JavaDoc args[])
127    {
128       CacheImpl cache = null;
129       TreeCacheView2 demo;
130       String JavaDoc start_directory = null;
131       String JavaDoc resource = "META-INF/replSync-service.xml";
132
133       for (int i = 0; i < args.length; i++)
134       {
135          if (args[i].equals("-console"))
136          {
137             useConsole = true;
138             continue;
139          }
140          if (args[i].equals("-config"))
141          {
142             resource = args[++i];
143             continue;
144          }
145          help();
146          return;
147       }
148
149       try
150       {
151          if (useConsole)
152          {
153             demo = new TreeCacheView2(null);
154             demo.start();
155          }
156          else
157          {
158             cache = new CacheImpl();
159             cache.setConfiguration(new XmlConfigurationParser().parseFile(resource));
160
161             cache.start();
162 // cache.getNotifier().addCacheListener(new TreeCacheView.MyListener());
163
demo = new TreeCacheView2(cache);
164             demo.start();
165             if (start_directory != null && start_directory.length() > 0)
166             {
167                demo.populateTree(start_directory);
168             }
169          }
170       }
171       catch (Exception JavaDoc ex)
172       {
173          ex.printStackTrace();
174       }
175    }
176
177    static void help()
178    {
179       System.out.println("TreeCacheView [-help] " +
180               "[-mbean_name <name of CacheImpl MBean>] " +
181               "[-start_directory <dirname>] [-props <props>] " +
182               "[-use_queue <true/false>] [-queue_interval <ms>] [-console]" +
183               "[-queue_max_elements <num>]");
184    }
185
186 }
187
188 class ShutdownThread extends Thread JavaDoc
189 {
190    CacheImpl cache = null;
191
192    ShutdownThread(CacheImpl cache)
193    {
194       this.cache = cache;
195    }
196
197    public void run()
198    {
199       cache.stop();
200    }
201 }
202
203 class TreeCacheGui2 extends JFrame implements WindowListener JavaDoc, CacheListener,
204         TreeSelectionListener JavaDoc, TableModelListener JavaDoc
205 {
206    private static final long serialVersionUID = -1242167331988194987L;
207
208    CacheImpl cache_;
209    DefaultTreeModel JavaDoc tree_model = null;
210    Log log = LogFactory.getLog(getClass());
211    JTree jtree = null;
212    DefaultTableModel JavaDoc table_model = new DefaultTableModel JavaDoc();
213    JTable table = new JTable(table_model);
214    MyNode root = new MyNode(SEP);
215    String JavaDoc props = null;
216    String JavaDoc selected_node = null;
217    JPanel tablePanel = null;
218    JMenu operationsMenu = null;
219    JPopupMenu operationsPopup = null;
220    JMenuBar menubar = null;
221    boolean use_system_exit = false;
222    static String JavaDoc SEP = Fqn.SEPARATOR;
223    private static final int KEY_COL_WIDTH = 20;
224    private static final int VAL_COL_WIDTH = 300;
225    final String JavaDoc STRING = String JavaDoc.class.getName();
226    final String JavaDoc MAP = Map JavaDoc.class.getName();
227    final String JavaDoc OBJECT = Object JavaDoc.class.getName();
228    TransactionManager JavaDoc tx_mgr = null;
229    Transaction JavaDoc tx = null;
230    JPanel mainPanel;
231
232
233    public TreeCacheGui2(CacheImpl cache) throws Exception JavaDoc
234    {
235       addNotify();
236
237       tree_model = new DefaultTreeModel JavaDoc(root);
238       jtree = new JTree(tree_model);
239       jtree.setDoubleBuffered(true);
240       jtree.getSelectionModel().setSelectionMode(
241               TreeSelectionModel.SINGLE_TREE_SELECTION);
242
243       JScrollPane scroll_pane = new JScrollPane(jtree);
244       mainPanel = new JPanel();
245       mainPanel.setLayout(new BorderLayout());
246       mainPanel.add(scroll_pane, BorderLayout.CENTER);
247
248       addWindowListener(this);
249
250       table_model.setColumnIdentifiers(new String JavaDoc[]{"Name", "Value"});
251       table_model.addTableModelListener(this);
252
253       setTableColumnWidths();
254
255       tablePanel = new JPanel();
256       tablePanel.setLayout(new BorderLayout());
257       tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
258       tablePanel.add(table, BorderLayout.CENTER);
259
260       mainPanel.add(tablePanel, BorderLayout.SOUTH);
261       JSplitPane contentPanel = null;
262       if (TreeCacheView2.useConsole)
263       {
264          JConsole bshConsole = new JConsole();
265          Interpreter interpreter = new Interpreter(bshConsole);
266          interpreter.getNameSpace().importCommands("org.jboss.cache.util");
267          interpreter.setShowResults(!interpreter.getShowResults()); // show();
268
//System.setIn(bshConsole.getInputStream());
269
System.setOut(bshConsole.getOut());
270          System.setErr(bshConsole.getErr());
271          Thread JavaDoc t = new Thread JavaDoc(interpreter);
272          t.start();
273
274          contentPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanel, bshConsole);
275          getContentPane().add(contentPanel);
276       }
277       else
278       {
279          getContentPane().add(mainPanel);
280       }
281       jtree.addTreeSelectionListener(this);// REVISIT
282

283       MouseListener JavaDoc ml = new MouseAdapter JavaDoc()
284       {
285          public void mouseClicked(MouseEvent JavaDoc e)
286          {
287             int selRow = jtree.getRowForLocation(e.getX(), e.getY());
288             TreePath JavaDoc selPath = jtree.getPathForLocation(e.getX(), e.getY());
289             if (selRow != -1)
290             {
291                selected_node = makeFQN(selPath.getPath());
292                jtree.setSelectionPath(selPath);
293
294                if (e.getModifiers() == java.awt.event.InputEvent.BUTTON3_MASK)
295                {
296                   operationsPopup.show(e.getComponent(), e.getX(), e
297                           .getY());
298                }
299             }
300          }
301       };
302
303       jtree.addMouseListener(ml);
304
305       createMenus();
306       setLocation(50, 50);
307       setSize(getInsets().left + getInsets().right + 485, getInsets().top
308               + getInsets().bottom + 367);
309
310       init();
311       setCache(cache);
312       setVisible(true);
313
314       if (TreeCacheView2.useConsole)
315       {
316          //has to be called after setVisible() otherwise no effect
317
contentPanel.setDividerLocation(0.65);
318       }
319    }
320
321    public void setCache(CacheImpl cache)
322    {
323       cache_ = cache;
324       if (cache_ != null)
325       {
326          Runtime.getRuntime().addShutdownHook(new ShutdownThread(cache));
327          cache_.getNotifier().addCacheListener(this);
328          setTitle("TreeCacheGui2: mbr=" + getLocalAddress());
329          tx_mgr = cache_.getTransactionManager();
330          populateTree();
331       }
332       else
333       {
334          setTitle("Cache undefined");
335          if (tree_model != null)
336          {
337             root = new MyNode(SEP);
338             tree_model.setRoot(root);
339             tree_model.reload();
340
341          }
342          if (table_model != null)
343          {
344             clearTable();
345          }
346       }
347    }
348
349    void setSystemExit(boolean flag)
350    {
351       use_system_exit = flag;
352    }
353
354    public void windowClosed(WindowEvent JavaDoc event)
355    {
356    }
357
358    public void windowDeiconified(WindowEvent JavaDoc event)
359    {
360    }
361
362    public void windowIconified(WindowEvent JavaDoc event)
363    {
364    }
365
366    public void windowActivated(WindowEvent JavaDoc event)
367    {
368    }
369
370    public void windowDeactivated(WindowEvent JavaDoc event)
371    {
372    }
373
374    public void windowOpened(WindowEvent JavaDoc event)
375    {
376    }
377
378    public void windowClosing(WindowEvent JavaDoc event)
379    {
380       stopGui();
381    }
382
383
384    public void tableChanged(TableModelEvent JavaDoc evt)
385    {
386       int row, col;
387       String JavaDoc key, val;
388
389       if (evt.getType() == TableModelEvent.UPDATE)
390       {
391          row = evt.getFirstRow();
392          col = evt.getColumn();
393          if (col == 0)
394          { // set()
395
key = (String JavaDoc) table_model.getValueAt(row, col);
396             val = (String JavaDoc) table_model.getValueAt(row, col + 1);
397             if (key != null && val != null)
398             {
399                // cache.put(selected_node, key, val);
400

401                try
402                {
403                   cache_.put(selected_node, key, val);
404                }
405                catch (Exception JavaDoc e)
406                {
407                   e.printStackTrace();
408                }
409
410             }
411          }
412          else
413          { // add()
414
key = (String JavaDoc) table_model.getValueAt(row, col - 1);
415             val = (String JavaDoc) table.getValueAt(row, col);
416             if (key != null && val != null)
417             {
418                put(selected_node, key, val);
419             }
420          }
421       }
422    }
423
424
425    public void valueChanged(TreeSelectionEvent JavaDoc evt)
426    {
427       TreePath JavaDoc path = evt.getPath();
428       String JavaDoc fqn = SEP;
429       String JavaDoc component_name;
430       Map JavaDoc data = null;
431
432       for (int i = 0; i < path.getPathCount(); i++)
433       {
434          component_name = ((MyNode) path.getPathComponent(i)).name;
435          if (component_name.equals(SEP))
436             continue;
437          if (fqn.equals(SEP))
438             fqn += component_name;
439          else
440             fqn = fqn + SEP + component_name;
441       }
442       data = getData(fqn);
443       if (data != null)
444       {
445          mainPanel.add(tablePanel, BorderLayout.SOUTH);
446          populateTable(data);
447          validate();
448       }
449       else
450       {
451          clearTable();
452          mainPanel.remove(tablePanel);
453          validate();
454       }
455    }
456
457    /* ------------------ ReplicatedTree.ReplicatedTreeListener interface ------------ */
458
459    public void nodeCreated(Fqn fqn, boolean pre, boolean isLocal)
460    {
461       if (!pre)
462       {
463          MyNode n, p;
464
465          n = root.add(fqn.toString());
466          if (n != null)
467          {
468             p = (MyNode) n.getParent();
469             tree_model.reload(p);
470             jtree.scrollPathToVisible(new TreePath JavaDoc(n.getPath()));
471          }
472       }
473
474    }
475
476    public void nodeModified(Fqn fqn, boolean pre, boolean isLocal, ModificationType modType, Map JavaDoc data)
477    {
478 // data=getData(fqn.toString());
479
// System.out.println("Data modified: fqn: " +fqn + " data: " +data);
480
populateTable(data);
481    }
482
483    public void nodeRemoved(Fqn fqn, boolean pre, boolean isLocal, Map JavaDoc data)
484    {
485       if (!pre)
486       {
487          MyNode n;
488          TreeNode JavaDoc par;
489
490          n = root.findNode(fqn.toString());
491          if (n != null)
492          {
493             n.removeAllChildren();
494             par = n.getParent();
495             n.removeFromParent();
496             tree_model.reload(par);
497          }
498       }
499
500    }
501
502    public void nodeVisited(Fqn fqn, boolean pre)
503    {
504    }
505
506    public void nodeEvicted(Fqn fqn, boolean pre, boolean isLocal)
507    {
508       nodeRemoved(fqn, pre, isLocal, null);
509    }
510
511    public void nodeLoaded(Fqn fqn, boolean pre, Map JavaDoc data)
512    {
513       nodeCreated(fqn, pre, true);
514    }
515
516    public void nodeMoved(Fqn from, Fqn to, boolean pre, boolean isLocal)
517    {
518    }
519
520    public void nodeActivated(Fqn fqn, boolean pre)
521    {
522    }
523
524    public void nodePassivated(Fqn fqn, boolean pre)
525    {
526    }
527
528    public void cacheStarted(CacheSPI cache)
529    {
530    }
531
532    public void cacheStopped(CacheSPI cache)
533    {
534    }
535
536    public void viewChange(final View new_view)
537    {
538       new Thread JavaDoc()
539       {
540          public void run()
541          {
542             Vector JavaDoc mbrship;
543             if (new_view != null && (mbrship = new_view.getMembers()) != null)
544             {
545                _put(SEP, "members", mbrship);
546                _put(SEP, "coordinator", mbrship.firstElement());
547             }
548          }
549       }.start();
550    }
551
552    /* ---------------- End of ReplicatedTree.ReplicatedTreeListener interface -------- */
553
554    /*----------------- Runnable implementation to make View change calles in AWT Thread ---*/
555
556    public void run()
557    {
558
559    }
560
561    /* ----------------------------- Private Methods ---------------------------------- */
562
563    /**
564     * Fetches all data from underlying cache model and display it graphically
565     */

566    void init()
567    {
568       Vector JavaDoc mbrship = null;
569
570       // addGuiNode(SEP);
571
mbrship = getMembers() != null ? (Vector JavaDoc) getMembers().clone() : null;
572       if (mbrship != null && mbrship.size() > 0)
573       {
574          _put(SEP, "members", mbrship);
575          _put(SEP, "coordinator", mbrship.firstElement());
576       }
577    }
578
579
580    /**
581     * Fetches all data from underlying cache model and display it graphically
582     */

583    private void populateTree()
584    {
585       addGuiNode(SEP);
586    }
587
588
589    /**
590     * Recursively adds GUI nodes starting from fqn
591     */

592    void addGuiNode(String JavaDoc fqn)
593    {
594       Set JavaDoc children;
595       String JavaDoc child_name;
596
597       if (fqn == null) return;
598
599       // 1 . Add myself
600
root.add(fqn);
601
602       // 2. Then add my children
603
children = getChildrenNames(fqn);
604       if (children != null)
605       {
606          for (Iterator JavaDoc it = children.iterator(); it.hasNext();)
607          {
608             child_name = it.next().toString();
609             addGuiNode(fqn + SEP + child_name);
610          }
611       }
612    }
613
614
615    String JavaDoc makeFQN(Object JavaDoc[] path)
616    {
617       StringBuffer JavaDoc sb = new StringBuffer JavaDoc("");
618       String JavaDoc tmp_name;
619
620       if (path == null) return null;
621       for (int i = 0; i < path.length; i++)
622       {
623          tmp_name = ((MyNode) path[i]).name;
624          if (tmp_name.equals(SEP))
625             continue;
626          else
627             sb.append(SEP + tmp_name);
628       }
629       tmp_name = sb.toString();
630       if (tmp_name.length() == 0)
631          return SEP;
632       else
633          return tmp_name;
634    }
635
636    void clearTable()
637    {
638       int num_rows = table.getRowCount();
639
640       if (num_rows > 0)
641       {
642          for (int i = 0; i < num_rows; i++)
643             table_model.removeRow(0);
644          table_model.fireTableRowsDeleted(0, num_rows - 1);
645          repaint();
646       }
647    }
648
649
650    void populateTable(Map JavaDoc data)
651    {
652       String JavaDoc key, strval = "<null>";
653       Object JavaDoc val;
654       int num_rows = 0;
655       Map.Entry JavaDoc entry;
656
657       if (data == null) return;
658       num_rows = data.size();
659       clearTable();
660
661       if (num_rows > 0)
662       {
663          for (Iterator JavaDoc it = data.entrySet().iterator(); it.hasNext();)
664          {
665             entry = (Map.Entry JavaDoc) it.next();
666             key = (String JavaDoc) entry.getKey();
667             val = entry.getValue();
668             if (val != null) strval = val.toString();
669             table_model.addRow(new Object JavaDoc[]{key, strval});
670          }
671          table_model.fireTableRowsInserted(0, num_rows - 1);
672          validate();
673       }
674    }
675
676    private void setTableColumnWidths()
677    {
678       table.sizeColumnsToFit(JTable.AUTO_RESIZE_NEXT_COLUMN);
679       TableColumn JavaDoc column = null;
680       column = table.getColumnModel().getColumn(0);
681       column.setMinWidth(KEY_COL_WIDTH);
682       column.setPreferredWidth(KEY_COL_WIDTH);
683       column = table.getColumnModel().getColumn(1);
684       column.setPreferredWidth(VAL_COL_WIDTH);
685    }
686
687    private void createMenus()
688    {
689       menubar = new JMenuBar();
690       operationsMenu = new JMenu("Operations");
691       AddNodeAction addNode = new AddNodeAction();
692       addNode.putValue(AbstractAction.NAME, "Add to this node");
693       LoadAction load_action = new LoadAction();
694       load_action.putValue(AbstractAction.NAME, "Load from the CacheLoader");
695       RemoveNodeAction removeNode = new RemoveNodeAction();
696       removeNode.putValue(AbstractAction.NAME, "Remove this node");
697       EvictAction evict_action = new EvictAction();
698       evict_action.putValue(AbstractAction.NAME, "Evict from the Cache");
699       AddModifyDataForNodeAction addModAction = new AddModifyDataForNodeAction();
700       addModAction.putValue(AbstractAction.NAME, "Add/Modify data");
701       PrintLockInfoAction print_locks = new PrintLockInfoAction();
702       print_locks.putValue(AbstractAction.NAME, "Print lock information (stdout)");
703       ReleaseAllLocksAction release_locks = new ReleaseAllLocksAction();
704       release_locks.putValue(AbstractAction.NAME, "Release all locks");
705       ExitAction exitAction = new ExitAction();
706       exitAction.putValue(AbstractAction.NAME, "Exit");
707       StartTransaction start_tx = new StartTransaction();
708       start_tx.putValue(AbstractAction.NAME, "Start TX");
709       CommitTransaction commit_tx = new CommitTransaction();
710       commit_tx.putValue(AbstractAction.NAME, "Commit TX");
711       RollbackTransaction rollback_tx = new RollbackTransaction();
712       rollback_tx.putValue(AbstractAction.NAME, "Rollback TX");
713       operationsMenu.add(addNode);
714       operationsMenu.add(load_action);
715       operationsMenu.add(removeNode);
716       operationsMenu.add(evict_action);
717       operationsMenu.add(addModAction);
718       operationsMenu.add(print_locks);
719       operationsMenu.add(release_locks);
720       operationsMenu.add(start_tx);
721       operationsMenu.add(commit_tx);
722       operationsMenu.add(rollback_tx);
723       operationsMenu.add(exitAction);
724       menubar.add(operationsMenu);
725       setJMenuBar(menubar);
726
727       operationsPopup = new JPopupMenu();
728       operationsPopup.add(addNode);
729       operationsPopup.add(load_action);
730       operationsPopup.add(evict_action);
731       operationsPopup.add(removeNode);
732       operationsPopup.add(addModAction);
733    }
734
735    Object JavaDoc getLocalAddress()
736    {
737       try
738       {
739          return cache_.getLocalAddress();
740       }
741       catch (Throwable JavaDoc t)
742       {
743          log.error("TreeCacheGui2.getLocalAddress(): " + t);
744          return null;
745       }
746    }
747
748    Map JavaDoc getData(String JavaDoc fqn)
749    {
750       Map JavaDoc data;
751       Set JavaDoc keys;
752       String JavaDoc key;
753       Object JavaDoc value;
754
755       if (fqn == null) return null;
756       keys = getKeys(fqn);
757       if (keys == null) return null;
758       data = new HashMap JavaDoc();
759       for (Iterator JavaDoc it = keys.iterator(); it.hasNext();)
760       {
761          key = (String JavaDoc) it.next();
762          value = get(fqn, key);
763          if (value != null)
764             data.put(key, value);
765       }
766       return data;
767    }
768
769
770    void load(String JavaDoc fqn)
771    {
772       try
773       {
774          cache_.load(fqn);
775       }
776       catch (Throwable JavaDoc t)
777       {
778          log.error("TreeCacheGui2.load(): " + t);
779       }
780    }
781
782    void evict(String JavaDoc fqn)
783    {
784       try
785       {
786          cache_.evict(Fqn.fromString(fqn));
787       }
788       catch (Throwable JavaDoc t)
789       {
790          log.error("TreeCacheGui2.evict(): " + t);
791       }
792    }
793
794    void put(String JavaDoc fqn, Map JavaDoc m)
795    {
796       try
797       {
798          cache_.put(fqn, m);
799       }
800       catch (Throwable JavaDoc t)
801       {
802          log.error("TreeCacheGui2.put(): " + t);
803       }
804    }
805
806    void _put(String JavaDoc fqn, Map JavaDoc m)
807    {
808       try
809       {
810          cache_._put(null, fqn, m, false);
811       }
812       catch (Throwable JavaDoc t)
813       {
814          log.error("TreeCacheGui2._put(): " + t);
815       }
816    }
817
818    void put(String JavaDoc fqn, String JavaDoc key, Object JavaDoc value)
819    {
820       try
821       {
822          cache_.put(fqn, key, value);
823       }
824       catch (Throwable JavaDoc t)
825       {
826          log.error("TreeCacheGui2.put(): " + t);
827       }
828    }
829
830    void _put(String JavaDoc fqn, String JavaDoc key, Object JavaDoc value)
831    {
832       try
833       {
834          cache_._put(null, fqn, key, value, false);
835       }
836       catch (Throwable JavaDoc t)
837       {
838          log.error("TreeCacheGui2._put(): " + t);
839       }
840    }
841
842    Set JavaDoc getKeys(String JavaDoc fqn)
843    {
844       try
845       {
846          return cache_.getKeys(fqn);
847       }
848       catch (Throwable JavaDoc t)
849       {
850          log.error("TreeCacheGui2.getKeys(): " + t);
851          return null;
852       }
853    }
854
855    Object JavaDoc get(String JavaDoc fqn, String JavaDoc key)
856    {
857       try
858       {
859          return cache_.get(fqn, key);
860       }
861       catch (Throwable JavaDoc t)
862       {
863          log.error("TreeCacheGui2.get(): " + t);
864          return null;
865       }
866    }
867
868    Set JavaDoc getChildrenNames(String JavaDoc fqn)
869    {
870       try
871       {
872          return cache_.getChildrenNames(fqn);
873       }
874       catch (Throwable JavaDoc t)
875       {
876          log.error("TreeCacheGui2.getChildrenNames(): " + t);
877          return null;
878       }
879    }
880
881    Vector JavaDoc getMembers()
882    {
883       try
884       {
885          return cache_.getMembers();
886       }
887       catch (Throwable JavaDoc t)
888       {
889          log.error("TreeCacheGui.getMembers(): " + t);
890          return null;
891       }
892    }
893
894    /* -------------------------- End of Private Methods ------------------------------ */
895
896    /*----------------------- Actions ---------------------------*/
897
898    class ExitAction extends AbstractAction
899    {
900       private static final long serialVersionUID = -5364163916172148038L;
901
902       public void actionPerformed(ActionEvent JavaDoc e)
903       {
904          stopGui();
905       }
906    }
907
908
909    void stopGui()
910    {
911       if (cache_ != null)
912       {
913          try
914          {
915             cache_.stop();
916             cache_.destroy();
917             cache_ = null;
918          }
919          catch (Throwable JavaDoc t)
920          {
921             t.printStackTrace();
922          }
923       }
924       dispose();
925       System.exit(0);
926    }
927
928    class AddNodeAction extends AbstractAction
929    {
930       private static final long serialVersionUID = 7084928639244438800L;
931
932       public void actionPerformed(ActionEvent JavaDoc e)
933       {
934          JTextField fqnTextField = new JTextField();
935          if (selected_node != null)
936             fqnTextField.setText(selected_node);
937          Object JavaDoc[] information = {"Enter fully qualified name",
938                  fqnTextField};
939          final String JavaDoc btnString1 = "OK";
940          final String JavaDoc btnString2 = "Cancel";
941          Object JavaDoc[] options = {btnString1, btnString2};
942          int userChoice = JOptionPane.showOptionDialog(null,
943                  information,
944                  "Add DataNode",
945                  JOptionPane.YES_NO_OPTION,
946                  JOptionPane.PLAIN_MESSAGE,
947                  null,
948                  options,
949                  options[0]);
950          if (userChoice == 0)
951          {
952             String JavaDoc userInput = fqnTextField.getText();
953             put(userInput, null);
954          }
955       }
956    }
957
958    class LoadAction extends AbstractAction
959    {
960       private static final long serialVersionUID = -6998760732995584428L;
961
962       public void actionPerformed(ActionEvent JavaDoc e)
963       {
964          JTextField fqnTextField = new JTextField();
965          if (selected_node != null)
966             fqnTextField.setText(selected_node);
967          Object JavaDoc[] information = {"Enter fully qualified name",
968                  fqnTextField};
969          final String JavaDoc btnString1 = "OK";
970          final String JavaDoc btnString2 = "Cancel";
971          Object JavaDoc[] options = {btnString1, btnString2};
972          int userChoice = JOptionPane.showOptionDialog(null,
973                  information,
974                  "Load DataNode",
975                  JOptionPane.YES_NO_OPTION,
976                  JOptionPane.PLAIN_MESSAGE,
977                  null,
978                  options,
979                  options[0]);
980          if (userChoice == 0)
981          {
982             String JavaDoc userInput = fqnTextField.getText();
983             load(userInput);
984          }
985       }
986    }
987
988    class EvictAction extends AbstractAction
989    {
990       private static final long serialVersionUID = 6007500908549034215L;
991
992       public void actionPerformed(ActionEvent JavaDoc e)
993       {
994          JTextField fqnTextField = new JTextField();
995          if (selected_node != null)
996             fqnTextField.setText(selected_node);
997          Object JavaDoc[] information = {"Enter fully qualified name",
998                  fqnTextField};
999          final String JavaDoc btnString1 = "OK";
1000         final String JavaDoc btnString2 = "Cancel";
1001         Object JavaDoc[] options = {btnString1, btnString2};
1002         int userChoice = JOptionPane.showOptionDialog(null,
1003                 information,
1004                 "Evict DataNode",
1005                 JOptionPane.YES_NO_OPTION,
1006                 JOptionPane.PLAIN_MESSAGE,
1007                 null,
1008                 options,
1009                 options[0]);
1010         if (userChoice == 0)
1011         {
1012            String JavaDoc userInput = fqnTextField.getText();
1013            evict(userInput);
1014         }
1015      }
1016   }
1017
1018
1019   class StartTransaction extends AbstractAction
1020   {
1021      private static final long serialVersionUID = 7059131008813144857L;
1022
1023      public void actionPerformed(ActionEvent JavaDoc e)
1024      {
1025         if (tx_mgr == null)
1026         {
1027            log.error("no TransactionManager specified");
1028            return;
1029         }
1030         if (tx != null)
1031         {
1032            log.error("transaction is already running: " + tx);
1033            return;
1034         }
1035         try
1036         {
1037            tx_mgr.begin();
1038            tx = tx_mgr.getTransaction();
1039         }
1040         catch (Throwable JavaDoc t)
1041         {
1042            t.printStackTrace();
1043         }
1044      }
1045   }
1046
1047   class CommitTransaction extends AbstractAction
1048   {
1049      private static final long serialVersionUID = 5426108920883879873L;
1050
1051      public void actionPerformed(ActionEvent JavaDoc e)
1052      {
1053         if (tx == null)
1054         {
1055            log.error("transaction is not running");
1056            return;
1057         }
1058         try
1059         {
1060            tx.commit();
1061         }
1062         catch (Throwable JavaDoc t)
1063         {
1064            t.printStackTrace();
1065         }
1066         finally
1067         {
1068            tx = null;
1069         }
1070      }
1071   }
1072
1073   class RollbackTransaction extends AbstractAction
1074   {
1075      private static final long serialVersionUID = -4836748411400541430L;
1076
1077      public void actionPerformed(ActionEvent JavaDoc e)
1078      {
1079         if (tx == null)
1080         {
1081            log.error("transaction is not running");
1082            return;
1083         }
1084         try
1085         {
1086            tx.rollback();
1087         }
1088         catch (Throwable JavaDoc t)
1089         {
1090            t.printStackTrace();
1091         }
1092         finally
1093         {
1094            tx = null;
1095         }
1096      }
1097   }
1098
1099   class PrintLockInfoAction extends AbstractAction
1100   {
1101      private static final long serialVersionUID = -2171307516592250436L;
1102
1103      public void actionPerformed(ActionEvent JavaDoc e)
1104      {
1105         System.out.println("\n*** lock information ****\n" + cache_.printLockInfo());
1106      }
1107   }
1108
1109   class ReleaseAllLocksAction extends AbstractAction
1110   {
1111      private static final long serialVersionUID = 6894888234400908985L;
1112
1113      public void actionPerformed(ActionEvent JavaDoc e)
1114      {
1115         cache_.releaseAllLocks("/");
1116      }
1117   }
1118
1119   class RemoveNodeAction extends AbstractAction
1120   {
1121      private static final long serialVersionUID = 3746013603940497991L;
1122
1123      public void actionPerformed(ActionEvent JavaDoc e)
1124      {
1125         try
1126         {
1127            cache_.remove(selected_node);
1128         }
1129         catch (Throwable JavaDoc t)
1130         {
1131            log.error("RemoveNodeAction.actionPerformed(): " + t);
1132         }
1133      }
1134   }
1135
1136   class AddModifyDataForNodeAction extends AbstractAction
1137   {
1138      private static final long serialVersionUID = -7656592171312920825L;
1139
1140      public void actionPerformed(ActionEvent JavaDoc e)
1141      {
1142         Map JavaDoc data = getData(selected_node);
1143         if (data != null && data.size() > 0)
1144         {
1145         }
1146         else
1147         {
1148            clearTable();
1149            data = new HashMap JavaDoc();
1150            data.put("Add Key", "Add Value");
1151
1152         }
1153         populateTable(data);
1154         getContentPane().add(tablePanel, BorderLayout.SOUTH);
1155         validate();
1156
1157      }
1158   }
1159
1160
1161   class MyNode extends DefaultMutableTreeNode JavaDoc
1162   {
1163      private static final long serialVersionUID = 4882445905140460053L;
1164      String JavaDoc name = "<unnamed>";
1165
1166
1167      MyNode(String JavaDoc name)
1168      {
1169         this.name = name;
1170      }
1171
1172
1173      /**
1174       * Adds a new node to the view. Intermediary nodes will be created if they don't yet exist.
1175       * Returns the first node that was created or null if node already existed
1176       */

1177      public MyNode add(String JavaDoc fqn)
1178      {
1179         MyNode curr, n, ret = null;
1180         StringTokenizer JavaDoc tok;
1181         String JavaDoc child_name;
1182
1183         if (fqn == null) return null;
1184         curr = this;
1185         tok = new StringTokenizer JavaDoc(fqn, TreeCacheGui2.SEP);
1186
1187         while (tok.hasMoreTokens())
1188         {
1189            child_name = tok.nextToken();
1190            n = curr.findChild(child_name);
1191            if (n == null)
1192            {
1193               n = new MyNode(child_name);
1194               if (ret == null) ret = n;
1195               curr.add(n);
1196            }
1197            curr = n;
1198         }
1199         return ret;
1200      }
1201
1202
1203      /**
1204       * Removes a node from the view. Child nodes will be removed as well
1205       */

1206      public void remove(String JavaDoc fqn)
1207      {
1208         removeFromParent();
1209      }
1210
1211
1212      MyNode findNode(String JavaDoc fqn)
1213      {
1214         MyNode curr, n;
1215         StringTokenizer JavaDoc tok;
1216         String JavaDoc child_name;
1217
1218         if (fqn == null) return null;
1219         curr = this;
1220         tok = new StringTokenizer JavaDoc(fqn, TreeCacheGui2.SEP);
1221
1222         while (tok.hasMoreTokens())
1223         {
1224            child_name = tok.nextToken();
1225            n = curr.findChild(child_name);
1226            if (n == null)
1227               return null;
1228            curr = n;
1229         }
1230         return curr;
1231      }
1232
1233
1234      MyNode findChild(String JavaDoc relative_name)
1235      {
1236         MyNode child;
1237
1238         if (relative_name == null || getChildCount() == 0)
1239            return null;
1240         for (int i = 0; i < getChildCount(); i++)
1241         {
1242            child = (MyNode) getChildAt(i);
1243            if (child.name == null)
1244            {
1245               continue;
1246            }
1247
1248            if (child.name.equals(relative_name))
1249               return child;
1250         }
1251         return null;
1252      }
1253
1254
1255      String JavaDoc print(int indent)
1256      {
1257         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1258
1259         for (int i = 0; i < indent; i++)
1260            sb.append(" ");
1261         if (!isRoot())
1262         {
1263            if (name == null)
1264               sb.append("/<unnamed>");
1265            else
1266            {
1267               sb.append(TreeCacheGui2.SEP + name);
1268            }
1269         }
1270         sb.append("\n");
1271         if (getChildCount() > 0)
1272         {
1273            if (isRoot())
1274               indent = 0;
1275            else
1276               indent += 4;
1277            for (int i = 0; i < getChildCount(); i++)
1278               sb.append(((MyNode) getChildAt(i)).print(indent));
1279         }
1280         return sb.toString();
1281      }
1282
1283
1284      public String JavaDoc toString()
1285      {
1286         return name;
1287      }
1288
1289   }
1290}
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
Popular Tags