Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
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.geronimo.monitoring.jmx;
 
 import java.util.Set;
 
 
 
 
 
 
This is the GBean that will be the bottleneck for the communication between the management node and the data in the server node.
 
 public class MasterRemoteControlJMX implements GBeanLifecycle {
     private static final Logger log = LoggerFactory.getLogger(MasterRemoteControlJMX.class);
 
     // mbean server to talk to other components
     private static MBeanServer mbServer = null;
     
     // threads
     private static SnapshotThread snapshotThread = null;
     
     // datasources
     private DataSource activeDS;
     private DataSource archiveDS;
 
 
     public MasterRemoteControlJMX() {
         // retrieve the mbean server
         ArrayList mbServerList = MBeanServerFactory.findMBeanServer(null);
         if(mbServerList.size() >= 1) {
              = (MBeanServermbServerList.get(0);
             for(int i = 0; i < mbServerList.size(); i++) {
                 String domain = ((MBeanServer)mbServerList.get(i)).getDefaultDomain();
                 if(domain.equals. )) {
                      = (MBeanServer)mbServerList.get(i);
                     break;
                 }
             }
         }
         // ensure that the mbServer has something in it
         if( == null) {
              = MBeanServerFactory.createMBeanServer. );
         }
        
         // set up SnaphotDBHelper with the necessary data sources
         // Note: do not put this in the constructor...datasources are not injected by then
         try {
             InitialContext ic = new InitialContext();
              = (DataSource)ic.lookup("jca:/org.apache.geronimo.plugins.monitoring/agent-ds/JCAConnectionManager/jdbc/ActiveDS");
              = (DataSource)ic.lookup("jca:/org.apache.geronimo.plugins.monitoring/agent-ds/JCAConnectionManager/jdbc/ArchiveDS");
         } catch(Exception e) {
             .error(e.getMessage());
         }
          = new SnapshotDBHelper();
    }
    
    
Looks up the JSR-77 statistics associated with this object name.

Parameters:
objectName
Returns:
HashMap
Throws:
java.lang.Exception
    public static HashMap getStats(String objectNamethrows Exception {
        HashMap statsMap = new HashMap();
        Stats stats = (Stats).getAttribute(new ObjectName(objectName), "stats");
        String[] sttsName = stats.getStatisticNames();
        Statistic[] stts = stats.getStatistics();
        for(int i = 0; i < sttsName.lengthi++) {
            Statistic aStat = stats.getStatistic(sttsName[i]);
            if(aStat instanceof RangeStatistic) {
                Long current = new Long(((RangeStatistic)aStat).getCurrent());
                Long high = new Long(((RangeStatistic)aStat).getHighWaterMark());
                Long low = new Long(((RangeStatistic)aStat).getLowWaterMark());
                statsMap.put(stts[i].getName() + " Current"current);
                statsMap.put(stts[i].getName() + " Max"high);
                statsMap.put(stts[i].getName() + " Min"low);
            } else if(aStat instanceof CountStatistic) {
                Long current = new Long(((CountStatistic)aStat).getCount());
                statsMap.put(stts[i].getName(), current);
            } else if(aStat instanceof TimeStatistic) {
                Long current = new Long(((TimeStatistic)aStat).getCount());
                Long max = new Long(((TimeStatistic)aStat).getMaxTime());
                Long min = new Long(((TimeStatistic)aStat).getMinTime());
                Long total = new Long(((TimeStatistic)aStat).getTotalTime());
                statsMap.put(stts[i].getName() + " CurrentTime"current);
                statsMap.put(stts[i].getName() + " MaxTime"max);
                statsMap.put(stts[i].getName() + " MinTime"min);
                statsMap.put(stts[i].getName() + " TotalTime"total);
            } else {
                // this should never happen
                throw new Exception();
            }
        }
        return statsMap;
    }
    
    
Changes the objectName's attrName's value to attrValue

Parameters:
objectName
attrName
attrValue
Throws:
java.lang.Exception
    public void setAttribute(String objectNameString attrNameObject attrValuethrows Exception {
        Attribute attr = new Attribute(attrNameattrValue);
        .setAttribute(new ObjectName(objectName), attr);
    }
    
    
Stops the snapshot thread and save the started status
    public boolean stopSnapshot() {
        setSnapshotStarted(false);
        return stopSnapshotThread();
    }
    
    
Stops the snapshot thread
    private boolean stopSnapshotThread() {
        if( != null) {
            if(.getSnapshotDuration() != .) {
                saveDuration(.getSnapshotDuration());
                .setSnapshotDuration(.);
                .info("Snapshot thread stopped.");
                return true;
            } else {
                return false;
            }
        } else {
            .error("There is not a snapshot thread running. Stopping aborted.");
            return false;
        }
    }
    
    
Fetches the data stored from the snapshot thread and returns it in a ArrayList with each element being a HashMap of the attribute mapping to the statistic. All stats will be the average of 1 - n, n+1 - 2n, ..., cn+1 - c(n+1) Grabs 'numberOfSnapshots' snapshots. Grabs one snapshot per 'everyNthsnapshot'

Parameters:
numberOfSnapshot
everyNthSnapshot
Returns:
ArrayList
 
    public ArrayList<HashMap<StringHashMap<StringObject>>> fetchSnapshotData(Integer numberOfSnapshotInteger everyNthSnapshot) {
        return .fetchData(numberOfSnapshoteveryNthSnapshot);
    }
    
    
Fetches the max amount for each statistic stored from the snapshot thread and returns it in a HashMap

Parameters:
numberOfSnapshot
Returns:
HashMap
    public HashMap<StringHashMap<StringLong>> fetchMaxSnapshotData(Integer numberOfSnapshot) {
        return .fetchMaxSnapshotData(numberOfSnapshot);
    }

    
Fetches the min amount for each statistic stored from the snapshot thread and returns it in a HashMap

Parameters:
numberOfSnapshot
Returns:
HashMap
    public HashMap<StringHashMap<StringLong>> fetchMinSnapshotData(Integer numberOfSnapshot) {
        return .fetchMinSnapshotData(numberOfSnapshot);
    }
    
    
Gets the elapsed time in milliseconds between each snapshot.

Returns:
Long
    public Long getSnapshotDuration() {
        try {
            return Long.parseLong(SnapshotConfigXMLBuilder.getAttributeValue. ));
        } catch(Exception e) {
            return new Long. );
        }
    }
    
    
Sets the elapsed time in milliseconds between each snapshot.

Parameters:
snapshotDuration
    public void setSnapshotDuration(Long snapshotDuration) {
        if( != null) {
            .setSnapshotDuration(snapshotDuration.longValue());
        } else {
            .warn("There is not a snapshot thread instantiated.");
        }
    }
    
    public void setSnapshotRetention(Integer retention) {
        saveRetention(retention.intValue());
    }
    
    public void setSnapshotStarted(Boolean started) {
        saveStarted(started.booleanValue());
    }
    
    
Begins the snapshot process given the time interval between snapshots Precondition: interval is given in milli seconds

Parameters:
interval
    public boolean startSnapshot(Long interval) {
        setSnapshotStarted(true);
        // get the saved/default retention period
        String retentionStr = null;
        try {
            retentionStr = SnapshotConfigXMLBuilder.getAttributeValue. );
        } catch(Exception e){
            // happens when there is not an instance of "retention" in the config
            // which is okay.
        }
        int retention;
        if(retentionStr == null) {
            retention = .;
        } else {
            retention = Integer.parseInt(retentionStr);
        }
        return startSnapshot(intervalnew Integer(retention));
    }
    
    
Begins the snapshot process given the time interval between snapshots Precondition: interval is given in milli seconds

Parameters:
interval
    public boolean startSnapshot(Long intervalInteger retention) {
        if(( == null || ( != null && (.SnapshotStatus() == 0))) && interval.longValue() > 0) {
            saveDuration(interval.longValue());
            saveRetention(retention.intValue());
             = new SnapshotThread(interval.longValue(), );
            .start();
            .info("Snapshot thread successfully created.");
            return true;
        } else {
            .warn("There is already a snapshot thread running.");
            return false;
        }
    }
    
    public Long getSnapshotCount() {
        return .getSnapshotCount();
    }
    
    
Fetches all mbean names that provide JSR-77 statistics

Returns:
A set containing all mbean names of mbeans that provide statistics
        return (Set<String>)MBeanHelper.getStatsProvidersMBeansgetAllMBeanNames() );
    }
    
    
Fetches all mbean names

Returns:
A set containing all mbean names
    public Set<StringgetAllMBeanNames() {
        try {
            Set<ObjectNamenames = (Set<ObjectName>).queryNames(nullnull);
            Set<StringstrNames = new HashSet<String>();
            for(Iterator<ObjectNameit = names.iterator(); it.hasNext(); ) {
                strNames.add(it.next().getCanonicalName());
            }
            return strNames;
       } catch(Exception e) {
            .error(e.getMessage(), e);
            return new HashSet<String>();
        }
    }
    
    public void doFail() {
        doStop();
    }

    
Executes when the GBean starts up. Also starts the snapshot thread.
    public void doStart() {
        boolean started = false;
        try {
            started = Boolean.parseBoolean(
                    SnapshotConfigXMLBuilder.getAttributeValue(.));
        } catch (Exception e) {
            .warn("Failed to parse 'started', set to default value " + startede);            
        }
        if (started) {
            long duration = .;
            try {
                duration = Long.parseLong(
                        SnapshotConfigXMLBuilder.getAttributeValue(.));
            } catch (Exception e) {
                .warn("Failed to parse 'duration', set to default value " + duratione);
            }
            startSnapshot(duration);
        }
    }
    
    
Executes when the GBean stops. Also stops the snapshot thread.
    public void doStop() {
        if(SnapshotStatus() == 1) {
            stopSnapshotThread();
        }
    }
    
    private void saveDuration(long duration) {
        SnapshotConfigXMLBuilder.saveDuration(duration);
    }
    
    private void saveRetention(int retention) {
        SnapshotConfigXMLBuilder.saveRetention(retention);
    }
    
    private void saveStarted(boolean started) {
        SnapshotConfigXMLBuilder.saveStarted(started);
    }
    
    
Adds a record of the mbean via its name to take snapshots of. As a result the mbeanName will be written to snapshot-config.xml

Parameters:
mbeanName
    public boolean addMBeanForSnapshot(String mbeanName) {
        return SnapshotConfigXMLBuilder.addMBeanName(mbeanName);
    }

    
Removes a record of the mbean via its name to take snapshots of. As a result the mbeanName will be removed from snapshot-config.xml

Parameters:
mbeanName
    public boolean removeMBeanForSnapshot(String mbeanName) {
        return SnapshotConfigXMLBuilder.removeMBeanName(mbeanName);
    }
    
    

Returns:
A map: mbeanName --> ArrayList of statistic attributes for that mbean
        HashMap<StringArrayList<String>> snapshotAttributes = new HashMap<StringArrayList<String>>();
        Set<Stringmbeans = getTrackedMBeans();
        // for each mbean name
        for(Iterator<Stringit = mbeans.iterator(); it.hasNext(); ) {
            ArrayList<StringmbeanStatsList = new ArrayList<String>();
            String mbeanName = it.next();
            try {
                Stats stats = (Stats).getAttribute(new ObjectName(mbeanName), "stats");
                String[] sttsName = stats.getStatisticNames();
                Statistic[] stts = stats.getStatistics();
                for(int i = 0; i < sttsName.lengthi++) {
                    Statistic aStat = stats.getStatistic(sttsName[i]);
                    if(aStat instanceof RangeStatistic) {
                        mbeanStatsList.add(stts[i].getName() + " Current");
                        mbeanStatsList.add(stts[i].getName() + " Max");
                        mbeanStatsList.add(stts[i].getName() + " Min");
                    } else if(aStat instanceof CountStatistic) {
                        mbeanStatsList.add(stts[i].getName());
                    } else if(aStat instanceof TimeStatistic) {
                        mbeanStatsList.add(stts[i].getName() + " CurrentTime");
                        mbeanStatsList.add(stts[i].getName() + " MaxTime");
                        mbeanStatsList.add(stts[i].getName() + " MinTime");
                        mbeanStatsList.add(stts[i].getName() + " TotalTime");
                    } else {
                        // for the time being, only numbers should be returned
                    }
                }
            } catch (Exception e) {
                .error(e.getMessage(), e);
            }
            // save attributes to the returning list
            snapshotAttributes.put(mbeanNamembeanStatsList);
        }
        return snapshotAttributes;
    }
    
    public Set<StringgetTrackedMBeans() {
        ArrayList<Stringmbeans = (ArrayList<String>)SnapshotConfigXMLBuilder.getMBeanNames();
        Set<Stringset = new HashSet<String>();
        for(int i = 0; i < mbeans.size(); i++) {
            set.add(mbeans.get(i));
        }
        return set;
    }
    
    public Integer getSnapshotRetention() {
        try {
            return new Integer(SnapshotConfigXMLBuilder.getAttributeValue. ));
        } catch(Exception e) {
            return new Integer(.); // the default
        }
    }
    
    

Parameters:
name - object name of the mbean
operationName - method within the class
params - parameters for the method
signature - types for the parameters
Returns:
Invokes the method of a class defined.
    public Object invoke(ObjectName nameString operationNameObject[] paramsString[] signaturethrows Exception {
        return .invoke(nameoperationNameparamssignature);
    }
    
    

Parameters:
mbeanName
statsName
numberOfSnapshots
everyNthSnapshot
Returns:
HashMap which maps from a snapshot_time --> value of the mbean.statsName at that time
    public TreeMap<LongLonggetSpecificStatistics(   String mbeanName,
                                                        String statsName
                                                        Integer numberOfSnapshots
                                                        Integer everyNthSnapshot,
                                                        Boolean showArchived) {
        return .getSpecificStatistics(mbeanNamestatsNamenumberOfSnapshots.intValue(), everyNthSnapshot.intValue(), showArchived);
    }
    
    

Returns:
Returns true if snapshot is running.
    public Integer SnapshotStatus() {
        // TODO: check if the snapshot thread is running 
        if( == null) {
            return 0;
        } else {
            return .SnapshotStatus();
        }
    }
    public static final GBeanInfo GBEAN_INFO;
    static {
        GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic("MasterRemoteControlJMX"MasterRemoteControlJMX.class);
        infoFactory.addOperation("getStats"new Class[] {String.class}, "HashMap");
        infoFactory.addOperation("setAttribute"new Class[] {String.classString.classObject.class}, "void");
        infoFactory.addOperation("startSnapshot"new Class[] {Long.class}, "Boolean");
        infoFactory.addOperation("startSnapshot"new Class[] {Long.classInteger.class}, "Boolean");
        infoFactory.addOperation("stopSnapshot"new Class[] {}, "Boolean");
        infoFactory.addOperation("fetchSnapshotData"new Class[] {Integer.classInteger.class}, "ArrayList");
        infoFactory.addOperation("fetchMaxSnapshotData"new Class[] {Integer.class}, "HashMap");
        infoFactory.addOperation("fetchMinSnapshotData"new Class[] {Integer.class}, "HashMap");
        infoFactory.addOperation("getSnapshotDuration"new Class[] {}, "Long");
        infoFactory.addOperation("getSnapshotCount"new Class[] {}, "Long");
        infoFactory.addOperation("setSnapshotDuration"new Class[] {Long.class}, "void");
        infoFactory.addOperation("getStatisticsProviderMBeanNames"new Class[] {}, "Set");
        infoFactory.addOperation("getAllMBeanNames"new Class[] {}, "Set");
        infoFactory.addOperation("getAllSnapshotStatAttributes"new Class[] {}, "HashMap");
        infoFactory.addOperation("addMBeanForSnapshot"new Class[] {String.class}, "void");
        infoFactory.addOperation("removeMBeanForSnapshot"new Class[] {String.class}, "void");
        infoFactory.addOperation("getSnapshotRetention"new Class[] {}, "Integer");
        infoFactory.addOperation("setSnapshotRetention"new Class[] {Integer.class}, "void");
        infoFactory.addOperation("SnapshotStatus"new Class[] {}, "Integer");
        infoFactory.addOperation("getSpecificStatistics"new Class[] {String.classString.classInteger.classInteger.classBoolean.class}, "TreeMap");
        infoFactory.addOperation("getTrackedMBeans"new Class[] {}, "Set");
        infoFactory.setConstructor(new String[] {});
         = infoFactory.getBeanInfo();
    }
    public static GBeanInfo getGBeanInfo() {
        return ;
    }
New to GrepCode? Check out our FAQ X