Package com.palominolabs.metrics.guice

Source Code of com.palominolabs.metrics.guice.GaugeListener

package com.palominolabs.metrics.guice;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Gauge;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

import java.lang.reflect.Method;

/**
* A listener which adds gauge injection listeners to classes with gauges.
*/
public class GaugeListener implements TypeListener {
    static final String GAUGE_SUFFIX = "gauge";
    private final MetricRegistry metricRegistry;

    public GaugeListener(MetricRegistry metricRegistry) {
        this.metricRegistry = metricRegistry;
    }

    @Override
    public <I> void hear(final TypeLiteral<I> literal, TypeEncounter<I> encounter) {
        Class<? super I> klass = literal.getRawType();
        for (final Method method : klass.getMethods()) {
            final Gauge annotation = method.getAnnotation(Gauge.class);
            if (annotation != null) {
                if (method.getParameterTypes().length == 0) {
                    final String metricName = determineName(annotation, klass, method);
                    encounter.register(new GaugeInjectionListener<I>(metricRegistry,
                        metricName,
                        method));
                } else {
                    encounter.addError("Method %s is annotated with @Gauge but requires parameters.",
                                       method);
                }
            }
        }
    }

    private static String determineName(Gauge annotation, Class<?> klass, Method method) {
        if (annotation.absolute()) {
            return annotation.name();
        }

        if (annotation.name().isEmpty()) {
            return MetricRegistry.name(klass, method.getName(), GAUGE_SUFFIX);
        }

        return MetricRegistry.name(klass, annotation.name());
    }

}
TOP

Related Classes of com.palominolabs.metrics.guice.GaugeListener

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.