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 io.tehuti.metrics;
 
 import java.util.List;
 import java.util.Map;
 
 
Register metrics in JMX as dynamic mbeans based on the metric names
 
 public class JmxReporter implements MetricsReporter {
 
     private static final Logger log = Logger.getLogger(JmxReporter.class);
     private static final Object lock = new Object();
     private String prefix;
     private final Map<StringTehutiMbeanmbeans = new HashMap<StringTehutiMbean>();
 
     public JmxReporter() {
         this("");
     }

    
Create a JMX reporter that prefixes all metrics with the given string.
 
     public JmxReporter(String prefix) {
         this. = prefix;
     }
 
     @Override
     public void configure(Map<String, ?> configs) {
     }
 
     @Override
     public void init(List<TehutiMetricmetrics) {
         synchronized () {
             for (TehutiMetric metric : metrics)
                 addAttribute(metric);
             for (TehutiMbean mbean : .values())
                 reregister(mbean);
         }
     }
 
     @Override
     public void metricChange(TehutiMetric metric) {
         synchronized () {
             TehutiMbean mbean = addAttribute(metric);
             reregister(mbean);
         }
     }
 
     private TehutiMbean addAttribute(TehutiMetric metric) {
         try {
             String[] names = split( + metric.name());
             String qualifiedName = names[0] + "." + names[1];
             if (!this..containsKey(qualifiedName))
                 .put(qualifiedNamenew TehutiMbean(names[0], names[1]));
             TehutiMbean mbean = this..get(qualifiedName);
             mbean.setAttribute(names[2], metric);
             return mbean;
         } catch (JMException e) {
             throw new TehutiException("Error creating mbean attribute " + metric.name(), e);
         }
     }
 
     public void close() {
         synchronized () {
             for (TehutiMbean mbean : this..values())
                 unregister(mbean);
         }
     }
    private void unregister(TehutiMbean mbean) {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        try {
            if (server.isRegistered(mbean.name()))
                server.unregisterMBean(mbean.name());
        } catch (JMException e) {
            throw new TehutiException("Error unregistering mbean"e);
        }
    }
    private void reregister(TehutiMbean mbean) {
        unregister(mbean);
        try {
            ManagementFactory.getPlatformMBeanServer().registerMBean(mbeanmbean.name());
        } catch (JMException e) {
            throw new TehutiException("Error registering mbean " + mbean.name(), e);
        }
    }
    private String[] split(String name) {
        int attributeStart = name.lastIndexOf('.');
        if (attributeStart < 0)
            throw new IllegalArgumentException("No MBean name in metric name: " + name);
        String attributeName = name.substring(attributeStart + 1, name.length());
        String remainder = name.substring(0, attributeStart);
        int beanStart = remainder.lastIndexOf('.');
        if (beanStart < 0)
            return new String[] { ""remainderattributeName };
        String packageName = remainder.substring(0, beanStart);
        String beanName = remainder.substring(beanStart + 1, remainder.length());
        return new String[] { packageNamebeanNameattributeName };
    }
    private static class TehutiMbean implements DynamicMBean {
        private final String beanName;
        private final ObjectName objectName;
        private final Map<StringTehutiMetricmetrics;
        public TehutiMbean(String packageNameString beanNamethrows MalformedObjectNameException {
            this. = beanName;
            this. = new HashMap<StringTehutiMetric>();
            this. = new ObjectName(packageName + ":type=" + beanName);
        }
        public ObjectName name() {
            return ;
        }
        public void setAttribute(String nameTehutiMetric metric) {
            this..put(namemetric);
        }
        @Override
            if (this..containsKey(name))
                return this..get(name).value();
            else
                throw new AttributeNotFoundException("Could not find attribute " + name);
        }
        @Override
        public AttributeList getAttributes(String[] names) {
            try {
                AttributeList list = new AttributeList();
                for (String name : names)
                    list.add(new Attribute(namegetAttribute(name)));
                return list;
            } catch (Exception e) {
                .error("Error getting JMX attribute: "e);
                return new AttributeList();
            }
        }
        @Override
        public MBeanInfo getMBeanInfo() {
            MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[.size()];
            int i = 0;
            for (Map.Entry<StringTehutiMetricentry : this..entrySet()) {
                String attribute = entry.getKey();
                TehutiMetric metric = entry.getValue();
                attrs[i] = new MBeanAttributeInfo(attributedouble.class.getName(), metric.description(), truefalsefalse);
                i += 1;
            }
            return new MBeanInfo(""attrsnullnullnull);
        }
        @Override
        public Object invoke(String nameObject[] paramsString[] sigthrows MBeanExceptionReflectionException {
            throw new UnsupportedOperationException("Set not allowed.");
        }
        @Override
        public void setAttribute(Attribute attributethrows AttributeNotFoundException,
                                                     InvalidAttributeValueException,
                                                     MBeanException,
                                                     ReflectionException {
            throw new UnsupportedOperationException("Set not allowed.");
        }
        @Override
        public AttributeList setAttributes(AttributeList list) {
            throw new UnsupportedOperationException("Set not allowed.");
        }
    }
New to GrepCode? Check out our FAQ X