1 package com.github.triceo.splitlog;
2
3 import java.util.HashSet;
4
5 import org.apache.commons.collections4.BidiMap;
6 import org.apache.commons.collections4.bidimap.DualHashBidiMap;
7
8 import com.github.triceo.splitlog.api.Message;
9 import com.github.triceo.splitlog.api.MessageDeliveryStatus;
10 import com.github.triceo.splitlog.api.MessageMeasure;
11 import com.github.triceo.splitlog.api.MessageMetric;
12 import com.github.triceo.splitlog.api.MessageMetricProducer;
13 import com.github.triceo.splitlog.api.MessageSource;
14
15 final class MessageMetricManager implements MessageMetricProducer, MessageListener<MessageSource> {
16
17 private final BidiMap<String, DefaultMessageMetric<? extends Number>> metrics = new DualHashBidiMap<String, DefaultMessageMetric<? extends Number>>();
18
19 @Override
20 public synchronized MessageMetric<? extends Number> getMetric(final String id) {
21 return this.metrics.get(id);
22 }
23
24 @Override
25 public synchronized String getMetricId(final MessageMetric<? extends Number> measure) {
26 return this.metrics.getKey(measure);
27 }
28
29 @Override
30 public boolean isMeasuring(final MessageMetric<? extends Number> metric) {
31 return this.metrics.containsValue(metric);
32 }
33
34 @Override
35 public boolean isMeasuring(final String id) {
36 return this.metrics.containsKey(id);
37 }
38
39 @Override
40 public synchronized void messageReceived(final Message msg, final MessageDeliveryStatus status,
41 final MessageSource source) {
42 for (final DefaultMessageMetric<? extends Number> metric : this.metrics.values()) {
43 metric.messageReceived(msg, status, source);
44 }
45 }
46
47 @Override
48 public synchronized <T extends Number> MessageMetric<T> startMeasuring(final MessageMeasure<T> measure,
49 final String id) {
50 if (measure == null) {
51 throw new IllegalArgumentException("Measure may not be null.");
52 } else if (id == null) {
53 throw new IllegalArgumentException("ID may not be null.");
54 } else if (this.metrics.containsKey(id)) {
55 throw new IllegalArgumentException("Duplicate ID:" + id);
56 }
57 final DefaultMessageMetric<T> metric = new DefaultMessageMetric<T>(measure);
58 this.metrics.put(id, metric);
59 return metric;
60 }
61
62 @Override
63 public synchronized boolean stopMeasuring(final MessageMetric<? extends Number> measure) {
64 final String removed = this.metrics.removeValue(measure);
65 return (removed != null);
66 }
67
68 @Override
69 public synchronized boolean stopMeasuring(final String id) {
70 final MessageMetric<? extends Number> removed = this.metrics.remove(id);
71 return (removed != null);
72 }
73
74
75
76
77
78 public synchronized void terminateMeasuring() {
79 for (final String metricId : new HashSet<String>(this.metrics.keySet())) {
80 this.stopMeasuring(metricId);
81 }
82 }
83
84 }