KickJava   Java API By Example, From Geeks To Geeks.

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


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 org.apache.commons.logging.Log;
12 import org.apache.commons.logging.LogFactory;
13 import org.jboss.cache.config.Configuration;
14 import org.jgroups.View;
15
16 import javax.management.MBeanServer JavaDoc;
17 import javax.management.MBeanServerFactory JavaDoc;
18 import javax.management.ObjectName JavaDoc;
19 import javax.swing.*;
20 import javax.swing.event.TableModelEvent JavaDoc;
21 import javax.swing.event.TableModelListener JavaDoc;
22 import javax.swing.event.TreeSelectionEvent JavaDoc;
23 import javax.swing.event.TreeSelectionListener JavaDoc;
24 import javax.swing.table.DefaultTableModel JavaDoc;
25 import javax.swing.table.TableColumn JavaDoc;
26 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
27 import javax.swing.tree.DefaultTreeModel JavaDoc;
28 import javax.swing.tree.TreeNode JavaDoc;
29 import javax.swing.tree.TreePath JavaDoc;
30 import javax.swing.tree.TreeSelectionModel JavaDoc;
31 import java.awt.*;
32 import java.awt.event.ActionEvent JavaDoc;
33 import java.awt.event.MouseAdapter JavaDoc;
34 import java.awt.event.MouseEvent JavaDoc;
35 import java.awt.event.MouseListener JavaDoc;
36 import java.awt.event.WindowEvent JavaDoc;
37 import java.awt.event.WindowListener JavaDoc;
38 import java.io.File JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Map JavaDoc;
44 import java.util.Set 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.21 $
57  * @author<a HREF="mailto:bela@jboss.org">Bela Ban</a> March 27 2003
58  */

59 public class TreeCacheView implements TreeCacheViewMBean
60 {
61    /**
62     * Reference to the CacheImpl MBean (the model for this view)
63     */

64    ObjectName JavaDoc cache_service = null;
65    TreeCacheGui gui = null;
66    CacheSPI cache;
67    Log log = LogFactory.getLog(TreeCacheView.class);
68
69
70    public TreeCacheView() throws Exception JavaDoc
71    {
72       super();
73       init(null);
74    }
75
76    public TreeCacheView(String JavaDoc cache_service) throws Exception JavaDoc
77    {
78       init(cache_service);
79    }
80
81
82    public void create()
83    {
84    }
85
86    public void start() throws Exception JavaDoc
87    {
88       if (gui == null)
89       {
90          log.info("start(): creating the GUI");
91          gui = new TreeCacheGui(cache);
92       }
93    }
94
95    public void stop()
96    {
97       if (gui != null)
98       {
99          log.info("stop(): disposing the GUI");
100          gui.dispose();
101          gui = null;
102       }
103    }
104
105    /**
106     */

107    public void destroy()
108    {
109    }
110
111    public String JavaDoc getCacheService()
112    {
113       return cache_service != null ? cache_service.toString() : null;
114    }
115
116    /**
117     * @param cache_service
118     * @throws Exception
119     */

120    public void setCacheService(String JavaDoc cache_service) throws Exception JavaDoc
121    {
122       init(cache_service);
123    }
124
125
126    void init(String JavaDoc cache_service) throws Exception JavaDoc
127    {
128       MBeanServer JavaDoc srv = null;
129
130       if (cache_service != null)
131          this.cache_service = new ObjectName JavaDoc(cache_service);
132       else
133          return;
134
135       // is this the right way to get hold of the JBoss MBeanServer ?
136
List JavaDoc servers = MBeanServerFactory.findMBeanServer(null);
137       if (servers == null || servers.size() == 0)
138          throw new Exception JavaDoc("TreeCacheView.init(): no MBeanServers found");
139       srv = (MBeanServer JavaDoc) servers.get(0);
140       log.info("init(): found MBeanServer " + srv);
141       cache = (CacheSPI) srv.getAttribute(this.cache_service, "Cache");
142       System.out.println("Cache " + cache);
143       TreeCacheGui gui = new TreeCacheGui(cache);
144    }
145
146
147    void populateTree(String JavaDoc dir) throws Exception JavaDoc
148    {
149       File JavaDoc file = new File JavaDoc(dir);
150
151       if (!file.exists()) return;
152
153       put(Fqn.fromString(dir), null);
154
155       if (file.isDirectory())
156       {
157          String JavaDoc[] children = file.list();
158          if (children != null && children.length > 0)
159          {
160             for (int i = 0; i < children.length; i++)
161                populateTree(dir + "/" + children[i]);
162          }
163       }
164    }
165
166    void put(Fqn fqn, Map JavaDoc m)
167    {
168       try
169       {
170          cache.put(fqn, m);
171       }
172       catch (Throwable JavaDoc t)
173       {
174          log.error("TreeCacheView.put(): " + t);
175       }
176    }
177
178
179    public static void main(String JavaDoc args[])
180    {
181       CacheImpl cache = null;
182       TreeCacheView demo;
183       String JavaDoc start_directory = null;
184       String JavaDoc mbean_name = "jboss.cache:service=CacheImpl";
185       String JavaDoc props = getDefaultProps();
186       MBeanServer JavaDoc srv;
187       Log log;
188       boolean use_queue = false;
189       int queue_interval = 5000;
190       int queue_max_elements = 100;
191
192
193       for (int i = 0; i < args.length; i++)
194       {
195          if (args[i].equals("-mbean_name"))
196          {
197             mbean_name = args[++i];
198             continue;
199          }
200          if (args[i].equals("-props"))
201          {
202             props = args[++i];
203             continue;
204          }
205          if (args[i].equals("-start_directory"))
206          {
207             start_directory = args[++i];
208             continue;
209          }
210          if (args[i].equals("-use_queue"))
211          {
212             use_queue = true;
213             continue;
214          }
215          if (args[i].equals("-queue_interval"))
216          {
217             queue_interval = Integer.parseInt(args[++i]);
218             use_queue = true;
219             continue;
220          }
221          if (args[i].equals("-queue_max_elements"))
222          {
223             queue_max_elements = Integer.parseInt(args[++i]);
224             use_queue = true;
225             continue;
226          }
227          help();
228          return;
229       }
230
231       try
232       {
233          log = LogFactory.getLog(CacheImpl.class);
234          srv = MBeanServerFactory.createMBeanServer();
235
236 // String FACTORY="org.jboss.cache.transaction.DummyContextFactory";
237
// System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
238
//
239
// DummyTransactionManager.getInstance();
240

241
242          cache = new CacheImpl();
243          Configuration c = new Configuration();
244          c.setClusterName("TreeCacheGroup");
245          c.setClusterConfig(props);
246          c.setInitialStateRetrievalTimeout(10000);
247          c.setCacheMode("REPL_ASYNC");
248
249          if (use_queue)
250          {
251             c.setUseReplQueue(true);
252             c.setReplQueueInterval(queue_interval);
253             c.setReplQueueMaxElements(queue_max_elements);
254          }
255
256          cache.getNotifier().addCacheListener(new MyListener());
257
258          log.info("registering the cache as " + mbean_name);
259          srv.registerMBean(cache.getCacheMBeanInterface(), new ObjectName JavaDoc(mbean_name));
260
261          cache.start();
262
263          Runtime.getRuntime().addShutdownHook(new ShutdownThread(cache));
264
265 // cache.put("/a/b/c", null);
266
// cache.put("/a/b/c1", null);
267
// cache.put("/a/b/c2", null);
268
// cache.put("/a/b1/chat", null);
269
// cache.put("/a/b1/chat2", null);
270
// cache.put("/a/b1/chat5", null);
271

272          demo = new TreeCacheView(mbean_name);
273          demo.create();
274          demo.start();
275          if (start_directory != null && start_directory.length() > 0)
276          {
277             demo.populateTree(start_directory);
278          }
279       }
280       catch (Exception JavaDoc ex)
281       {
282          ex.printStackTrace();
283       }
284    }
285
286    static class ShutdownThread extends Thread JavaDoc
287    {
288       CacheImpl cache = null;
289
290       ShutdownThread(CacheImpl cache)
291       {
292          this.cache = cache;
293       }
294
295       public void run()
296       {
297          cache.stop();
298       }
299    }
300
301    private static String JavaDoc getDefaultProps()
302    {
303       return
304               "UDP(ip_mcast=true;ip_ttl=64;loopback=false;mcast_addr=228.1.2.3;" +
305                       "mcast_port=45566;mcast_recv_buf_size=80000;mcast_send_buf_size=150000;" +
306                       "ucast_recv_buf_size=80000;ucast_send_buf_size=150000):" +
307                       "PING(down_thread=true;num_initial_members=3;timeout=2000;up_thread=true):" +
308                       "MERGE2(max_interval=20000;min_interval=10000):" +
309                       "FD(down_thread=true;shun=true;up_thread=true):" +
310                       "VERIFY_SUSPECT(down_thread=true;timeout=1500;up_thread=true):" +
311                       "pbcast.NAKACK(down_thread=true;gc_lag=50;retransmit_timeout=600,1200,2400,4800;" +
312                       "up_thread=true):" +
313                       "pbcast.STABLE(desired_avg_gossip=20000;down_thread=true;up_thread=true):" +
314                       "UNICAST(down_thread=true;min_threshold=10;timeout=600,1200,2400;window_size=100):" +
315                       "FRAG(down_thread=true;frag_size=8192;up_thread=true):" +
316                       "pbcast.GMS(join_retry_timeout=2000;join_timeout=5000;print_local_addr=true;shun=true):" +
317                       "pbcast.STATE_TRANSFER(down_thread=true;up_thread=true)";
318    }
319
320
321    static void help()
322    {
323       System.out.println("TreeCacheView [-help] " +
324               "[-mbean_name <name of CacheImpl MBean>] " +
325               "[-start_directory <dirname>] [-props <props>] " +
326               "[-use_queue <true/false>] [-queue_interval <ms>] " +
327               "[-queue_max_elements <num>]");
328    }
329
330
331    public static class MyListener extends AbstractCacheListener
332    {
333    }
334
335
336 }
337
338
339 class TreeCacheGui extends JFrame implements WindowListener JavaDoc, CacheListener,
340         TreeSelectionListener JavaDoc, TableModelListener JavaDoc
341 {
342    private static final long serialVersionUID = 8576324868563647538L;
343    CacheSPI cache;
344    DefaultTreeModel JavaDoc tree_model = null;
345    Log log = LogFactory.getLog(getClass());
346    JTree jtree = null;
347    DefaultTableModel JavaDoc table_model = new DefaultTableModel JavaDoc();
348    JTable table = new JTable(table_model);
349    MyNode root = new MyNode(SEP.getLastElementAsString());
350    Fqn selected_node = null;
351    JPanel tablePanel = null;
352    JMenu operationsMenu = null;
353    JPopupMenu operationsPopup = null;
354    JMenuBar menubar = null;
355    static final Fqn SEP = Fqn.ROOT;
356    private static final int KEY_COL_WIDTH = 20;
357    private static final int VAL_COL_WIDTH = 300;
358
359
360    public TreeCacheGui(CacheSPI cache) throws Exception JavaDoc
361    {
362       this.cache = cache;
363
364       //server.invoke(cache_service, "addTreeCacheListener",
365
// new Object[]{this},
366
// new String[]{TreeCacheListener.class.getLastElementAsString()});
367
cache.getNotifier().addCacheListener(this);
368       addNotify();
369       setTitle("TreeCacheGui: mbr=" + getLocalAddress());
370
371       tree_model = new DefaultTreeModel JavaDoc(root);
372       jtree = new JTree(tree_model);
373       jtree.setDoubleBuffered(true);
374       jtree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
375
376       JScrollPane scroll_pane = new JScrollPane(jtree);
377
378       populateTree();
379
380       getContentPane().add(scroll_pane, BorderLayout.CENTER);
381       addWindowListener(this);
382
383       table_model.setColumnIdentifiers(new String JavaDoc[]{"Name", "Value"});
384       table_model.addTableModelListener(this);
385
386       setTableColumnWidths();
387
388       tablePanel = new JPanel();
389       tablePanel.setLayout(new BorderLayout());
390       tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
391       tablePanel.add(table, BorderLayout.CENTER);
392
393       getContentPane().add(tablePanel, BorderLayout.SOUTH);
394
395       jtree.addTreeSelectionListener(this);//REVISIT
396

397       MouseListener JavaDoc ml = new MouseAdapter JavaDoc()
398       {
399          public void mouseClicked(MouseEvent JavaDoc e)
400          {
401             int selRow = jtree.getRowForLocation(e.getX(), e.getY());
402             TreePath JavaDoc selPath = jtree.getPathForLocation(e.getX(), e.getY());
403             if (selRow != -1)
404             {
405                selected_node = makeFQN(selPath.getPath());
406                jtree.setSelectionPath(selPath);
407
408                if (e.getModifiers() == java.awt.event.InputEvent.BUTTON3_MASK)
409                {
410                   operationsPopup.show(e.getComponent(),
411                           e.getX(), e.getY());
412                }
413             }
414          }
415       };
416
417       jtree.addMouseListener(ml);
418
419       createMenus();
420       setLocation(50, 50);
421       setSize(getInsets().left + getInsets().right + 485,
422               getInsets().top + getInsets().bottom + 367);
423
424       init();
425       setVisible(true);
426    }
427
428    void setSystemExit(boolean flag)
429    {
430    }
431
432    public void windowClosed(WindowEvent JavaDoc event)
433    {
434    }
435
436    public void windowDeiconified(WindowEvent JavaDoc event)
437    {
438    }
439
440    public void windowIconified(WindowEvent JavaDoc event)
441    {
442    }
443
444    public void windowActivated(WindowEvent JavaDoc event)
445    {
446    }
447
448    public void windowDeactivated(WindowEvent JavaDoc event)
449    {
450    }
451
452    public void windowOpened(WindowEvent JavaDoc event)
453    {
454    }
455
456    public void windowClosing(WindowEvent JavaDoc event)
457    {
458       dispose();
459    }
460
461
462    public void tableChanged(TableModelEvent JavaDoc evt)
463    {
464       int row, col;
465       String JavaDoc key, val;
466
467       if (evt.getType() == TableModelEvent.UPDATE)
468       {
469          row = evt.getFirstRow();
470          col = evt.getColumn();
471          if (col == 0)
472          { // set()
473
key = (String JavaDoc) table_model.getValueAt(row, col);
474             val = (String JavaDoc) table_model.getValueAt(row, col + 1);
475             if (key != null && val != null)
476             {
477                // cache.put(selected_node, key, val);
478

479 // server.invoke(cache_service, "put",
480
// new Object[]{selected_node, key, val},
481
// new String[]{String.class.getLastElementAsString(),
482
// String.class.getLastElementAsString(), Object.class.getLastElementAsString()});
483
try
484                {
485                   cache.put(selected_node, key, val);
486                }
487                catch (Exception JavaDoc e)
488                {
489                   e.printStackTrace();
490                }
491
492             }
493          }
494          else
495          { // add()
496
key = (String JavaDoc) table_model.getValueAt(row, col - 1);
497             val = (String JavaDoc) table.getValueAt(row, col);
498             if (key != null && val != null)
499             {
500                cache.put(selected_node, key, val);
501             }
502          }
503       }
504    }
505
506
507    public void valueChanged(TreeSelectionEvent JavaDoc evt)
508    {
509       TreePath JavaDoc path = evt.getPath();
510       Fqn fqn = SEP;
511       Object JavaDoc component_name;
512       Map JavaDoc data = null;
513
514       for (int i = 0; i < path.getPathCount(); i++)
515       {
516          component_name = ((MyNode) path.getPathComponent(i)).name;
517          if (component_name.equals("/"))
518             continue;
519          fqn = new Fqn(fqn, component_name);
520       }
521       data = getData(fqn);
522       if (data != null)
523       {
524          getContentPane().add(tablePanel, BorderLayout.SOUTH);
525          populateTable(data);
526          validate();
527       }
528       else
529       {
530          clearTable();
531          getContentPane().remove(tablePanel);
532          validate();
533       }
534    }
535
536    /* ------------------ ReplicatedTree.ReplicatedTreeListener interface ------------ */
537
538    public void nodeCreated(Fqn fqn, boolean pre, boolean isLocal)
539    {
540       if (!pre)
541       {
542          MyNode n, p;
543
544          n = root.add(fqn);
545          if (n != null)
546          {
547             p = (MyNode) n.getParent();
548             tree_model.reload(p);
549             jtree.scrollPathToVisible(new TreePath JavaDoc(n.getPath()));
550          }
551       }
552    }
553
554    public void nodeRemoved(Fqn fqn, boolean pre, boolean isLocal, Map JavaDoc data)
555    {
556       if (!pre)
557       {
558          MyNode n;
559          TreeNode JavaDoc par;
560
561          n = root.findNode(fqn);
562          if (n != null)
563          {
564             n.removeAllChildren();
565             par = n.getParent();
566             n.removeFromParent();
567             tree_model.reload(par);
568          }
569       }
570    }
571
572    public void nodeVisited(Fqn fqn, boolean pre)
573    {
574    }
575
576    public void nodeLoaded(Fqn fqn, boolean pre, Map JavaDoc data)
577    {
578       nodeCreated(fqn, pre, false);
579    }
580
581    public void nodeMoved(Fqn from, Fqn to, boolean pre, boolean isLocal)
582    {
583    }
584
585    public void nodeActivated(Fqn fqn, boolean pre)
586    {
587    }
588
589    public void nodePassivated(Fqn fqn, boolean pre)
590    {
591    }
592
593    public void nodeEvicted(Fqn fqn, boolean pre, boolean isLocal)
594    {
595       nodeRemoved(fqn, pre, isLocal, null);
596    }
597
598    public void nodeModified(Fqn fqn, boolean pre, boolean isLocal, ModificationType modType, Map JavaDoc data)
599    {
600       // Map data;
601
//data=getData(fqn);
602
//populateTable(data); REVISIT
603
/*
604         poulateTable is the current table being shown is the info of the node. that is modified.
605       */

606    }
607
608    public void nodeVisited(Fqn fqn, boolean pre, boolean isLocal)
609    {
610    }
611
612    public void cacheStarted(CacheSPI cache)
613    {
614    }
615
616    public void cacheStopped(CacheSPI cache)
617    {
618    }
619
620    public void viewChange(final View new_view)
621    {
622       new Thread JavaDoc()
623       {
624          public void run()
625          {
626             Vector JavaDoc mbrship;
627             if (new_view != null && (mbrship = new_view.getMembers()) != null)
628             {
629                put(SEP, "members", mbrship);
630                put(SEP, "coordinator", mbrship.firstElement());
631             }
632          }
633       }.start();
634    }
635
636    /* ---------------- End of ReplicatedTree.ReplicatedTreeListener interface -------- */
637
638    /*----------------- Runnable implementation to make View change calles in AWT Thread ---*/
639
640    public void run()
641    {
642
643    }
644
645    /* ----------------------------- Private Methods ---------------------------------- */
646
647    /**
648     * Fetches all data from underlying cache model and display it graphically
649     */

650    void init()
651    {
652       Vector JavaDoc mbrship = null;
653
654       addGuiNode(SEP);
655
656       mbrship = getMembers() != null ? (Vector JavaDoc) getMembers().clone() : null;
657       if (mbrship != null && mbrship.size() > 0)
658       {
659          put(SEP, "members", mbrship);
660          put(SEP, "coordinator", mbrship.firstElement());
661       }
662    }
663
664
665    /**
666     * Fetches all data from underlying cache model and display it graphically
667     */

668    private void populateTree()
669    {
670       addGuiNode(SEP);
671    }
672
673
674    /**
675     * Recursively adds GUI nodes starting from fqn
676     */

677    void addGuiNode(Fqn fqn)
678    {
679       Set JavaDoc children;
680
681       if (fqn == null) return;
682
683       // 1 . Add myself
684
root.add(fqn);
685
686       // 2. Then add my children
687
children = getChildrenNames(fqn);
688       for (Object JavaDoc o : children)
689       {
690          addGuiNode(new Fqn(fqn, o));
691       }
692    }
693
694
695    Fqn makeFQN(Object JavaDoc[] opath)
696    {
697       List JavaDoc l = new ArrayList JavaDoc();
698       for (Object JavaDoc o : opath)
699       {
700          MyNode node = (MyNode) o;
701          Object JavaDoc name = node.name;
702          if (name.equals(Fqn.SEPARATOR))
703             continue;
704          l.add(name);
705       }
706       System.out.println(" L " + l);
707       return new Fqn(l);
708    }
709
710    void clearTable()
711    {
712       int num_rows = table.getRowCount();
713
714       if (num_rows > 0)
715       {
716          for (int i = 0; i < num_rows; i++)
717             table_model.removeRow(0);
718          table_model.fireTableRowsDeleted(0, num_rows - 1);
719          repaint();
720       }
721    }
722
723
724    void populateTable(Map JavaDoc data)
725    {
726       String JavaDoc key, strval = "<null>";
727       Object JavaDoc val;
728       int num_rows = 0;
729       Map.Entry JavaDoc entry;
730
731       if (data == null) return;
732       num_rows = data.size();
733       clearTable();
734
735       if (num_rows > 0)
736       {
737          for (Iterator JavaDoc it = data.entrySet().iterator(); it.hasNext();)
738          {
739             entry = (Map.Entry JavaDoc) it.next();
740             key = (String JavaDoc) entry.getKey();
741             val = entry.getValue();
742             if (val != null) strval = val.toString();
743             table_model.addRow(new Object JavaDoc[]{key, strval});
744          }
745          table_model.fireTableRowsInserted(0, num_rows - 1);
746          validate();
747       }
748    }
749
750    private void setTableColumnWidths()
751    {
752       table.sizeColumnsToFit(JTable.AUTO_RESIZE_NEXT_COLUMN);
753       TableColumn JavaDoc column = null;
754       column = table.getColumnModel().getColumn(0);
755       column.setMinWidth(KEY_COL_WIDTH);
756       column.setPreferredWidth(KEY_COL_WIDTH);
757       column = table.getColumnModel().getColumn(1);
758       column.setPreferredWidth(VAL_COL_WIDTH);
759    }
760
761    private void createMenus()
762    {
763       menubar = new JMenuBar();
764       operationsMenu = new JMenu("Operations");
765       AddNodeAction addNode = new AddNodeAction();
766       addNode.putValue(AbstractAction.NAME, "Add to this node");
767       RemoveNodeAction removeNode = new RemoveNodeAction();
768       removeNode.putValue(AbstractAction.NAME, "Remove this node");
769       AddModifyDataForNodeAction addModAction = new AddModifyDataForNodeAction();
770       addModAction.putValue(AbstractAction.NAME, "Add/Modify data");
771       PrintLockInfoAction print_locks = new PrintLockInfoAction();
772       print_locks.putValue(AbstractAction.NAME, "Print lock information (stdout)");
773       ReleaseAllLocksAction release_locks = new ReleaseAllLocksAction();
774       release_locks.putValue(AbstractAction.NAME, "Release all locks");
775       ExitAction exitAction = new ExitAction();
776       exitAction.putValue(AbstractAction.NAME, "Exit");
777       operationsMenu.add(addNode);
778       operationsMenu.add(removeNode);
779       operationsMenu.add(addModAction);
780       operationsMenu.add(print_locks);
781       operationsMenu.add(release_locks);
782       operationsMenu.add(exitAction);
783       menubar.add(operationsMenu);
784       setJMenuBar(menubar);
785
786       operationsPopup = new JPopupMenu();
787       operationsPopup.add(addNode);
788       operationsPopup.add(removeNode);
789       operationsPopup.add(addModAction);
790    }
791
792    Object JavaDoc getLocalAddress()
793    {
794       try
795       {
796          return cache.getLocalAddress();
797       }
798       catch (Throwable JavaDoc t)
799       {
800          log.error("TreeCacheGui.getLocalAddress(): " + t);
801          return null;
802       }
803    }
804
805    Map JavaDoc getData(Fqn fqn)
806    {
807       Node n = cache.getRoot().getChild(fqn);
808       if (n == null)
809       {
810          return null;
811       }
812       return n.getData();
813    }
814
815
816    void put(Fqn fqn, Map JavaDoc m)
817    {
818       try
819       {
820          cache.put(fqn, m);
821       }
822       catch (Throwable JavaDoc t)
823       {
824          log.error("TreeCacheGui.put(): " + t);
825       }
826    }
827
828
829    void put(Fqn fqn, String JavaDoc key, Object JavaDoc value)
830    {
831       try
832       {
833          cache.put(fqn, key, value);
834       }
835       catch (Throwable JavaDoc t)
836       {
837          log.error("TreeCacheGui.put(): " + t);
838       }
839    }
840
841    Set JavaDoc getKeys(Fqn fqn)
842    {
843       try
844       {
845          return cache.getRoot().getChild(fqn).getKeys();
846       }
847       catch (Throwable JavaDoc t)
848       {
849          log.error("TreeCacheGui.getKeys(): " + t);
850          return null;
851       }
852    }
853
854    Object JavaDoc get(Fqn fqn, String JavaDoc key)
855    {
856       try
857       {
858          return cache.getRoot().getChild(fqn).getData().get(key);
859       }
860       catch (Throwable JavaDoc t)
861       {
862          log.error("TreeCacheGui.get(): " + t);
863          return null;
864       }
865    }
866
867    Set JavaDoc getChildrenNames(Fqn fqn)
868    {
869       try
870       {
871          Node n = cache.getRoot().getChild(fqn);
872          return n.getChildrenNames();
873       }
874       catch (Throwable JavaDoc t)
875       {
876          log.error("TreeCacheGui.getChildrenNames(): " + t);
877          return null;
878       }
879    }
880
881    Vector JavaDoc getMembers()
882    {
883       try
884       {
885          return new Vector JavaDoc();
886          // return cache.getMembers();
887
}
888       catch (Throwable JavaDoc t)
889       {
890          log.error("TreeCacheGui.getMembers(): " + t);
891          return null;
892       }
893    }
894
895    /* -------------------------- End of Private Methods ------------------------------ */
896
897    /*----------------------- Actions ---------------------------*/
898
899    class ExitAction extends AbstractAction
900    {
901       private static final long serialVersionUID = 8895044368299888998L;
902
903       public void actionPerformed(ActionEvent JavaDoc e)
904       {
905          dispose();
906       }
907    }
908
909    class AddNodeAction extends AbstractAction
910    {
911       private static final long serialVersionUID = 5568518714172267901L;
912
913       public void actionPerformed(ActionEvent JavaDoc e)
914       {
915          JTextField fqnTextField = new JTextField();
916          if (selected_node != null)
917             fqnTextField.setText(selected_node.toString());
918          Object JavaDoc[] information = {"Enter fully qualified name",
919                  fqnTextField};
920          final String JavaDoc btnString1 = "OK";
921          final String JavaDoc btnString2 = "Cancel";
922          Object JavaDoc[] options = {btnString1, btnString2};
923          int userChoice = JOptionPane.showOptionDialog(null,
924                  information,
925                  "Add DataNode",
926                  JOptionPane.YES_NO_OPTION,
927                  JOptionPane.PLAIN_MESSAGE,
928                  null,
929                  options,
930                  options[0]);
931          if (userChoice == 0)
932          {
933             String JavaDoc userInput = fqnTextField.getText();
934             put(Fqn.fromString(userInput), null);
935          }
936       }
937    }
938
939
940    class PrintLockInfoAction extends AbstractAction
941    {
942       private static final long serialVersionUID = 5577441016277949170L;
943
944       public void actionPerformed(ActionEvent JavaDoc e)
945       {
946          System.out.println("\n*** lock information ****\n" + cache.getLockTable());
947       }
948    }
949
950    class ReleaseAllLocksAction extends AbstractAction
951    {
952       private static final long serialVersionUID = 3796901116451916116L;
953
954       public void actionPerformed(ActionEvent JavaDoc e)
955       {
956          System.out.println("TODO :-)");
957       }
958    }
959
960    class RemoveNodeAction extends AbstractAction
961    {
962       private static final long serialVersionUID = 8985697625953238855L;
963
964       public void actionPerformed(ActionEvent JavaDoc e)
965       {
966          try
967          {
968             cache.getRoot().removeChild(selected_node);
969          }
970          catch (Throwable JavaDoc t)
971          {
972             log.error("RemoveNodeAction.actionPerformed(): " + t);
973          }
974       }
975    }
976
977    class AddModifyDataForNodeAction extends AbstractAction
978    {
979       private static final long serialVersionUID = 3593129982953807846L;
980
981       public void actionPerformed(ActionEvent JavaDoc e)
982       {
983          Map JavaDoc data = getData(selected_node);
984          if (data != null)
985          {
986          }
987          else
988          {
989             clearTable();
990             data = new HashMap JavaDoc();
991             data.put("Add Key", "Add Value");
992
993          }
994          populateTable(data);
995          getContentPane().add(tablePanel, BorderLayout.SOUTH);
996          validate();
997
998       }
999    }
1000
1001
1002   class MyNode extends DefaultMutableTreeNode JavaDoc
1003   {
1004      private static final long serialVersionUID = 1578599138419577069L;
1005      Object JavaDoc name = "<unnamed>";
1006
1007
1008      MyNode(Object JavaDoc name)
1009      {
1010         this.name = name;
1011      }
1012
1013
1014      /**
1015       * Adds a new node to the view. Intermediary nodes will be created if they don't yet exist.
1016       * Returns the first node that was created or null if node already existed
1017       */

1018      public MyNode add(Fqn fqn)
1019      {
1020         MyNode curr, n, ret = null;
1021
1022         if (fqn == null) return null;
1023         curr = this;
1024         for (Object JavaDoc o : fqn.peekElements())
1025         {
1026            n = curr.findChild(o);
1027            if (n == null)
1028            {
1029               n = new MyNode(o.toString());
1030               if (ret == null) ret = n;
1031               curr.add(n);
1032            }
1033            curr = n;
1034         }
1035         return ret;
1036      }
1037
1038
1039      /**
1040       * Removes a node from the view. Child nodes will be removed as well
1041       */

1042      public void remove(String JavaDoc fqn)
1043      {
1044         removeFromParent();
1045      }
1046
1047
1048      MyNode findNode(Fqn fqn)
1049      {
1050         MyNode curr, n;
1051
1052         if (fqn == null) return null;
1053         curr = this;
1054         for (Object JavaDoc o : fqn.peekElements())
1055         {
1056            n = curr.findChild(o);
1057            if (n == null)
1058               return null;
1059            curr = n;
1060         }
1061         return curr;
1062      }
1063
1064
1065      MyNode findChild(Object JavaDoc relative_name)
1066      {
1067         MyNode child;
1068
1069         if (relative_name == null || getChildCount() == 0)
1070            return null;
1071         for (int i = 0; i < getChildCount(); i++)
1072         {
1073            child = (MyNode) getChildAt(i);
1074            if (child.name == null)
1075            {
1076               continue;
1077            }
1078
1079            if (child.name.equals(relative_name))
1080               return child;
1081         }
1082         return null;
1083      }
1084
1085
1086      String JavaDoc print(int indent)
1087      {
1088         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1089
1090         for (int i = 0; i < indent; i++)
1091            sb.append(" ");
1092         if (!isRoot())
1093         {
1094            if (name == null)
1095               sb.append("/<unnamed>");
1096            else
1097            {
1098               sb.append(TreeCacheGui.SEP.toString() + name);
1099            }
1100         }
1101         sb.append("\n");
1102         if (getChildCount() > 0)
1103         {
1104            if (isRoot())
1105               indent = 0;
1106            else
1107               indent += 4;
1108            for (int i = 0; i < getChildCount(); i++)
1109               sb.append(((MyNode) getChildAt(i)).print(indent));
1110         }
1111         return sb.toString();
1112      }
1113
1114
1115      public String JavaDoc toString()
1116      {
1117         return name.toString();
1118      }
1119
1120   }
1121
1122
1123}
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
Popular Tags