summaryrefslogtreecommitdiff
path: root/qpid/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java
blob: fedb1c4bd0e74747968dbd2ec7b14828b4fffe66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.qpid.management.ui.views;

import static org.apache.qpid.management.ui.Constants.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.qpid.management.ui.ApplicationRegistry;
import org.apache.qpid.management.ui.ManagedBean;
import org.apache.qpid.management.ui.ManagedServer;
import org.apache.qpid.management.ui.ServerRegistry;
import org.apache.qpid.management.ui.exceptions.InfoRequiredException;
import org.apache.qpid.management.ui.jmx.JMXServerRegistry;
import org.apache.qpid.management.ui.jmx.MBeanUtility;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IFontProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.part.ViewPart;

/**
 * Navigation View for navigating the managed servers and managed beans on
 * those servers
 * @author Bhupendra Bhardwaj
 */
public class NavigationView extends ViewPart
{
    public static final String ID = "org.apache.qpid.management.ui.navigationView";
    public static final String INI_FILENAME = System.getProperty("user.home") + File.separator + "qpidManagementConsole.ini";

    private static final String INI_SERVERS = "Servers";
    private static final String INI_QUEUES = QUEUE + "s";
    private static final String INI_CONNECTIONS = CONNECTION + "s";
    private static final String INI_EXCHANGES = EXCHANGE + "s";

    private TreeViewer _treeViewer = null;
    private TreeObject _serversRootNode = null;

    private PreferenceStore _preferences;
    // Map of connected servers
    private HashMap<ManagedServer, TreeObject> _managedServerMap = new HashMap<ManagedServer, TreeObject>();

    private void createTreeViewer(Composite parent)
    {
        _treeViewer = new TreeViewer(parent);
        _treeViewer.setContentProvider(new ContentProviderImpl());
        _treeViewer.setLabelProvider(new LabelProviderImpl());
        _treeViewer.setSorter(new ViewerSorterImpl());

        // layout the tree viewer below the label field, to cover the area
        GridData layoutData = new GridData();
        layoutData = new GridData();
        layoutData.grabExcessHorizontalSpace = true;
        layoutData.grabExcessVerticalSpace = true;
        layoutData.horizontalAlignment = GridData.FILL;
        layoutData.verticalAlignment = GridData.FILL;
        _treeViewer.getControl().setLayoutData(layoutData);
        _treeViewer.setUseHashlookup(true);

        createListeners();
    }

    /**
     * Creates listeners for the JFace treeviewer
     */
    private void createListeners()
    {
        _treeViewer.addDoubleClickListener(new IDoubleClickListener()
            {
                public void doubleClick(DoubleClickEvent event)
                {
                    IStructuredSelection ss = (IStructuredSelection) event.getSelection();
                    if ((ss == null) || (ss.getFirstElement() == null))
                    {
                        return;
                    }

                    boolean state = _treeViewer.getExpandedState(ss.getFirstElement());
                    _treeViewer.setExpandedState(ss.getFirstElement(), !state);
                }
            });

        _treeViewer.addTreeListener(new ITreeViewerListener()
            {
                public void treeExpanded(TreeExpansionEvent event)
                {
                    getSite().getShell().getDisplay().asyncExec(
                            new Runnable()
                            {
                                public void run()
                                {
                                     _treeViewer.refresh();
                                }
                            });
                }

                public void treeCollapsed(TreeExpansionEvent event)
                {
                    getSite().getShell().getDisplay().asyncExec(
                            new Runnable()
                            {
                                public void run()
                                {
                                     _treeViewer.refresh();
                                }
                            });
                }
            });

        // This listener is for popup menu, which pops up if a queue,exchange or connection is selected
        // with right click.
        _treeViewer.getTree().addListener(SWT.MenuDetect, new Listener()
            {
                Display display = getSite().getShell().getDisplay();
                final Shell shell = new Shell(display);

                public void handleEvent(Event event)
                {
                    Tree widget = (Tree) event.widget;
                    TreeItem[] items = widget.getSelection();
                    if (items == null)
                    {
                        return;
                    }

                    // Get the selected node
                    final TreeObject selectedNode = (TreeObject) items[0].getData();
                    final TreeObject parentNode = selectedNode.getParent();

                    // This popup is only for mbeans and only connection,exchange and queue types
                    if ((parentNode == null) || !MBEAN.equals(selectedNode.getType())
                            || !(CONNECTION.equals(parentNode.getName()) || QUEUE.equals(parentNode.getName())
                                || EXCHANGE.equals(parentNode.getName())))
                    {
                        return;
                    }

                    Menu menu = new Menu(shell, SWT.POP_UP);
                    MenuItem item = new MenuItem(menu, SWT.PUSH);
                    // Add the action item, which will remove the node from the tree if selected
                    item.setText(ACTION_REMOVE_MBEANNODE);
                    item.addListener(SWT.Selection, new Listener()
                        {
                            public void handleEvent(Event e)
                            {
                                removeManagedObject(parentNode, (ManagedBean) selectedNode.getManagedObject());
                                _treeViewer.refresh();
                                // set the selection to the parent node
                                _treeViewer.setSelection(new StructuredSelection(parentNode));
                            }
                        });
                    menu.setLocation(event.x, event.y);
                    menu.setVisible(true);
                    while (!menu.isDisposed() && menu.isVisible())
                    {
                        if (!display.readAndDispatch())
                        {
                            display.sleep();
                        }
                    }

                    menu.dispose();
                }
            });
    }

    /**
     * Creates Qpid Server connection
     * @param server
     * @throws Exception
     */
    private void createJMXServerConnection(ManagedServer server) throws Exception
    {
        // Currently Qpid Management Console only supports JMX MBeanServer
        ServerRegistry serverRegistry = new JMXServerRegistry(server);
        ApplicationRegistry.addServer(server, serverRegistry);
    }

    /**
     * Adds a new server node in the navigation view if server connection is successful.
     * @param transportProtocol
     * @param host
     * @param port
     * @param domain
     * @throws Exception
     */
    public void addNewServer(String host, int port, String domain, String user, String pwd)
        throws Exception
    {
        ManagedServer managedServer = new ManagedServer(host, port, domain, user, pwd);

        String server = managedServer.getName();
        List<TreeObject> list = _serversRootNode.getChildren();
        for (TreeObject node : list)
        {
            ManagedServer nodeServer = (ManagedServer)node.getManagedObject();
            if (server.equals(nodeServer.getName()))
            {
                // Server is already in the list of added servers, so now connect it.
                // Set the server node as selected and then connect it.
                _treeViewer.setSelection(new StructuredSelection(node));
                reconnect(user, pwd);

                return;
            }
        }

        // The server is not in the list of already added servers, so now connect and add it.
        createJMXServerConnection(managedServer);

        // Server connection is successful. Now add the server in the tree
        TreeObject serverNode = new TreeObject(server, NODE_TYPE_SERVER);
        serverNode.setManagedObject(managedServer);
        _serversRootNode.addChild(serverNode);

        // Add server in the connected server map
        _managedServerMap.put(managedServer, serverNode);

        // populate the server tree
        try
        {
            populateServer(serverNode);
        }
        catch (SecurityException ex)
        {
            disconnect(managedServer);
            throw ex;
        }

        // Add the Queue/Exchanges/Connections from config file into the navigation tree
        addConfiguredItems(managedServer);

        expandInitialMBeanView(serverNode);
        
        _treeViewer.refresh();

        // save server address in file
        addServerInConfigFile(server);
    }

    /**
     * Create the config file, if it doesn't already exist.
     * Exits the application if the file could not be created.
     */
    private void createConfigFile()
    {
        File file = new File(INI_FILENAME);
        try
        {
            if (!file.exists())
            {
                file.createNewFile();
            }
        }
        catch (IOException ex)
        {
            System.out.println("Could not write to the file " + INI_FILENAME);
            System.out.println(ex);
            System.exit(1);
        }
    }

    /**
     * Server addresses are stored in a file. When user launches the application again, the
     * server addresses are picked up from the file and shown in the navigfation view. This method
     * adds the server address in a file, when a new server is added in the navigation view.
     * @param serverAddress
     */
    private void addServerInConfigFile(String serverAddress)
    {
        // Check if the address already exists
        List<String> list = getServerListFromFile();
        if ((list != null) && list.contains(serverAddress))
        {
            return;
        }

        // Get the existing server list and add to that
        String servers = _preferences.getString(INI_SERVERS);
        String value = (servers.length() != 0) ? (servers + "," + serverAddress) : serverAddress;
        _preferences.putValue(INI_SERVERS, value);
        try
        {
            _preferences.save();
        }
        catch (IOException ex)
        {
            System.err.println("Could not add " + serverAddress + " in " + INI_SERVERS + " (" + INI_FILENAME + ")");
            System.out.println(ex);
        }
    }

    /**
     * Adds the item (Queue/Exchange/Connection) to the config file
     * @param server
     * @param virtualhost
     * @param type - (Queue or Exchange or Connection)
     * @param name - item name
     */
    private void addItemInConfigFile(TreeObject node)
    {
        ManagedBean mbean = (ManagedBean) node.getManagedObject();
        String server = mbean.getServer().getName();
        String virtualhost = mbean.getVirtualHostName();
        String type = node.getParent().getName() + "s";
        String name = node.getName();
        String itemKey = server + "." + virtualhost + "." + type;

        // Check if the item already exists in the config file
        List<String> list = getConfiguredItemsFromFile(itemKey);
        if ((list != null) && list.contains(name))
        {
            return;
        }

        // Add this item to the existing list of items
        String items = _preferences.getString(itemKey);
        String value = (items.length() != 0) ? (items + "," + name) : name;
        _preferences.putValue(itemKey, value);
        try
        {
            _preferences.save();
        }
        catch (IOException ex)
        {
            System.err.println("Could not add " + name + " in " + itemKey + " (" + INI_FILENAME + ")");
            System.out.println(ex);
        }
    }

    private void removeItemFromConfigFile(TreeObject node)
    {
        ManagedBean mbean = (ManagedBean) node.getManagedObject();
        String server = mbean.getServer().getName();
        String vHost = mbean.getVirtualHostName();
        String type = node.getParent().getName() + "s";
        String itemKey = server + "." + vHost + "." + type;

        List<String> list = getConfiguredItemsFromFile(itemKey);
        if (list.contains(node.getName()))
        {
            list.remove(node.getName());
            String value = "";
            for (String item : list)
            {
                value += item + ",";
            }

            value = (value.lastIndexOf(",") != -1) ? value.substring(0, value.lastIndexOf(",")) : value;

            _preferences.putValue(itemKey, value);
            try
            {
                _preferences.save();
            }
            catch (IOException ex)
            {
                System.err.println("Error in updating the config file " + INI_FILENAME);
                System.out.println(ex);
            }
        }
    }

    //check if the MBeanInfo can be retrieved.
    private boolean haveAccessPermission(ManagedBean mbean)
    {
        try
        {                
            MBeanUtility.getMBeanInfo(mbean);     
        }
        catch(Exception ex)
        {
            return false;
        }
        
        return true;
    }
    
    /**
     * Queries the qpid server for MBeans and populates the navigation view with all MBeans for
     * the given server node.
     * @param serverNode
     * @throws Exception
     */
    private void populateServer(TreeObject serverNode) throws Exception
    {
        ManagedServer server = (ManagedServer) serverNode.getManagedObject();
        String domain = server.getDomain();

        List<ManagedBean> mbeans = MBeanUtility.getManagedObjectsForDomain(server, domain);
        for (ManagedBean mbean : mbeans)
        {
            mbean.setServer(server);
            ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server);
            serverRegistry.addManagedObject(mbean);

            // Add all mbeans other than Connections, Exchanges and Queues. Because these will be added
            // manually by selecting from MBeanView
            if (!(mbean.isConnection() || mbean.isExchange() || mbean.isQueue()))
            {
                //if we cant get the MBeanInfo then we cant display the mbean, so dont add it to the tree
                if (haveAccessPermission(mbean))
                {
                    addManagedBean(serverNode, mbean);
                }
            }
        }
        // To make it work with the broker without virtual host implementation.
        // This will add the default nodes to the domain node
        boolean hasVirtualHost = false;
        for (TreeObject child : serverNode.getChildren())
        {
            if (child.getName().startsWith(VIRTUAL_HOST))
            {
                hasVirtualHost = true;
                break;      
            }
        }
        
        if (!hasVirtualHost){
            addDefaultNodes(serverNode);
        }
    }

    /**
     * Add these three types - Connection, Exchange, Queue
     * By adding these, these will always be available, even if there are no mbeans under thse types
     * This is required because, the mbeans will be added from mbeanview, by selecting from the list
     * @param parent Node
     */
    private void addDefaultNodes(TreeObject parent)
    {
        TreeObject typeChild = new TreeObject(CONNECTION, NODE_TYPE_MBEANTYPE);
        typeChild.setParent(parent);
        typeChild.setVirtualHost(parent.getVirtualHost());
        typeChild = new TreeObject(EXCHANGE, NODE_TYPE_MBEANTYPE);
        typeChild.setParent(parent);
        typeChild.setVirtualHost(parent.getVirtualHost());
        typeChild = new TreeObject(QUEUE, NODE_TYPE_MBEANTYPE);
        typeChild.setParent(parent);
        typeChild.setVirtualHost(parent.getVirtualHost());
        
        // Add common notification node for virtual host
        TreeObject notificationNode = new TreeObject(NOTIFICATIONS, NOTIFICATIONS);
        notificationNode.setParent(parent);
        notificationNode.setVirtualHost(parent.getVirtualHost());
    }

    /**
     * Checks if a particular mbeantype is already there in the navigation view for a domain.
     * This is used while populating domain with mbeans.
     * @param parent
     * @param typeName
     * @return Node if given mbeantype already exists, otherwise null
     */
    private TreeObject getMBeanTypeNode(TreeObject parent, String typeName)
    {
        List<TreeObject> childNodes = parent.getChildren();
        for (TreeObject child : childNodes)
        {
            if ((NODE_TYPE_MBEANTYPE.equals(child.getType()) || NODE_TYPE_TYPEINSTANCE.equals(child.getType()))
                    && typeName.equals(child.getName()))
            {
                return child;
            }
        }

        return null;
    }

    private boolean doesMBeanNodeAlreadyExist(TreeObject typeNode, String mbeanName)
    {
        List<TreeObject> childNodes = typeNode.getChildren();
        for (TreeObject child : childNodes)
        {
            if (MBEAN.equals(child.getType()) && mbeanName.equals(child.getName()))
            {
                return true;
            }
        }

        return false;
    }

    /**
     * Adds the given MBean to the given domain node.
     * sample ObjectNames -
     * org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=localhost
     * org.apache.qpid:type=VirtualHost.Queue,VirtualHost=test,name=ping_1
     * @param parent parent tree node to add the mbean to
     * @param mbean mbean to add
     */
    private void addManagedBean(TreeObject parent, ManagedBean mbean)
    {
        String name = mbean.getName();
        // Split the mbean type into array of Strings, to create hierarchy
        // eg. type=VirtualHost.VirtualHostManager,VirtualHost=localhost will be:
        // localhost->VirtualHostManager
        // eg. type=org.apache.qpid:type=VirtualHost.Queue,VirtualHost=test,name=ping will be:
        // test->Queue->ping
        String[] types = mbean.getType().split("\\.");
        TreeObject typeNode = null;
        TreeObject parentNode = parent;

        // Run this loop till all nodes(hierarchy) for this mbean are created. This loop only creates
        // all the required parent nodes for the mbean
        for (int i = 0; i < types.length; i++)
        {
            String type = types[i];
            String valueOftype = mbean.getProperty(type);
            // If value is not null, then there will be a parent node for this mbean
            // eg. for type=VirtualHost the value is "test"
            typeNode = getMBeanTypeNode(parentNode, type);

            // create the type node if not already created
            if (typeNode == null)
            {
                // If the ObjectName doesn't have name property, that means there will be only one instance
                // of this mbean for given "type". So there will be no type node created for this mbean.
                if ((name == null) && (i == (types.length - 1)))
                {
                    break;
                }

                // create a node for "type"
                typeNode = createTypeNode(parentNode, type);
                if (!type.equals(VIRTUAL_HOST))
                {
                    typeNode.setVirtualHost(mbean.getVirtualHostName());
                }
            }

            // now type node create becomes the parent node for next node in hierarchy
            parentNode = typeNode;

            /*
             * Now create instances node for this type if value exists.
             */
            if (valueOftype == null)
            {
                // No instance node will be created when value is null (eg type=Queue)
                break;
            }

            // For different virtual hosts, the nodes with given value will be created.
            // eg type=VirtualHost, value=test
            typeNode = getMBeanTypeNode(parentNode, valueOftype);
            if (typeNode == null)
            {
                typeNode = createTypeInstanceNode(parentNode, valueOftype);
                typeNode.setVirtualHost(mbean.getVirtualHostName());

                // Create default nodes for VHost instances
                if (type.equals(VIRTUAL_HOST))
                {
                    addDefaultNodes(typeNode);
                }
            }

            parentNode = typeNode;
        }

        if (typeNode == null)
        {
            typeNode = parentNode;
        }

        // Check if an MBean is already added
        if (doesMBeanNodeAlreadyExist(typeNode, name))
        {
            return;
        }

        // Add the mbean node now
        TreeObject mbeanNode = new TreeObject(mbean);
        mbeanNode.setParent(typeNode);

        // Add the mbean to the config file
        if (mbean.isQueue() || mbean.isExchange() || mbean.isConnection())
        {
            addItemInConfigFile(mbeanNode);
        }
    }

    private TreeObject createTypeNode(TreeObject parent, String name)
    {
        TreeObject typeNode = new TreeObject(name, NODE_TYPE_MBEANTYPE);
        typeNode.setParent(parent);

        return typeNode;
    }

    private TreeObject createTypeInstanceNode(TreeObject parent, String name)
    {
        TreeObject typeNode = new TreeObject(name, NODE_TYPE_TYPEINSTANCE);
        typeNode.setParent(parent);

        return typeNode;
    }

    /**
     * Removes all the child nodes of the given parent node. Used when closing a server.
     * @param parent
     */
    private void removeManagedObject(TreeObject parent)
    {
        List<TreeObject> list = parent.getChildren();
        for (TreeObject child : list)
        {
            removeManagedObject(child);
        }

        list.clear();
    }

    /**
     * Removes the mbean from the tree
     * @param parent
     * @param mbean
     */
    private void removeManagedObject(TreeObject parent, ManagedBean mbean)
    {
        List<TreeObject> list = parent.getChildren();
        TreeObject objectToRemove = null;
        for (TreeObject child : list)
        {
            if (MBEAN.equals(child.getType()))
            {
                String name = (mbean.getName() != null) ? mbean.getName() : mbean.getType();
                if (child.getName().equals(name))
                {
                    objectToRemove = child;

                    break;
                }
            }
            else
            {
                removeManagedObject(child, mbean);
            }
        }

        if (objectToRemove != null)
        {
            list.remove(objectToRemove);
            removeItemFromConfigFile(objectToRemove);
        }

    }

    /**
     * Closes the Qpid server connection
     */
    public void disconnect() throws Exception
    {
        TreeObject selectedNode = getSelectedServerNode();
        ManagedServer managedServer = (ManagedServer) selectedNode.getManagedObject();
        disconnect(managedServer);
    }
    
    private void disconnect(ManagedServer managedServer) throws Exception
    {
        if (!_managedServerMap.containsKey(managedServer))
        {
            return;
        }

        // Close server connection
        ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(managedServer);
        if (serverRegistry == null) // server connection is already closed
        {
            return;
        }

        serverRegistry.closeServerConnection();
        // Add server to the closed server list and the worker thread will remove the server from required places.
        ApplicationRegistry.serverConnectionClosed(managedServer);
    }

    /**
     * Connects the selected server node
     * @throws Exception
     */
    public void reconnect(String user, String password) throws Exception
    {
        TreeObject selectedNode = getSelectedServerNode();
        ManagedServer managedServer = (ManagedServer) selectedNode.getManagedObject();
        if (_managedServerMap.containsKey(managedServer))
        {
            throw new InfoRequiredException("Server " + managedServer.getName() + " is already connected");
        }

        managedServer.setUser(user);
        managedServer.setPassword(password);
        createJMXServerConnection(managedServer);

        // put the server in the managed server map
        _managedServerMap.put(managedServer, selectedNode);

        try
        {
            // populate the server tree now
            populateServer(selectedNode);
        }
        catch (SecurityException ex)
        {
            disconnect(managedServer);
            throw ex;
        }
        

        // Add the Queue/Exchanges/Connections from config file into the navigation tree
        addConfiguredItems(managedServer);

        expandInitialMBeanView(selectedNode);
        
        _treeViewer.refresh();
    }
    
    private void expandInitialMBeanView(TreeObject serverNode)
    {
        if (serverNode.getChildren().size() == 0 )
        {
            return;
        }
        else
        {
            _treeViewer.setExpandedState(serverNode , true);
        }
        
        List<TreeObject> children = serverNode.getChildren();
        for (TreeObject child : children)
        {
            if (child.getChildren().size() > 0)
            {
                _treeViewer.setExpandedState(child, true);
            }
        }
    }

    /**
     * Adds the items(queues/exchanges/connectins) from config file to the server tree
     * @param server
     */
    private void addConfiguredItems(ManagedServer server)
    {
        ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server);
        List<String> list = serverRegistry.getVirtualHosts();
        for (String virtualHost : list)
        {
            // Add Queues
            String itemKey = server.getName() + "." + virtualHost + "." + INI_QUEUES;
            List<String> items = getConfiguredItemsFromFile(itemKey);
            List<ManagedBean> mbeans = serverRegistry.getQueues(virtualHost);
            addConfiguredItems(items, mbeans);

            // Add Exchanges
            itemKey = server.getName() + "." + virtualHost + "." + INI_EXCHANGES;
            items = getConfiguredItemsFromFile(itemKey);
            mbeans = serverRegistry.getExchanges(virtualHost);
            addConfiguredItems(items, mbeans);

            // Add Connections
            itemKey = server.getName() + "." + virtualHost + "." + INI_CONNECTIONS;
            items = getConfiguredItemsFromFile(itemKey);
            mbeans = serverRegistry.getConnections(virtualHost);
            addConfiguredItems(items, mbeans);
        }
    }

    /**
     * Gets the mbeans corresponding to the items and adds those to the navigation tree
     * @param items
     * @param mbeans
     */
    private void addConfiguredItems(List<String> items, List<ManagedBean> mbeans)
    {
        if ((items == null) || (items.isEmpty() | (mbeans == null)) || mbeans.isEmpty())
        {
            return;
        }

        for (String item : items)
        {
            for (ManagedBean mbean : mbeans)
            {
                if (item.equals(mbean.getName()))
                {
                    addManagedBean(mbean);

                    break;
                }
            }
        }
    }

    /**
     * Closes the Qpid server connection if not already closed and removes the server node from the navigation view and
     * also from the ini file stored in the system.
     * @throws Exception
     */
    public void removeServer() throws Exception
    {
        disconnect();

        // Remove from the Tree
        String serverNodeName = getSelectedServerNode().getName();
        List<TreeObject> list = _serversRootNode.getChildren();
        TreeObject objectToRemove = null;
        for (TreeObject child : list)
        {
            if (child.getName().equals(serverNodeName))
            {
                objectToRemove = child;

                break;
            }
        }

        if (objectToRemove != null)
        {
            list.remove(objectToRemove);
        }

        _treeViewer.refresh();

        // Remove from the ini file
        removeServerFromConfigFile(serverNodeName);
    }

    private void removeServerFromConfigFile(String serverNodeName)
    {
        List<String> serversList = getServerListFromFile();
        serversList.remove(serverNodeName);

        String value = "";
        for (String item : serversList)
        {
            value += item + ",";
        }

        value = (value.lastIndexOf(",") != -1) ? value.substring(0, value.lastIndexOf(",")) : value;

        _preferences.putValue(INI_SERVERS, value);

        try
        {
            _preferences.save();
        }
        catch (IOException ex)
        {
            System.err.println("Error in updating the config file " + INI_FILENAME);
            System.out.println(ex);
        }
    }

    /**
     * @return the server addresses from the ini file
     * @throws Exception
     */
    private List<String> getServerListFromFile()
    {
        return getConfiguredItemsFromFile(INI_SERVERS);
    }

    /**
     * Returns the list of items from the config file.
     * sample ini file:
     * Servers=localhost:8999,127.0.0.1:8999
     * localhost.virtualhost1.Queues=queue1,queue2
     * localhost.virtualhost1.Exchanges=exchange1,exchange2
     * localhost.virtualhost2.Connections=conn1
     * @param key
     * @return
     */
    private List<String> getConfiguredItemsFromFile(String key)
    {
        List<String> list = new ArrayList<String>();
        String items = _preferences.getString(key);
        if (items.length() != 0)
        {
            String[] array = items.split(",");
            for (String item : array)
            {
                list.add(item);
            }
        }

        return list;
    }

    public TreeObject getSelectedServerNode() throws Exception
    {
        IStructuredSelection ss = (IStructuredSelection) _treeViewer.getSelection();
        TreeObject selectedNode = (TreeObject) ss.getFirstElement();
        if (ss.isEmpty() || (selectedNode == null) || (!selectedNode.getType().equals(NODE_TYPE_SERVER)))
        {
            throw new InfoRequiredException("Please select the server");
        }

        return selectedNode;
    }

    /**
     * This is a callback that will allow us to create the viewer and initialize
     * it.
     */
    public void createPartControl(Composite parent)
    {
        Composite composite = new Composite(parent, SWT.NONE);
        GridLayout gridLayout = new GridLayout();
        gridLayout.marginHeight = 2;
        gridLayout.marginWidth = 2;
        gridLayout.horizontalSpacing = 0;
        gridLayout.verticalSpacing = 2;
        composite.setLayout(gridLayout);

        createTreeViewer(composite);
        _serversRootNode = new TreeObject(NAVIGATION_ROOT, "ROOT");

        _treeViewer.setInput(_serversRootNode);
        // set viewer as selection event provider for MBeanView
        getSite().setSelectionProvider(_treeViewer);

        // Start worker thread to refresh tree for added or removed objects
        (new Thread(new Worker())).start();

        createConfigFile();
        _preferences = new PreferenceStore(INI_FILENAME);

        try
        {
            _preferences.load();
        }
        catch (IOException ex)
        {
            System.out.println(ex);
        }

        // load the list of servers already added from file
        List<String> serversList = getServerListFromFile();
        if (serversList != null)
        {
            for (String serverAddress : serversList)
            {
                String[] server = serverAddress.split(":");
                ManagedServer managedServer = new ManagedServer(server[0], Integer.parseInt(server[1]), "org.apache.qpid");
                TreeObject serverNode = new TreeObject(serverAddress, NODE_TYPE_SERVER);
                serverNode.setManagedObject(managedServer);
                _serversRootNode.addChild(serverNode);
            }
        }

        _treeViewer.refresh();

    }

    /**
     * Passing the focus request to the viewer's control.
     */
    public void setFocus()
    { }

    public void refresh()
    {
        _treeViewer.refresh();
    }

    /**
     * Content provider class for the tree viewer
     */
    private class ContentProviderImpl implements ITreeContentProvider
    {
        public Object[] getElements(Object parent)
        {
            return getChildren(parent);
        }

        public Object[] getChildren(final Object parentElement)
        {
            final TreeObject node = (TreeObject) parentElement;

            return node.getChildren().toArray(new TreeObject[0]);
        }

        public Object getParent(final Object element)
        {
            final TreeObject node = (TreeObject) element;

            return node.getParent();
        }

        public boolean hasChildren(final Object element)
        {
            final TreeObject node = (TreeObject) element;

            return !node.getChildren().isEmpty();
        }

        public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput)
        {
            // Do nothing
        }

        public void dispose()
        {
            // Do nothing
        }
    }

    /**
     * Label provider class for the tree viewer
     */
    private class LabelProviderImpl extends LabelProvider implements IFontProvider
    {
        public Image getImage(Object element)
        {
            TreeObject node = (TreeObject) element;
            if (node.getType().equals(NOTIFICATIONS))
            {
                return ApplicationRegistry.getImage(NOTIFICATION_IMAGE);
            }
            else if (!node.getType().equals(MBEAN))
            {
                if (_treeViewer.getExpandedState(node))
                {
                    return ApplicationRegistry.getImage(OPEN_FOLDER_IMAGE);
                }
                else
                {
                    return ApplicationRegistry.getImage(CLOSED_FOLDER_IMAGE);
                }

            }
            else
            {
                return ApplicationRegistry.getImage(MBEAN_IMAGE);
            }
        }

        public String getText(Object element)
        {
            TreeObject node = (TreeObject) element;
            if (node.getType().equals(NODE_TYPE_MBEANTYPE))
            {
                return node.getName() + "s";
            }
            else
            {
                return node.getName();
            }
        }

        public Font getFont(Object element)
        {
            TreeObject node = (TreeObject) element;
            if (node.getType().equals(NODE_TYPE_SERVER))
            {
                if (node.getChildren().isEmpty())
                {
                    return ApplicationRegistry.getFont(FONT_NORMAL);
                }
                else
                {
                    return ApplicationRegistry.getFont(FONT_BOLD);
                }
            }

            return ApplicationRegistry.getFont(FONT_NORMAL);
        }
    } // End of LabelProviderImpl

    private class ViewerSorterImpl extends ViewerSorter
    {
        public int category(Object element)
        {
            TreeObject node = (TreeObject) element;
            if (node.getType().equals(MBEAN))
            {
                return 1;
            }
            if (node.getType().equals(NOTIFICATIONS))
            {
                return 2;
            }
            return 3;
        }
    }

    /**
     * Worker thread, which keeps looking for new ManagedObjects to be added and
     * unregistered objects to be removed from the tree.
     * @author Bhupendra Bhardwaj
     */
    private class Worker implements Runnable
    {
        public void run()
        {
            while (true)
            {
                if (!_managedServerMap.isEmpty())
                {
                    refreshRemovedObjects();
                    refreshClosedServerConnections();
                }

                try
                {
                    Thread.sleep(3000);
                }
                catch (Exception ex)
                { }

            } // end of while loop
        } // end of run method.
    } // end of Worker class

    /**
     * Adds the mbean to the navigation tree
     * @param mbean mbean to add to the tree
     */
    public void addManagedBean(ManagedBean mbean)
    {
        TreeObject treeServerObject = _managedServerMap.get(mbean.getServer());
        addManagedBean(treeServerObject, mbean);
        _treeViewer.refresh();
    }

    private void refreshRemovedObjects()
    {
        for (ManagedServer server : _managedServerMap.keySet())
        {
            final ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server);
            if (serverRegistry == null) // server connection is closed
            {
                continue;
            }

            final List<ManagedBean> removalList = serverRegistry.getObjectsToBeRemoved();
            if (removalList != null)
            {
                Display display = getSite().getShell().getDisplay();
                display.syncExec(new Runnable()
                    {
                        public void run()
                        {
                            for (ManagedBean mbean : removalList)
                            {
                                TreeObject treeServerObject = _managedServerMap.get(mbean.getServer());

                                removeManagedObject(treeServerObject, mbean);
                            }

                            _treeViewer.refresh();
                        }
                    });
            }
        }
    }

    /**
     * Gets the list of closed server connection from the ApplicationRegistry and then removes
     * the closed server nodes from the navigation view
     */
    private void refreshClosedServerConnections()
    {
        final List<ManagedServer> closedServers = ApplicationRegistry.getClosedServers();
        if (closedServers != null)
        {
            Display display = getSite().getShell().getDisplay();
            display.syncExec(new Runnable()
                {
                    public void run()
                    {
                        for (ManagedServer server : closedServers)
                        {
                            removeManagedObject(_managedServerMap.get(server));
                            _managedServerMap.remove(server);
                            ApplicationRegistry.removeServer(server);
                        }

                        _treeViewer.refresh();
                    }
                });
        }
    }

}