1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.omid.metrics;
19
20 import org.apache.phoenix.thirdparty.com.google.common.base.Optional;
21
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26
27 public class MetricsRegistryMap {
28
29 private final ConcurrentMap<String, Metric> metrics = new ConcurrentHashMap<>();
30
31 interface MetricBuilder<T extends Metric> {
32
33 MetricBuilder<Gauge<? extends Number>> GAUGES = new MetricBuilder<Gauge<? extends Number>>() {
34 @Override
35 public boolean isInstance(Metric metric) {
36 return Gauge.class.isInstance(metric);
37 }
38 };
39
40 MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() {
41 @Override
42 public boolean isInstance(Metric metric) {
43 return Counter.class.isInstance(metric);
44 }
45 };
46
47 MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() {
48 @Override
49 public boolean isInstance(Metric metric) {
50 return Timer.class.isInstance(metric);
51 }
52 };
53
54 MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() {
55 @Override
56 public boolean isInstance(Metric metric) {
57 return Meter.class.isInstance(metric);
58 }
59 };
60
61 MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() {
62 @Override
63 public boolean isInstance(Metric metric) {
64 return Histogram.class.isInstance(metric);
65 }
66 };
67
68 boolean isInstance(Metric metric);
69 }
70
71 public Optional<? extends Metric> get(final String name,
72 MetricBuilder<? extends Metric> builder,
73 Class<? extends Metric> type) {
74
75 final Metric metric = metrics.get(name);
76 if (builder.isInstance(metric)) {
77 return Optional.of(type.cast(metric));
78 }
79 return Optional.absent();
80
81 }
82
83 @SuppressWarnings("unchecked")
84 public <T extends Metric, U extends Number> List<Gauge<U>> getGauges() {
85 List<Gauge<U>> gaugesList = new ArrayList<>();
86 for (Metric metric : metrics.values()) {
87 if (metric instanceof Gauge) {
88 gaugesList.add((Gauge<U>) metric);
89 }
90 }
91 return gaugesList;
92 }
93
94 public void register(String name, Metric metric) throws IllegalArgumentException {
95 final Metric existing = metrics.putIfAbsent(name, metric);
96 if (existing != null) {
97 throw new IllegalArgumentException("A metric named " +
98 name +
99 " of class " +
100 metric.getClass().getCanonicalName() +
101 " already exists");
102 }
103 }
104
105 }