Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.codahale.metrics;
  
  import org.slf4j.Logger;
  
  import javax.management.*;
  import java.io.Closeable;
 import java.util.Map;
 import java.util.Set;
A reporter which listens for new metrics and exposes them as namespaced MBeans.
 
 public class JmxReporter implements Closeable {
    
Returns a new JmxReporter.Builder for JmxReporter.

Parameters:
registry the registry to report
Returns:
a JmxReporter.Builder instance for a JmxReporter
 
     public static Builder forRegistry(MetricRegistry registry) {
         return new Builder(registry);
     }

    
A builder for CsvReporter instances. Defaults to using the default MBean server and not filtering metrics.
 
     public static class Builder {
         private final MetricRegistry registry;
         private MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
         private TimeUnit rateUnit;
         private TimeUnit durationUnit;
         private MetricFilter filter = .;
         private String domain;
         private Map<StringTimeUnitspecificDurationUnits;
         private Map<StringTimeUnitspecificRateUnits;
 
         private Builder(MetricRegistry registry) {
             this. = registry;
             this. = .;
             this. = .;
             this. = "metrics";
             this. = Collections.emptyMap();
             this. = Collections.emptyMap();
         }

        
Register MBeans with the given javax.management.MBeanServer.

Parameters:
mBeanServer an javax.management.MBeanServer
Returns:
this
 
         public Builder registerWith(MBeanServer mBeanServer) {
             this. = mBeanServer;
             return this;
         }

        
Convert rates to the given time unit.

Parameters:
rateUnit a unit of time
Returns:
this
 
         public Builder convertRatesTo(TimeUnit rateUnit) {
             this. = rateUnit;
             return this;
         }

        
Convert durations to the given time unit.

Parameters:
durationUnit a unit of time
Returns:
this
 
         public Builder convertDurationsTo(TimeUnit durationUnit) {
             this. = durationUnit;
             return this;
         }

        
Only report metrics which match the given filter.

Parameters:
filter a MetricFilter
Returns:
this
 
         public Builder filter(MetricFilter filter) {
             this. = filter;
             return this;
         }
 
         public Builder inDomain(String domain) {
             this. = domain;
             return this;
        }

        
Use specific java.util.concurrent.TimeUnits for the duration of the metrics with these names.

Parameters:
specificDurationUnits a map of metric names and specific java.util.concurrent.TimeUnits
Returns:
this
        public Builder specificDurationUnits(Map<StringTimeUnitspecificDurationUnits) {
            this. = Collections.unmodifiableMap(specificDurationUnits);
            return this;
        }


        
Use specific java.util.concurrent.TimeUnits for the rate of the metrics with these names.

Parameters:
specificRateUnits a map of metric names and specific java.util.concurrent.TimeUnits
Returns:
this
        public Builder specificRateUnits(Map<StringTimeUnitspecificRateUnits) {
            this. = Collections.unmodifiableMap(specificRateUnits);
            return this;
        }

        
Builds a JmxReporter with the given properties.

Returns:
a JmxReporter
        public JmxReporter build() {
            final MetricTimeUnits timeUnits = new MetricTimeUnits();
            return new JmxReporter(timeUnits);
        }
    }
    private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class);
    // CHECKSTYLE:OFF
    @SuppressWarnings("UnusedDeclaration")
    public interface MetricMBean {
        ObjectName objectName();
    }
    // CHECKSTYLE:ON
    private abstract static class AbstractBean implements MetricMBean {
        private final ObjectName objectName;
        AbstractBean(ObjectName objectName) {
            this. = objectName;
        }
        @Override
        public ObjectName objectName() {
            return ;
        }
    }
    // CHECKSTYLE:OFF
    @SuppressWarnings("UnusedDeclaration")
    public interface JmxGaugeMBean extends MetricMBean {
        Object getValue();
    }
    // CHECKSTYLE:ON
    private static class JmxGauge extends AbstractBean implements JmxGaugeMBean {
        private final Gauge<?> metric;
        private JmxGauge(Gauge<?> metricObjectName objectName) {
            super(objectName);
            this. = metric;
        }
        @Override
        public Object getValue() {
            return .getValue();
        }
    }
    // CHECKSTYLE:OFF
    @SuppressWarnings("UnusedDeclaration")
    public interface JmxCounterMBean extends MetricMBean {
        long getCount();
    }
    // CHECKSTYLE:ON
    private static class JmxCounter extends AbstractBean implements JmxCounterMBean {
        private final Counter metric;
        private JmxCounter(Counter metricObjectName objectName) {
            super(objectName);
            this. = metric;
        }
        @Override
        public long getCount() {
            return .getCount();
        }
    }
    // CHECKSTYLE:OFF
    @SuppressWarnings("UnusedDeclaration")
    public interface JmxHistogramMBean extends MetricMBean {
        long getCount();
        long getMin();
        long getMax();
        double getMean();
        double getStdDev();
        double get50thPercentile();
        double get75thPercentile();
        double get95thPercentile();
        double get98thPercentile();
        double get99thPercentile();
        double get999thPercentile();
        long[] values();
    }
    // CHECKSTYLE:ON
    private static class JmxHistogram implements JmxHistogramMBean {
        private final ObjectName objectName;
        private final Histogram metric;
        private JmxHistogram(Histogram metricObjectName objectName) {
            this. = metric;
            this. = objectName;
        }
        @Override
        public ObjectName objectName() {
            return ;
        }
        @Override
        public double get50thPercentile() {
            return .getSnapshot().getMedian();
        }
        @Override
        public long getCount() {
            return .getCount();
        }
        @Override
        public long getMin() {
            return .getSnapshot().getMin();
        }
        @Override
        public long getMax() {
            return .getSnapshot().getMax();
        }
        @Override
        public double getMean() {
            return .getSnapshot().getMean();
        }
        @Override
        public double getStdDev() {
            return .getSnapshot().getStdDev();
        }
        @Override
        public double get75thPercentile() {
            return .getSnapshot().get75thPercentile();
        }
        @Override
        public double get95thPercentile() {
            return .getSnapshot().get95thPercentile();
        }
        @Override
        public double get98thPercentile() {
            return .getSnapshot().get98thPercentile();
        }
        @Override
        public double get99thPercentile() {
            return .getSnapshot().get99thPercentile();
        }
        @Override
        public double get999thPercentile() {
            return .getSnapshot().get999thPercentile();
        }
        @Override
        public long[] values() {
            return .getSnapshot().getValues();
        }
    }
    //CHECKSTYLE:OFF
    @SuppressWarnings("UnusedDeclaration")
    public interface JmxMeterMBean extends MetricMBean {
        long getCount();
        double getMeanRate();
        double getOneMinuteRate();
        double getFiveMinuteRate();
        double getFifteenMinuteRate();
        String getRateUnit();
    }
    //CHECKSTYLE:ON
    private static class JmxMeter extends AbstractBean implements JmxMeterMBean {
        private final Metered metric;
        private final double rateFactor;
        private final String rateUnit;
        private JmxMeter(Metered metricObjectName objectNameTimeUnit rateUnit) {
            super(objectName);
            this. = metric;
            this. = rateUnit.toSeconds(1);
            this. = "events/" + calculateRateUnit(rateUnit);
        }
        @Override
        public long getCount() {
            return .getCount();
        }
        @Override
        public double getMeanRate() {
            return .getMeanRate() * ;
        }
        @Override
        public double getOneMinuteRate() {
            return .getOneMinuteRate() * ;
        }
        @Override
        public double getFiveMinuteRate() {
            return .getFiveMinuteRate() * ;
        }
        @Override
        public double getFifteenMinuteRate() {
            return .getFifteenMinuteRate() * ;
        }
        @Override
        public String getRateUnit() {
            return ;
        }
        private String calculateRateUnit(TimeUnit unit) {
            final String s = unit.toString().toLowerCase(.);
            return s.substring(0, s.length() - 1);
        }
    }
    // CHECKSTYLE:OFF
    @SuppressWarnings("UnusedDeclaration")
    public interface JmxTimerMBean extends JmxMeterMBean {
        double getMin();
        double getMax();
        double getMean();
        double getStdDev();
        double get50thPercentile();
        double get75thPercentile();
        double get95thPercentile();
        double get98thPercentile();
        double get99thPercentile();
        double get999thPercentile();
        long[] values();
        String getDurationUnit();
    }
    // CHECKSTYLE:ON
    static class JmxTimer extends JmxMeter implements JmxTimerMBean {
        private final Timer metric;
        private final double durationFactor;
        private final String durationUnit;
        private JmxTimer(Timer metric,
                         ObjectName objectName,
                         TimeUnit rateUnit,
                         TimeUnit durationUnit) {
            super(metricobjectNamerateUnit);
            this. = metric;
            this. = 1.0 / durationUnit.toNanos(1);
            this. = durationUnit.toString().toLowerCase(.);
        }
        @Override
        public double get50thPercentile() {
            return .getSnapshot().getMedian() * ;
        }
        @Override
        public double getMin() {
            return .getSnapshot().getMin() * ;
        }
        @Override
        public double getMax() {
            return .getSnapshot().getMax() * ;
        }
        @Override
        public double getMean() {
            return .getSnapshot().getMean() * ;
        }
        @Override
        public double getStdDev() {
            return .getSnapshot().getStdDev() * ;
        }
        @Override
        public double get75thPercentile() {
            return .getSnapshot().get75thPercentile() * ;
        }
        @Override
        public double get95thPercentile() {
            return .getSnapshot().get95thPercentile() * ;
        }
        @Override
        public double get98thPercentile() {
            return .getSnapshot().get98thPercentile() * ;
        }
        @Override
        public double get99thPercentile() {
            return .getSnapshot().get99thPercentile() * ;
        }
        @Override
        public double get999thPercentile() {
            return .getSnapshot().get999thPercentile() * ;
        }
        @Override
        public long[] values() {
            return .getSnapshot().getValues();
        }
        @Override
        public String getDurationUnit() {
            return ;
        }
    }
    private static class JmxListener implements MetricRegistryListener {
        private final String name;
        private final MBeanServer mBeanServer;
        private final MetricFilter filter;
        private final MetricTimeUnits timeUnits;
        private final Set<ObjectNameregistered;
        private JmxListener(MBeanServer mBeanServerString nameMetricFilter filterMetricTimeUnits timeUnits) {
            this. = mBeanServer;
            this. = name;
            this. = filter;
            this. = timeUnits;
            this. = new CopyOnWriteArraySet<ObjectName>();
        }
        @Override
        public void onGaugeAdded(String nameGauge<?> gauge) {
            try {
                if (.matches(namegauge)) {
                    final ObjectName objectName = createName("gauges"name);
                    .registerMBean(new JmxGauge(gaugeobjectName), objectName);
                    .add(objectName);
                }
            } catch (InstanceAlreadyExistsException e) {
                .debug("Unable to register gauge"e);
            } catch (JMException e) {
                .warn("Unable to register gauge"e);
            }
        }
        @Override
        public void onGaugeRemoved(String name) {
            try {
                final ObjectName objectName = createName("gauges"name);
                .unregisterMBean(objectName);
                .remove(objectName);
            } catch (InstanceNotFoundException e) {
                .debug("Unable to unregister gauge"e);
            } catch (MBeanRegistrationException e) {
                .warn("Unable to unregister gauge"e);
            }
        }
        @Override
        public void onCounterAdded(String nameCounter counter) {
            try {
                if (.matches(namecounter)) {
                    final ObjectName objectName = createName("counters"name);
                    .registerMBean(new JmxCounter(counterobjectName), objectName);
                    .add(objectName);
                }
            } catch (InstanceAlreadyExistsException e) {
                .debug("Unable to register counter"e);
            } catch (JMException e) {
                .warn("Unable to register counter"e);
            }
        }
        @Override
        public void onCounterRemoved(String name) {
            try {
                final ObjectName objectName = createName("counters"name);
                .unregisterMBean(objectName);
                .remove(objectName);
            } catch (InstanceNotFoundException e) {
                .debug("Unable to unregister counter"e);
            } catch (MBeanRegistrationException e) {
                .warn("Unable to unregister counter"e);
            }
        }
        @Override
        public void onHistogramAdded(String nameHistogram histogram) {
            try {
                if (.matches(namehistogram)) {
                    final ObjectName objectName = createName("histograms"name);
                    .registerMBean(new JmxHistogram(histogramobjectName), objectName);
                    .add(objectName);
                }
            } catch (InstanceAlreadyExistsException e) {
                .debug("Unable to register histogram"e);
            } catch (JMException e) {
                .warn("Unable to register histogram"e);
            }
        }
        @Override
        public void onHistogramRemoved(String name) {
            try {
                final ObjectName objectName = createName("histograms"name);
                .unregisterMBean(objectName);
                .remove(objectName);
            } catch (InstanceNotFoundException e) {
                .debug("Unable to unregister histogram"e);
            } catch (MBeanRegistrationException e) {
                .warn("Unable to unregister histogram"e);
            }
        }
        @Override
        public void onMeterAdded(String nameMeter meter) {
            try {
                if (.matches(namemeter)) {
                    final ObjectName objectName = createName("meters"name);
                    .registerMBean(new JmxMeter(meterobjectName.rateFor(name)), objectName);
                    .add(objectName);
                }
            } catch (InstanceAlreadyExistsException e) {
                .debug("Unable to register meter"e);
            } catch (JMException e) {
                .warn("Unable to register meter"e);
            }
        }
        @Override
        public void onMeterRemoved(String name) {
            try {
                final ObjectName objectName = createName("meters"name);
                .unregisterMBean(objectName);
                .remove(objectName);
            } catch (InstanceNotFoundException e) {
                .debug("Unable to unregister meter"e);
            } catch (MBeanRegistrationException e) {
                .warn("Unable to unregister meter"e);
            }
        }
        @Override
        public void onTimerAdded(String nameTimer timer) {
            try {
                if (.matches(nametimer)) {
                    final ObjectName objectName = createName("timers"name);
                    .registerMBean(new JmxTimer(timerobjectName.rateFor(name), .durationFor(name)), objectName);
                    .add(objectName);
                }
            } catch (InstanceAlreadyExistsException e) {
                .debug("Unable to register timer"e);
            } catch (JMException e) {
                .warn("Unable to register timer"e);
            }
        }
        @Override
        public void onTimerRemoved(String name) {
            try {
                final ObjectName objectName = createName("timers"name);
                .unregisterMBean(objectName);
                .add(objectName);
            } catch (InstanceNotFoundException e) {
                .debug("Unable to unregister timer"e);
            } catch (MBeanRegistrationException e) {
                .warn("Unable to unregister timer"e);
            }
        }
        private ObjectName createName(String typeString name) {
            try {
                return new ObjectName(this."name"name);
            } catch (MalformedObjectNameException e) {
                try {
                    return new ObjectName(this."name", ObjectName.quote(name));
                } catch (MalformedObjectNameException e1) {
                    .warn("Unable to register {} {}"typenamee1);
                    throw new RuntimeException(e1);
                }
            }
        }
        void unregisterAll() {
            for (ObjectName name : ) {
                try {
                    .unregisterMBean(name);
                } catch (InstanceNotFoundException e) {
                    .debug("Unable to unregister metric"e);
                } catch (MBeanRegistrationException e) {
                    .warn("Unable to unregister metric"e);
                }
            }
            .clear();
        }
    }
    private static class MetricTimeUnits {
        private final TimeUnit defaultRate;
        private final TimeUnit defaultDuration;
        private final Map<StringTimeUnitrateOverrides;
        private final Map<StringTimeUnitdurationOverrides;
        MetricTimeUnits(TimeUnit defaultRate,
                        TimeUnit defaultDuration,
                        Map<StringTimeUnitrateOverrides,
                        Map<StringTimeUnitdurationOverrides) {
            this. = defaultRate;
            this. = defaultDuration;
            this. = rateOverrides;
            this. = durationOverrides;
        }
        public TimeUnit durationFor(String name) {
            return .containsKey(name) ? .get(name) : ;
        }
        public TimeUnit rateFor(String name) {
            return .containsKey(name) ? .get(name) : ;
        }
    }
    private final MetricRegistry registry;
    private final JmxListener listener;
    private JmxReporter(MBeanServer mBeanServer,
                        String domain,
                        MetricRegistry registry,
                        MetricFilter filter,
                        MetricTimeUnits timeUnits) {
        this. = registry;
        this. = new JmxListener(mBeanServerdomainfiltertimeUnits);
    }

    
Starts the reporter.
    public void start() {
        .addListener();
    }

    
Stops the reporter.
    public void stop() {
        .unregisterAll();
    }

    
Stops the reporter.
    @Override
    public void close() {
        stop();
    }
New to GrepCode? Check out our FAQ X