001    /**
002     *  Licensed to the Apache Software Foundation (ASF) under one or more
003     *  contributor license agreements.  See the NOTICE file distributed with
004     *  this work for additional information regarding copyright ownership.
005     *  The ASF licenses this file to You under the Apache License, Version 2.0
006     *  (the "License"); you may not use this file except in compliance with
007     *  the License.  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    package org.apache.geronimo.monitoring.console;
018    
019    import java.sql.Connection;
020    import java.sql.Statement;
021    import java.text.Format;
022    import java.text.SimpleDateFormat;
023    import java.util.ArrayList;
024    import java.util.Date;
025    import java.util.HashMap;
026    import java.util.Hashtable;
027    import java.util.Iterator;
028    import java.util.Properties;
029    import java.util.Set;
030    import java.util.TreeMap;
031    import java.util.TreeSet;
032    
033    import javax.management.MBeanServerConnection;
034    import javax.management.ObjectName;
035    import javax.management.remote.JMXConnector;
036    import javax.management.remote.JMXConnectorFactory;
037    import javax.management.remote.JMXServiceURL;
038    
039    import javax.naming.Context;
040    import javax.naming.InitialContext;
041    
042    import org.apache.geronimo.monitoring.MasterRemoteControlRemote;
043    import org.apache.geronimo.monitoring.console.util.DBManager;
044    
045    import org.apache.geronimo.crypto.EncryptionManager;
046    
047    public class MRCConnector {
048    
049        private static String PATH = null;
050        private static MBeanServerConnection mbServerConn;
051        private MasterRemoteControlRemote mrc = null;
052        private int Protocol = 0;
053    
054        MRCConnector() {
055    
056        }
057    
058        /**
059         * @param ip -
060         *            IP address of mrc-server to connect to
061         * @param userName -
062         *            Username for JMX connection to the host
063         * @param password -
064         *            Password for JMX connection to the host
065         * @throws Exception -
066         *             If the connection to mrc-server fails
067         */
068        public MRCConnector(String ip, String userName, String password, int port,
069                int protocol) throws Exception {
070            // decrypt the password
071            password = (String) EncryptionManager.decrypt(password);
072            Protocol = protocol;
073    
074            if (Protocol == 1) {
075    
076                try {
077                    Properties props = new Properties();
078                    props
079                            .setProperty(Context.INITIAL_CONTEXT_FACTORY,
080                                    "org.apache.openejb.client.RemoteInitialContextFactory");
081                    props.setProperty(Context.PROVIDER_URL, "ejbd://" + ip + ":"
082                            + port);
083                    props.setProperty(Context.SECURITY_PRINCIPAL, userName);
084                    props.setProperty(Context.SECURITY_CREDENTIALS, password);
085                    props.setProperty("openejb.authentication.realmName",
086                            "geronimo-admin");
087                    Context ic = new InitialContext(props);
088                    mrc = (MasterRemoteControlRemote) ic
089                            .lookup("ejb/mgmt/MRCRemote");
090                    mrc.setUpMEJB(userName, password);
091                } catch (Exception e) {
092                    throw e;
093                }
094    
095            } else {
096                try {
097                    JMXServiceURL serviceURL = new JMXServiceURL(
098                            "service:jmx:rmi:///jndi/rmi://" + ip + ":" + port
099                                    + "/JMXConnector");
100                    Hashtable<String, Object> env = new Hashtable<String, Object>();
101                    String[] credentials = new String[2];
102                    credentials[0] = userName;
103                    credentials[1] = password;
104                    env.put(JMXConnector.CREDENTIALS, credentials);
105                    JMXConnector connector = JMXConnectorFactory.connect(
106                            serviceURL, env);
107                    mbServerConn = connector.getMBeanServerConnection();
108    
109                    // retrieve the mbean name to the agent-car-jmx plugin 
110                    if(PATH == null) {
111                        Set<ObjectName> mbeanNames = mbServerConn.queryNames(new ObjectName("*:name=MasterRemoteControlJMX,*"), null);
112                        for(Iterator<ObjectName> it = mbeanNames.iterator(); it.hasNext(); ) {
113                            String mbeanName = ((ObjectName)it.next()).getCanonicalName();
114                            if(mbeanName.contains("agent-car-jmx") &&
115                               mbeanName.contains("MasterRemoteControlJMX") &&
116                               mbeanName.contains("GBean")) {
117                                PATH = mbeanName;
118                                break;
119                            }
120                        }
121    
122                        if(PATH == null) {
123                            throw new Exception("[ERROR] Required mbean not found: agent-car-jmx");
124                        }
125                    }
126                } catch (Exception e) {
127                    e.printStackTrace();
128                    throw e;
129                }
130    
131            }
132            // when the code has reach this point, a connection was successfully
133            // established
134            // so we need to update the last_seen attribute for the server
135            Format formatter = null;
136            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
137            Date date = new Date(System.currentTimeMillis());
138            String currentTime = formatter.format(date);
139    
140            Connection conn = DBManager.createConnection();
141            try {
142                Statement stmt = conn.createStatement();
143                stmt.executeUpdate("UPDATE SERVERS SET LAST_SEEN = '" + currentTime
144                        + "' WHERE IP='" + ip + "'");
145            } catch (Exception e) {
146                throw e;
147            } finally {
148                try {
149                    if (conn != null) {
150                        conn.close();
151                    }
152                } catch (Exception e) {
153    
154                }
155            }
156        }
157    
158        /**
159         * @return - Returns an Long representing the current snapshot duration set
160         *         on the server side
161         * @throws Exception -
162         *             If the connection to the MRC-Server fails
163         */
164        public Long getSnapshotDuration() throws Exception {
165            if (Protocol == 1) {
166    
167                return mrc.getSnapshotDuration();
168    
169            } else {
170    
171                return (Long) mbServerConn.invoke(new ObjectName(PATH),
172                        "getSnapshotDuration", new Object[] {}, new String[] {});
173            }
174        }
175    
176        /**
177         * @return - Returns an ArrayList of String objects containing a listing of
178         *         all statistics values being collected
179         * @throws Exception -
180         *             If the connection to the MRC-Server fails
181         */
182        @SuppressWarnings("unchecked")
183        public HashMap<String, ArrayList<String>> getDataNameList()
184                throws Exception {
185    
186            HashMap<String, ArrayList<String>> DataNameList = new HashMap<String, ArrayList<String>>();
187    
188            if (Protocol == 1) {
189    
190                try {
191                    DataNameList = mrc.getAllSnapshotStatAttributes();
192                } catch (Exception e) {
193                    e.printStackTrace();
194                }
195    
196            } else {
197                try {
198                    DataNameList = (HashMap<String, ArrayList<String>>) mbServerConn
199                            .invoke(new ObjectName(PATH),
200                                    "getAllSnapshotStatAttributes",
201                                    new Object[] {}, new String[] {});
202                } catch (Exception e) {
203                    e.printStackTrace();
204                }
205            }
206            // Strip out snapshot_date and snapshot_time, we know these exist
207            for (Iterator<String> it = DataNameList.keySet().iterator(); it
208                    .hasNext();) {
209                String mbeanName = it.next();
210                DataNameList.get(mbeanName).remove("snapshot_date");
211                DataNameList.get(mbeanName).remove("snapshot_time");
212            }
213            return DataNameList;
214        }
215    
216        /**
217         * @param snapCount -
218         *            Number of snapshots to request from the server
219         * @param skipCount -
220         *            Every nth snapshot. A value of 1 will be every 1. A value of 2
221         *            will be every other.
222         * @return - Returns an ArrayList of Map objects.
223         * @throws Exception -
224         *             If the connection to the MRC-Server fails
225         */
226        @SuppressWarnings("unchecked")
227        public ArrayList<HashMap<String, HashMap<String, Object>>> getSnapshots(
228                int snapCount, int skipCount) throws Exception {
229            ArrayList<HashMap<String, HashMap<String, Object>>> snapshotList = null;
230            if (Protocol == 1) {
231    
232                snapshotList = mrc.fetchSnapshotData(snapCount, skipCount);
233    
234            } else {
235                snapshotList = (ArrayList<HashMap<String, HashMap<String, Object>>>) mbServerConn
236                        .invoke(new ObjectName(PATH), "fetchSnapshotData",
237                                new Object[] { snapCount, skipCount },
238                                new String[] { "java.lang.Integer",
239                                        "java.lang.Integer" });
240            }
241            // Check if snapshotList is empty
242            if (snapshotList.size() == 0) {
243                return snapshotList;
244            }
245            /*
246             * If there are not enough snapshots available to fill the requested
247             * number, insert some with values of 0 and the proper times.
248             */
249            while (snapshotList.size() < snapCount) {
250                // Temporary, always is first element (oldest)
251                HashMap<String, HashMap<String, Object>> mapTimeFix = snapshotList
252                        .get(0);
253    
254                // Temporary map, used to generate blank data to be added to
255                // the
256                // list at position 0
257                HashMap<String, HashMap<String, Object>> tempMap = new HashMap<String, HashMap<String, Object>>();
258    
259                // Temporary submap, used to store 0 elements to be added to
260                // the
261                // tempmap
262                HashMap<String, Object> subMap = new HashMap<String, Object>();
263    
264                // Calculate appropriate time, add it to the submap, then
265                // add
266                // that to the tempMap
267                subMap.put("snapshot_time", ((Long) mapTimeFix.get("times").get(
268                        "snapshot_time") - (getSnapshotDuration() * skipCount)));
269                Format formatter = null;
270                formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
271                Date date = new Date((Long) subMap.get("snapshot_time"));
272                subMap.put("snapshot_date", formatter.format(date));
273    
274                // Add the submap back to the tempmap
275                tempMap.put("times", new HashMap<String, Object>(subMap));
276    
277                // Clear out the subMap for use again
278                subMap.clear();
279    
280                // Run through the mbeans
281    
282                // Run through the mbeans
283                for (Iterator<String> it = mapTimeFix.keySet().iterator(); it
284                        .hasNext();) {
285                    // get the mbean name
286                    String mbeanName = it.next();
287                    HashMap<String, Object> stats = null;
288                    // Verify that it's not times
289    
290                    if (mbeanName.equals(new String("times"))) {
291    
292                    } else {
293                        stats = mapTimeFix.get(mbeanName);
294                        // Run through the stats elements for the particular
295                        // mbean
296                        for (Iterator<String> itt = stats.keySet().iterator(); itt
297                                .hasNext();) {
298                            String key = itt.next();
299                            // Place faux data into the submap
300                            subMap.put(key, new Long(0));
301                        }
302                        // Add the submap to the tempmap, and clear it
303                        tempMap.put(mbeanName, new HashMap<String, Object>(subMap));
304                    }
305                }
306                snapshotList.add(0, new HashMap<String, HashMap<String, Object>>(
307                        tempMap));
308            }
309    
310            /*
311             * This is where we will be inserting data to fill 'gaps' in the
312             * snapshots The initial for-loop will travel from the most recent
313             * snapshot to the oldest, checking that the snapshot_time along the way
314             * all align with what they should be
315             */
316            for (int i = snapshotList.size() - 1; i > 0; i--) {
317                if (i > 0) {
318                    HashMap<String, HashMap<String, Object>> mapTimeFix = snapshotList
319                            .get(i);
320                    HashMap<String, HashMap<String, Object>> mapTimeFix2 = snapshotList
321                            .get(i - 1);
322                    // here is where we will in missing data
323                    while (((((Long) mapTimeFix.get("times").get("snapshot_time") / 1000) / 60)
324                            - (((Long) mapTimeFix2.get("times")
325                                    .get("snapshot_time") / 1000) / 60) > (((getSnapshotDuration() / 1000) / 60) * skipCount))) {
326                        HashMap<String, HashMap<String, Object>> tempMap = new HashMap<String, HashMap<String, Object>>();
327                        HashMap<String, Object> subMap = new HashMap<String, Object>();
328    
329                        for (Iterator<String> it = mapTimeFix.keySet().iterator(); it
330                                .hasNext();) {
331                            // get the mbean name
332                            String mbeanName = it.next();
333                            HashMap<String, Object> stats = null;
334                            // Verify that it's not times
335                            if (!mbeanName.equals("times")) {
336                                stats = mapTimeFix.get(mbeanName);
337                                // Run through the stats elements for the
338                                // particular
339                                // mbean
340                                for (Iterator<String> itt = stats.keySet()
341                                        .iterator(); itt.hasNext();) {
342                                    String key = itt.next();
343                                    // Place faux data into the submap
344                                    subMap.put(key, new Long(0));
345                                }
346                                // Add the submap to the tempmap, and clear it
347                                tempMap.put(mbeanName, new HashMap<String, Object>(
348                                        subMap));
349                                subMap.clear();
350                            }
351                        }
352    
353                        subMap.put("snapshot_time", new Long((Long) mapTimeFix.get(
354                                "times").get("snapshot_time")
355                                - (getSnapshotDuration() * skipCount)));
356                        Format formatter = null;
357                        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
358                        Date date = new Date((Long) subMap.get("snapshot_time"));
359                        subMap.put("snapshot_date", formatter.format(date));
360                        tempMap.put("times", new HashMap<String, Object>(subMap));
361                        subMap.clear();
362                        snapshotList.add(i,
363                                new HashMap<String, HashMap<String, Object>>(
364                                        tempMap));
365                        snapshotList.remove(0);
366                        mapTimeFix = tempMap;
367                        mapTimeFix2 = snapshotList.get(i - 1);
368                    }
369                }
370            }
371            return snapshotList;
372        }
373    
374        @SuppressWarnings("unchecked")
375        public TreeMap<Long, Long> getSpecificStatistics(String mbeanName,
376                String statsName, int snapCount, int skipCount, boolean showArchive)
377                throws Exception {
378            TreeMap<Long, Long> snapshotList = null;
379            if (Protocol == 1) {
380    
381                snapshotList = mrc.getSpecificStatistics(mbeanName, statsName,
382                        snapCount, skipCount, showArchive);
383    
384            } else {
385                snapshotList = (TreeMap<Long, Long>) mbServerConn.invoke(
386                        new ObjectName(PATH), "getSpecificStatistics",
387                        new Object[] { mbeanName, statsName, snapCount, skipCount,
388                                showArchive }, new String[] { "java.lang.String",
389                                "java.lang.String", "java.lang.Integer",
390                                "java.lang.Integer", "java.lang.Boolean" });
391    
392            }
393            // Check if snapshotList is empty
394            if (snapshotList.size() == 0) {
395                return snapshotList;
396            }
397            /*
398             * If there are not enough snapshots available to fill the requested
399             * number, insert some with values of 0 and the proper times.
400             */
401            while (snapshotList.size() < snapCount) {
402                // Temporary, always is first element (oldest)
403                Long timeFix = snapshotList.firstKey();
404    
405                // Calculate appropriate time, add it to the submap, then
406                // add
407                // that to the tempMap
408                snapshotList.put((timeFix - (getSnapshotDuration() * skipCount)),
409                        new Long(0));
410            }
411    
412            /*
413             * This is where we will be inserting data to fill 'gaps' in the
414             * snapshots The initial for-loop will travel from the most recent
415             * snapshot to the oldest, checking that the snapshot_time along the way
416             * all align with what they should be
417             */
418            Set tempSet = snapshotList.keySet();
419            ArrayList<Long> tempArray = new ArrayList(tempSet);
420    
421            for (int i = tempArray.size() - 1; i > 0; i--) {
422                Long tempLong1 = tempArray.get(i);
423                Long tempLong2 = tempArray.get(i - 1);
424                // here is where we will in missing data
425                while ((((tempLong1 / 1000) / 60) - ((tempLong2 / 1000) / 60) > (((getSnapshotDuration() / 1000) / 60) * skipCount))
426                        && i > 0) {
427                    tempLong1 = tempLong1 - (getSnapshotDuration() * skipCount);
428                    snapshotList.remove(tempArray.get(0));
429                    snapshotList.put(tempLong1, new Long(0));
430                    tempArray.remove(0);
431                    i--;
432                }
433            }
434            return snapshotList;
435        }
436    
437        @SuppressWarnings("unchecked")
438        public HashMap<String, HashMap<String, Object>> getLatestSnapshots()
439                throws Exception {
440            int snapCount = 1;
441            int skipCount = 1;
442            ArrayList<HashMap<String, HashMap<String, Object>>> snapshotList = null;
443            if (Protocol == 1) {
444    
445                snapshotList = mrc.fetchSnapshotData(snapCount, skipCount);
446    
447            } else {
448                snapshotList = (ArrayList<HashMap<String, HashMap<String, Object>>>) mbServerConn
449                        .invoke(new ObjectName(PATH), "fetchSnapshotData",
450                                new Object[] { snapCount, skipCount },
451                                new String[] { "java.lang.Integer",
452                                        "java.lang.Integer" });
453            }
454            // Check if snapshotList is empty
455            if (snapshotList.size() == 0) {
456                return null;
457            } else
458                return snapshotList.get(0);
459        }
460    
461        /**
462         * @return - Returns a boolean indicating successful stop
463         * @throws Exception -
464         *             If the connection to the MRC-Server fails
465         */
466        public boolean stopSnapshotThread() throws Exception {
467            if (Protocol == 1) {
468    
469                return mrc.stopSnapshot();
470    
471            } else {
472                return (Boolean) mbServerConn.invoke(new ObjectName(PATH),
473                        "stopSnapshot", new Object[] {}, new String[] {});
474            }
475        }
476    
477        /**
478         * @return - Returns a boolean indicating successful stop
479         * @throws Exception -
480         *             If the connection to the MRC-Server fails
481         */
482        public boolean startSnapshotThread(long time) throws Exception {
483            if (Protocol == 1) {
484    
485                return mrc.startSnapshot(time);
486    
487            } else {
488                return (Boolean) mbServerConn.invoke(new ObjectName(PATH),
489                        "startSnapshot", new Object[] { time },
490                        new String[] { "java.lang.Long" });
491            }
492        }
493    
494        public int isSnapshotRunning() {
495            Integer running = 0;
496            if (Protocol == 1) {
497    
498                try {
499                    if (mrc.isSnapshotRunning())
500                        running = 1;
501                } catch (Exception e) {
502                    return 0;
503                }
504    
505            } else {
506                try {
507                    running = (Integer) mbServerConn.invoke(new ObjectName(PATH),
508                            "SnapshotStatus", new Object[] {}, new String[] {});
509                } catch (Exception e) {
510                    e.printStackTrace();
511                    return 0;
512                }
513            }
514            return running;
515        }
516    
517        @SuppressWarnings("unchecked")
518        public Set<String> getAllMbeanNames() throws Exception {
519            if (Protocol == 1) {
520    
521                return mrc.getAllMBeanNames();
522    
523            } else {
524                return (Set<String>) mbServerConn.invoke(new ObjectName(PATH),
525                        "getAllMBeanNames", new Object[] {}, new String[] {});
526            }
527        }
528    
529        @SuppressWarnings("unchecked")
530        public Set<String> getStatisticsProviderBeanNames() throws Exception {
531            if (Protocol == 1) {
532    
533                return mrc.getStatisticsProviderMBeanNames();
534    
535            } else {
536                return (Set<String>) mbServerConn.invoke(new ObjectName(PATH),
537                        "getStatisticsProviderMBeanNames", new Object[] {},
538                        new String[] {});
539            }
540        }
541    
542        @SuppressWarnings("unchecked")
543        public HashMap<String, ArrayList<String>> getAllSnapshotStatAttributes()
544                throws Exception {
545            if (Protocol == 1) {
546    
547                return mrc.getAllSnapshotStatAttributes();
548    
549            } else {
550                return (HashMap<String, ArrayList<String>>) mbServerConn.invoke(
551                        new ObjectName(PATH), "getAllSnapshotStatAttributes",
552                        new Object[] {}, new String[] {});
553            }
554        }
555    
556        @SuppressWarnings("unchecked")
557        public Set<String> getTrackedBeans() throws Exception {
558            if (Protocol == 1) {
559    
560                return mrc.getTrackedMBeans();
561    
562            } else {
563                return (Set<String>) mbServerConn.invoke(new ObjectName(PATH),
564                        "getTrackedMBeans", new Object[] {}, new String[] {});
565            }
566        }
567    
568        @SuppressWarnings("unchecked")
569        public Set<String> getStatAttributesOnMBean(String mBean) throws Exception {
570            HashMap<String, ArrayList<String>> allStatAttributes = getAllSnapshotStatAttributes();
571            ArrayList<String> tempArrayList = allStatAttributes.get(mBean);
572            Set<String> tempSet = new TreeSet<String>();
573            Iterator it = tempArrayList.iterator();
574            while (it.hasNext()) {
575                tempSet.add(it.next().toString());
576            }
577            return tempSet;
578        }
579    
580        @SuppressWarnings("unchecked")
581        public Set<String> getTrackedBeansPretty() throws Exception {
582            Set trackedBeans = getTrackedBeans();
583            Set prettybeans = new TreeSet();
584            Iterator it = trackedBeans.iterator();
585            while (it.hasNext()) {
586                String[] temparray1 = it.next().toString().split("name=");
587                String[] temparray2 = temparray1[1].split(",");
588                String[] temparray3 = temparray2[0].split("/");
589                String mbeanName = null;
590                if (temparray3.length > 1)
591                    mbeanName = temparray3[1];
592                else
593                    mbeanName = temparray2[0];
594                prettybeans.add(mbeanName);
595            }
596            return prettybeans;
597        }
598    
599        @SuppressWarnings("unchecked")
600        public TreeMap<String, String> getTrackedBeansMap() throws Exception {
601            Set trackedBeans = getTrackedBeans();
602            TreeMap<String, String> beanMap = new TreeMap<String, String>();
603            Iterator it = trackedBeans.iterator();
604            while (it.hasNext()) {
605                String mbeanName = it.next().toString();
606                String[] temparray1 = mbeanName.split("name=");
607                String[] temparray2 = temparray1[1].split(",");
608                String[] temparray3 = temparray2[0].split("/");
609                String mbeanNamePretty = null;
610                if (temparray3.length > 1)
611                    mbeanNamePretty = temparray3[1];
612                else
613                    mbeanNamePretty = temparray2[0];
614                beanMap.put(mbeanNamePretty, mbeanName);
615            }
616            return beanMap;
617        }
618    
619        @SuppressWarnings("unchecked")
620        public Set<String> getStatisticsProviderBeanNamesPretty() throws Exception {
621            Set availableBeans = getStatisticsProviderBeanNames();
622            Set prettybeans = new TreeSet();
623            Iterator it = availableBeans.iterator();
624            while (it.hasNext()) {
625                String[] temparray1 = it.next().toString().split("name=");
626                String[] temparray2 = temparray1[1].split(",");
627                String[] temparray3 = temparray2[0].split("/");
628                String mbeanName = null;
629                if (temparray3.length > 1)
630                    mbeanName = temparray3[1];
631                else
632                    mbeanName = temparray2[0];
633                prettybeans.add(mbeanName);
634            }
635            return prettybeans;
636        }
637    
638        @SuppressWarnings("unchecked")
639        public TreeMap<String, String> getStatisticsProviderBeanNamesMap()
640                throws Exception {
641            Set availableBeans = getStatisticsProviderBeanNames();
642            TreeMap<String, String> beanMap = new TreeMap<String, String>();
643            Iterator it = availableBeans.iterator();
644            while (it.hasNext()) {
645                String mbeanName = it.next().toString();
646                String[] temparray1 = mbeanName.split("name=");
647                String[] temparray2 = temparray1[1].split(",");
648                String[] temparray3 = temparray2[0].split("/");
649                String mbeanNamePretty = null;
650                if (temparray3.length > 1)
651                    mbeanNamePretty = temparray3[1];
652                else
653                    mbeanNamePretty = temparray2[0];
654                beanMap.put(mbeanNamePretty, mbeanName);
655            }
656            return beanMap;
657        }
658    
659        @SuppressWarnings("unchecked")
660        public Set<String> getFreeStatisticsProviderBeanNamesPretty()
661                throws Exception {
662            Set<String> availableBeans = getStatisticsProviderBeanNamesPretty();
663            Set<String> usedBeans = getTrackedBeansPretty();
664            Set freeBeans = new TreeSet();
665            Iterator it = availableBeans.iterator();
666            while (it.hasNext()) {
667                String mbeanName = it.next().toString();
668                if (!usedBeans.contains(mbeanName))
669                    freeBeans.add(mbeanName);
670            }
671            return freeBeans;
672        }
673    
674        @SuppressWarnings("unchecked")
675        public Set<String> getFreeStatisticsProviderBeanNames() throws Exception {
676            Set<String> availableBeans = getStatisticsProviderBeanNames();
677            Set<String> usedBeans = getTrackedBeansPretty();
678            Set freeBeans = new TreeSet();
679            Iterator it = availableBeans.iterator();
680            while (it.hasNext()) {
681                String mbeanName = it.next().toString();
682                String[] temparray1 = mbeanName.split("name=");
683                String[] temparray2 = temparray1[1].split(",");
684                String[] temparray3 = temparray2[0].split("/");
685                String mbeanNamePretty = null;
686                if (temparray3.length > 1)
687                    mbeanNamePretty = temparray3[1];
688                else
689                    mbeanNamePretty = temparray2[0];
690                if (!usedBeans.contains(mbeanNamePretty))
691                    freeBeans.add(mbeanName);
692            }
693            return freeBeans;
694        }
695    
696        @SuppressWarnings("unchecked")
697        public TreeMap<String, String> getFreeStatisticsProviderBeanNamesMap()
698                throws Exception {
699            Set<String> availableBeans = getStatisticsProviderBeanNames();
700            Set<String> usedBeans = getTrackedBeansPretty();
701            TreeMap<String, String> beanMap = new TreeMap<String, String>();
702            Iterator it = availableBeans.iterator();
703            while (it.hasNext()) {
704                String mbeanName = it.next().toString();
705                String[] temparray1 = mbeanName.split("name=");
706                String[] temparray2 = temparray1[1].split(",");
707                String[] temparray3 = temparray2[0].split("/");
708                String mbeanNamePretty = null;
709                if (temparray3.length > 1)
710                    mbeanNamePretty = temparray3[1];
711                else
712                    mbeanNamePretty = temparray2[0];
713                if (!usedBeans.contains(mbeanNamePretty))
714                    beanMap.put(mbeanNamePretty, mbeanName);
715            }
716            return beanMap;
717        }
718    
719        @SuppressWarnings("unchecked")
720        public boolean stopTrackingMbean(String MBean) throws Exception {
721            if (Protocol == 1) {
722    
723                mrc.removeMBeanForSnapshot(MBean);
724    
725            } else {
726                mbServerConn
727                        .invoke(new ObjectName(PATH), "removeMBeanForSnapshot",
728                                new Object[] { MBean },
729                                new String[] { "java.lang.String" });
730    
731            }
732            return true;
733        }
734    
735        @SuppressWarnings("unchecked")
736        public boolean startTrackingMbean(String MBean) throws Exception {
737            if (Protocol == 1) {
738    
739                mrc.addMBeanForSnapshot(MBean);
740    
741            } else {
742                mbServerConn
743                        .invoke(new ObjectName(PATH), "addMBeanForSnapshot",
744                                new Object[] { MBean },
745                                new String[] { "java.lang.String" });
746            }
747            return true;
748        }
749    
750        @SuppressWarnings("unchecked")
751        public HashMap<String, Long> getStats(String MBean) throws Exception {
752            if (Protocol == 1) {
753    
754                return mrc.getStats(MBean);
755    
756            } else {
757                return (HashMap<String, Long>) mbServerConn.invoke(new ObjectName(
758                        PATH), "getStats", new Object[] { MBean },
759                        new String[] { "java.lang.String" });
760            }
761        }
762    
763        public void setSnapshotDuration(long duration) {
764            if (Protocol == 1) {
765    
766                mrc.setSnapshotDuration(new Long(duration));
767    
768            } else {
769                try {
770    
771                    mbServerConn.invoke(new ObjectName(PATH),
772                            "setSnapshotDuration",
773                            new Object[] { new Long(duration) },
774                            new String[] { "java.lang.Long" });
775                } catch (Exception e) {
776                    e.printStackTrace();
777                }
778            }
779        }
780    
781        public int getSnapshotRetention() {
782            if (Protocol == 1) {
783    
784                return Integer.parseInt(mrc.getSnapshotRetention());
785    
786            } else {
787                try {
788                    return (Integer) mbServerConn.invoke(new ObjectName(PATH),
789                            "getSnapshotRetention", new Object[] {},
790                            new String[] {});
791                } catch (Exception e) {
792                    e.printStackTrace();
793                }
794            }
795            return 0;
796        }
797    
798        public void setSnapshotRetention(int duration) {
799            if (Protocol == 1) {
800    
801                mrc.setSnapshotRetention(duration);
802    
803            } else {
804                try {
805                    mbServerConn.invoke(new ObjectName(PATH),
806                            "setSnapshotRetention", new Object[] { duration },
807                            new String[] { "java.lang.Integer" });
808                } catch (Exception e) {
809                    e.printStackTrace();
810                }
811            }
812        }
813    }